c6059961a3f6ed2b2124276729698ab4ef46fd37
[phorkie.git] / src / phorkie / Repositories.php
1 <?php
2 namespace phorkie;
3
4 class Repositories
5 {
6     public function __construct()
7     {
8         $this->workDir = $GLOBALS['phorkie']['cfg']['workdir'];
9         $this->gitDir  = $GLOBALS['phorkie']['cfg']['gitdir'];
10     }
11
12     /**
13      * @return Repository
14      */
15     public function createNew()
16     {
17         chdir($this->gitDir);
18         $dirs = glob('*.git', GLOB_ONLYDIR);
19         foreach ($dirs as $key => $dir) {
20             $dirs[$key] = substr($dir, 0, -4);
21         }
22         sort($dirs, SORT_NUMERIC);
23
24         if ($GLOBALS['phorkie']['cfg']['randomIds']) {
25             $n = end($dirs) + mt_rand(65536, 16777216);
26         } else {
27             $n = end($dirs) + 1;
28         }
29
30         chdir($this->workDir);
31         $dir = $this->workDir . '/' . $n . '/';
32         mkdir($dir, fileperms($this->workDir) & 0777);
33         $r = new Repository();
34         $r->id = $n;
35         $r->workDir = $dir;
36         $r->gitDir = $this->gitDir . '/' . $n . '.git/';
37         mkdir($r->gitDir, fileperms($this->gitDir) & 0777);
38
39         return $r;
40     }
41
42     /**
43      * Get a list of repository objects
44      *
45      * @param integer $page    Page number, beginning with 0, or "last"
46      * @param integer $perPage Number of repositories per page
47      *
48      * @return array Array of Repositories first, number of repositories second
49      */
50     public function getList($page = 0, $perPage = 10)
51     {
52         chdir($this->gitDir);
53         $dirs = glob('*.git', GLOB_ONLYDIR);
54         sort($dirs, SORT_NUMERIC);
55         if ($page === 'last') {
56             //always show the last 10
57             $page = intval(count($dirs) / $perPage);
58             $start = count($dirs) - $perPage;
59             if ($start < 0) {
60                 $start = 0;
61             }
62             $some = array_slice($dirs, $start, $perPage);
63         } else {
64             $some = array_slice($dirs, $page * $perPage, $perPage);
65         }
66
67         $repos = array();
68         foreach ($some as $oneDir) {
69             $r = new Repository();
70             try {
71                 $r->loadById(substr($oneDir, 0, -4));
72             } catch (\VersionControl_Git_Exception $e) {
73                 if (strpos($e->getMessage(), 'does not have any commits') !== false) {
74                     //the git repo is broken as the initial commit
75                     // has not been finished
76                     continue;
77                 }
78                 throw $e;
79             }
80             $repos[] = $r;
81         }
82         return array($repos, count($dirs), $page);
83     }
84 }
85
86 ?>