Fix bug in Git_Tree::construct() involving array paths.
[phpgit.git] / library / Git / Tree.php
blobe3017359470852f156624a11b145564546f5d96f
1 <?php
3 /**
4 * Represents a tree file structure in Git.
5 */
6 class Git_Tree extends Git_Lazy {
7 /**
8 * Instance of Git_Repo.
9 */
10 public $repo;
11 /**
12 * Treeish identifier of the tree. Can be a SHA-1 sum.
14 protected $id;
15 protected $mode;
16 protected $name;
17 protected $contents;
18 public function __construct($repo, $kwargs = array()) {
19 $this->repo = $repo;
20 foreach ($kwargs as $k => $v) {
21 $this->$k = $v;
24 /**
25 * Lazy loads the tree's contents.
27 protected function bake() {
28 $tmp = Git_Tree::construct($this->repo, $this->id);
29 $this->contents = $tmp->contents;
31 /**
32 * Constructs and fully initializes a tree.
34 public static function construct($repo, $treeish, $paths = array()) {
35 $output = $repo->git->__call('lsTree', array_merge($paths, array($treeish)));
36 $tree = new Git_Tree($repo, array('id' => $treeish));
37 $tree->constructInitialize($repo, $treeish, $output);
38 return $tree;
40 /**
41 * Initializes a tree object based on the output of the ls-tree command.
43 public function constructInitialize($repo, $id, $text) {
44 $this->repo = $repo;
45 $this->id = $id;
46 $this->contents = array();
47 foreach (explode("\n", $text) as $line) {
48 $out = self::contentFromString($repo, $line);
49 if (!$out) continue;
50 $this->contents[] = $out;
52 $this->markBaked();
54 /**
55 * Creates a content object (blob or tree) based on the ls-tree command.
57 public function contentFromString($repo, $text) {
58 $text = str_replace("\t", ' ', $text);
59 $bits = explode(' ', $text);
60 if (count($bits) != 4) return;
61 list($mode, $type, $id, $name) = $bits;
62 switch ($type) {
63 case 'tree':
64 return new Git_Tree($repo, compact('id', 'mode', 'name'));
65 case 'blob':
66 return new Git_Blob($repo, compact('id', 'mode', 'name'));
67 case 'commit':
68 return;
69 default:
70 throw new Git_Exception('Invalid type: ' . $type);
73 /**
74 * Retrieves a named object in this tree's contents.
75 * @param Filename of object to return. This function does NOT search
76 * recursively.
77 * @return Null if file not found, otherwise Git_Tree or Git_Commit file.
79 public function get($file) {
80 foreach ($this->contents as $c) {
81 if ($c->name == $file) return $c;
84 /**
85 * Retrieves the basename of this tree.
87 public function basename() {
88 return basename($this->__get('name'));
90 public function __toString() {
91 return '(Git_Tree "'.$this->id.'")';