|
1
|
|
|
<?php
|
|
2
|
|
|
namespace Seufert\Hamle;
|
|
3
|
|
|
|
|
4
|
|
|
use Seufert\Hamle\Exception\OutOfScope;
|
|
5
|
|
|
use Seufert\Hamle\Exception\Unsupported;
|
|
6
|
|
|
use Seufert\Hamle\Exception\RunTime;
|
|
7
|
|
|
use Seufert\Hamle\Model;
|
|
8
|
|
|
|
|
9
|
|
|
/**
|
|
10
|
|
|
* HAMLE Controller/Model Scope Handler
|
|
11
|
|
|
*
|
|
12
|
|
|
* @author Chris Seufert <[email protected]>
|
|
13
|
|
|
*/
|
|
14
|
|
|
class Scope {
|
|
15
|
|
|
/** @var Model[] Array of Models by Scope Order */
|
|
16
|
|
|
static $scopes = array();
|
|
17
|
|
|
/** @var Model[] Assoc array of Models by Scope Name */
|
|
18
|
|
|
static $namedScopes = array();
|
|
19
|
|
|
|
|
20
|
|
|
static function add($model, $name = null) {
|
|
21
|
|
|
if (!$model instanceOf Model)
|
|
22
|
|
|
throw new Unsupported("Unsupported Model (".get_class($model)."), Needs to implement hamleModel Interface");
|
|
23
|
|
|
if ($name)
|
|
24
|
|
|
self::$namedScopes[$name] = $model;
|
|
25
|
|
|
else
|
|
26
|
|
|
self::$scopes[] = $model;
|
|
27
|
|
|
}
|
|
28
|
|
|
|
|
29
|
|
|
static function done() {
|
|
30
|
|
|
array_pop(self::$scopes);
|
|
31
|
|
|
}
|
|
32
|
|
|
|
|
33
|
|
|
/**
|
|
34
|
|
|
* Get arbitary scope
|
|
35
|
|
|
* 0 = current
|
|
36
|
|
|
* negative vals = back form here, -1 = last, -2 one before last, etc
|
|
37
|
|
|
* positive vals = absolute position, 1 = first, 2 = second, etc
|
|
38
|
|
|
* @param int $id ID of scope to get
|
|
39
|
|
|
* @return Model
|
|
40
|
|
|
* @throws OutOfScope
|
|
41
|
|
|
*/
|
|
42
|
|
|
static function get($id = 0) {
|
|
43
|
|
|
if (0 == $id) {
|
|
44
|
|
|
if ($scope = end(self::$scopes))
|
|
45
|
|
|
return $scope;
|
|
46
|
|
|
throw new OutOfScope("Unable to find Scope ($id)");
|
|
47
|
|
|
}
|
|
48
|
|
|
$key = $id - 1;
|
|
49
|
|
|
if ($id < 0) $key = count(self::$scopes) + $id - 1;
|
|
50
|
|
|
if ($id == 0) $key = count(self::$scopes) - 1;
|
|
51
|
|
|
if (!isset(self::$scopes[$key]))
|
|
52
|
|
|
throw new OutOfScope("Unable to find Scope ($id) or $key");
|
|
53
|
|
|
return self::$scopes[$key];
|
|
54
|
|
|
}
|
|
55
|
|
|
|
|
56
|
|
|
static function getTopScope() {
|
|
57
|
|
|
return end(self::$scopes);
|
|
58
|
|
|
}
|
|
59
|
|
|
static function getDepth() {
|
|
60
|
|
|
return count(self::$scopes);
|
|
61
|
|
|
}
|
|
62
|
|
|
|
|
63
|
|
|
static $returnZeroOnNoScope = false;
|
|
64
|
|
|
|
|
65
|
|
|
static function getName($name) {
|
|
66
|
|
|
if ($name && isset(self::$namedScopes[$name])) {
|
|
67
|
|
|
self::$namedScopes[$name]->rewind();
|
|
68
|
|
|
return self::$namedScopes[$name];
|
|
69
|
|
|
} else
|
|
70
|
|
|
if(self::$returnZeroOnNoScope)
|
|
71
|
|
|
return new Model\Zero();
|
|
72
|
|
|
throw new RunTime("Unable to find scope ($name)");
|
|
73
|
|
|
}
|
|
74
|
|
|
|
|
75
|
|
|
}
|
|
76
|
|
|
|