Do not crash list view when seeing a fully empty git repository
[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         array_walk(
20             $dirs,
21             function ($dir) {
22                 return substr($dir, 0, -4);
23             }
24         );
25         sort($dirs, SORT_NUMERIC);
26         $n = end($dirs) + 1;
27
28         chdir($this->workDir);
29         $dir = $this->workDir . '/' . $n . '/';
30         mkdir($dir, 0777);//FIXME
31         $r = new Repository();
32         $r->id = $n;
33         $r->workDir = $dir;
34         $r->gitDir = $this->gitDir . '/' . $n . '.git/';
35         mkdir($r->gitDir, 0777);//FIXME
36
37         return $r;
38     }
39
40     /**
41      * Get a list of repository objects
42      *
43      * @param integer $page    Page number, beginning with 0, or "last"
44      * @param integer $perPage Number of repositories per page
45      *
46      * @return array Array of Repositories first, number of repositories second
47      */
48     public function getList($page = 0, $perPage = 10)
49     {
50         chdir($this->gitDir);
51         $dirs = glob('*.git', GLOB_ONLYDIR);
52         sort($dirs, SORT_NUMERIC);
53         if ($page === 'last') {
54             //always show the last 10
55             $page = intval(count($dirs) / $perPage);
56             $start = count($dirs) - $perPage;
57             if ($start < 0) {
58                 $start = 0;
59             }
60             $some = array_slice($dirs, $start, $perPage);
61         } else {
62             $some = array_slice($dirs, $page * $perPage, $perPage);
63         }
64
65         $repos = array();
66         foreach ($some as $oneDir) {
67             $r = new Repository();
68             try {
69                 $r->loadById(substr($oneDir, 0, -4));
70             } catch (\VersionControl_Git_Exception $e) {
71                 if (strpos($e->getMessage(), 'does not have any commits') !== false) {
72                     //the git repo is broken as the initial commit
73                     // has not been finished
74                     continue;
75                 }
76                 throw $e;
77             }
78             $repos[] = $r;
79         }
80         return array($repos, count($dirs), $page);
81     }
82 }
83
84 ?>