summaryrefslogtreecommitdiffstats
path: root/3rdparty/granite/git/object/loose.php
blob: 32f894845b9902f6925514de1d7ca3cbc60a42ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/**
 * Loose - provides a 'loose object' object
 *
 * PHP version 5.3
 *
 * @category Git
 * @package  Granite
 * @author   Craig Roberts <craig0990@googlemail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT Expat License
 * @link     http://craig0990.github.com/Granite/
 */

namespace Granite\Git\Object;
use \UnexpectedValueException as UnexpectedValueException;

/**
 * Loose represents a loose object in the Git repository
 *
 * @category Git
 * @package  Granite
 * @author   Craig Roberts <craig0990@googlemail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT Expat License
 * @link     http://craig0990.github.com/Granite/
 */
class Loose extends Raw
{

    /**
     * Reads an object from a loose object file based on the SHA-1 id
     *
     * @param string $path The path to the repository root
     * @param string $sha  The SHA-1 id of the requested object
     *
     * @throws UnexpectedValueException If the type is not 'commit', 'tree',
     * 'tag' or 'blob'
     */
    public function __construct($path, $sha)
    {
        $this->sha = $sha;

        $loose_path = $path
                      . 'objects/'
                      . substr($sha, 0, 2)
                      . '/'
                      . substr($sha, 2);

        if (!file_exists($loose_path)) {
            throw new InvalidArgumentException("Cannot open loose object file for $sha");
        }

        $raw = gzuncompress(file_get_contents($loose_path));
        $data = explode("\0", $raw, 2);

        $header = $data[0];
        $this->content = $data[1];

        list($this->type, $this->size) = explode(' ', $header);

        switch ($this->type) {
            case 'commit':
                $this->type = Raw::OBJ_COMMIT;
            break;
            case 'tree':
                $this->type = Raw::OBJ_TREE;
            break;
            case 'blob':
                $this->type = Raw::OBJ_BLOB;
            break;
            case 'tag':
                $this->type = Raw::OBJ_TAG;
            break;
            default:
                throw new UnexpectedValueException(
                     "Unexpected type '{$this->type}'"
                );
            break;
        }
    }

}