<?php
/*
* This file is part of the Gitter library.
*
* (c) Klaus Silveira <klaussilveira@php.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Gitter\Model;
use Gitter\Repository;
use function Stringy\create;
use Stringy\Stringy as S;
class Tree extends Item implements \RecursiveIterator
{
protected $data;
protected $position = 0;
private $submodules = null;
public function __construct($hash, Repository $repository)
{
$this->setHash($hash);
$this->setRepository($repository);
}
private function getSubmodules($files, $hash) {
if ($this->submodules === null) {
foreach ($files as $file) {
if ($file[4] === '.gitmodules') {
$branch = $hash;
$gitsubmodule = $this->getRepository()->getBlob("$branch:\"$file[4]\"")->output();
$this->submodules = parse_ini_string($gitsubmodule, true);
}
}
if ($this->submodules === null && strpos($hash, ':') !== false) {
// Search in root folder
$data = $this->getRepository()->getClient()->run($this->getRepository(), 'ls-tree -lz ' . explode(':', $hash)[0]);
$lines = explode("\0", $data);
$rootFolderFiles = array();
$root = array();
foreach ($lines as $key => $line) {
if (empty($line)) {
unset($lines[$key]);
continue;
}
$rootFolderFiles[] = preg_split("/[\s]+/", $line, 5);
}
$this->submodules = $this->getSubmodules($rootFolderFiles, explode(':', $hash)[0]);
}
}
return $this->submodules;
}
public function parse()
{
$data = $this->getRepository()->getClient()->run($this->getRepository(), 'ls-tree -lz ' . $this->getHash());
$lines = explode("\0", $data);
$files = array();
$root = array();
foreach ($lines as $key => $line) {
if (empty($line)) {
unset($lines[$key]);
continue;
}
$files[] = preg_split("/[\s]+/", $line, 5);
}
foreach ($files as $file) {
// submodule
if ($file[0] == '160000') {
$submodules = $this->getSubmodules($files, $this->getHash());
if (strpos($this->getHash(), ':') === false) {
$submoduleName = $file[4];
}
else {
$submoduleName = str_replace('"', '', explode(':', $this->getHash())[1]) . "$file[4]";
}
$shortHash = $this->getRepository()->getShortHash($file[2]);
$tree = new Module;
$tree->setMode($file[0]);
$tree->setName($file[4]);
$tree->setHash($file[2]);
$tree->setShortHash($shortHash);