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