|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace mindplay\kisstpl; |
|
4
|
|
|
|
|
5
|
|
|
use RuntimeException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Simple view-finder implementation - maps a namespace directly to a root path |
|
9
|
|
|
* and assumes that the template exists. |
|
10
|
|
|
*/ |
|
11
|
|
|
class SimpleViewFinder implements ViewFinder |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var string absolute path to the view root-folder for the base namespace |
|
15
|
|
|
*/ |
|
16
|
|
|
public $root_path; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var string|null base namespace for view-models supported by this finder |
|
20
|
|
|
*/ |
|
21
|
|
|
public $namespace = null; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param string $root_path absolute path to view root-folder |
|
25
|
|
|
* @param string|null $namespace optional; base namespace for view-models supported by this finder |
|
26
|
|
|
*/ |
|
27
|
1 |
|
public function __construct($root_path, $namespace = null) |
|
28
|
|
|
{ |
|
29
|
1 |
|
$this->root_path = rtrim($root_path, DIRECTORY_SEPARATOR); |
|
30
|
1 |
|
$this->namespace = $namespace; |
|
31
|
1 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritdoc} |
|
35
|
|
|
* |
|
36
|
|
|
* @see ViewFinder::findTemplate() |
|
37
|
|
|
*/ |
|
38
|
1 |
|
public function findTemplate($view_model, $type) |
|
39
|
|
|
{ |
|
40
|
1 |
|
$name = $this->getTemplateName($view_model); |
|
41
|
|
|
|
|
42
|
1 |
|
return $name |
|
43
|
1 |
|
? $this->root_path . DIRECTORY_SEPARATOR . $name . ".{$type}.php" |
|
44
|
1 |
|
: null; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* {@inheritdoc} |
|
49
|
|
|
* |
|
50
|
|
|
* @see ViewFinder::listSearchPaths() |
|
51
|
|
|
*/ |
|
52
|
1 |
|
public function listSearchPaths($view_model, $type) |
|
53
|
|
|
{ |
|
54
|
1 |
|
return array_filter(array($this->findTemplate($view_model, $type))); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param object $view_model view-model |
|
59
|
|
|
* |
|
60
|
|
|
* @return string|null template name (e.g. "Bar/Baz" for class Foo\Bar\Baz if $namespace is 'Foo') |
|
61
|
|
|
* |
|
62
|
|
|
* @throws RuntimeException if the given view-model doesn't belong to the base namespace |
|
63
|
|
|
* |
|
64
|
|
|
* @see ViewFinder::findTemplate() |
|
65
|
|
|
*/ |
|
66
|
1 |
|
protected function getTemplateName($view_model) |
|
67
|
|
|
{ |
|
68
|
1 |
|
$name = get_class($view_model); |
|
69
|
|
|
|
|
70
|
1 |
|
if ($this->namespace !== null) { |
|
71
|
1 |
|
$prefix = $this->namespace . '\\'; |
|
72
|
1 |
|
$length = strlen($prefix); |
|
73
|
|
|
|
|
74
|
1 |
|
if (strncmp($name, $prefix, $length) !== 0) { |
|
75
|
1 |
|
return null; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
1 |
|
$name = substr($name, $length); // trim namespace prefix from class-name |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
1 |
|
return strtr($name, '\\', '/'); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|