1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: class NPresenterLoader implements IPresenterLoader
21: {
22:
23: public $caseSensitive = FALSE;
24:
25:
26: private $baseDir;
27:
28:
29: private $cache = array();
30:
31:
32:
33: 34: 35:
36: public function __construct($baseDir)
37: {
38: $this->baseDir = $baseDir;
39: }
40:
41:
42:
43: 44: 45: 46: 47:
48: public function getPresenterClass(& $name)
49: {
50: if (isset($this->cache[$name])) {
51: list($class, $name) = $this->cache[$name];
52: return $class;
53: }
54:
55: if (!is_string($name) || !NString::match($name, "#^[a-zA-Z\x7f-\xff][a-zA-Z0-9\x7f-\xff:]*$#")) {
56: throw new NInvalidPresenterException("Presenter name must be alphanumeric string, '$name' is invalid.");
57: }
58:
59: $class = $this->formatPresenterClass($name);
60:
61: if (!class_exists($class)) {
62: 63: $file = $this->formatPresenterFile($name);
64: if (is_file($file) && is_readable($file)) {
65: NLimitedScope::load($file);
66: }
67:
68: if (!class_exists($class)) {
69: throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' was not found in '$file'.");
70: }
71: }
72:
73: $reflection = new NClassReflection($class);
74: $class = $reflection->getName();
75:
76: if (!$reflection->implementsInterface('IPresenter')) {
77: throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is not Nette\\Application\\IPresenter implementor.");
78: }
79:
80: if ($reflection->isAbstract()) {
81: throw new NInvalidPresenterException("Cannot load presenter '$name', class '$class' is abstract.");
82: }
83:
84: 85: $realName = $this->unformatPresenterClass($class);
86: if ($name !== $realName) {
87: if ($this->caseSensitive) {
88: throw new NInvalidPresenterException("Cannot load presenter '$name', case mismatch. Real name is '$realName'.");
89: } else {
90: $this->cache[$name] = array($class, $realName);
91: $name = $realName;
92: }
93: } else {
94: $this->cache[$name] = array($class, $realName);
95: }
96:
97: return $class;
98: }
99:
100:
101:
102: 103: 104: 105: 106:
107: public function formatPresenterClass($presenter)
108: {
109: return strtr($presenter, ':', '_') . 'Presenter';
110: return str_replace(':', 'Module\\', $presenter) . 'Presenter';
111: }
112:
113:
114:
115: 116: 117: 118: 119:
120: public function unformatPresenterClass($class)
121: {
122: return strtr(substr($class, 0, -9), '_', ':');
123: return str_replace('Module\\', ':', substr($class, 0, -9));
124: }
125:
126:
127:
128: 129: 130: 131: 132:
133: public function formatPresenterFile($presenter)
134: {
135: $path = '/' . str_replace(':', 'Module/', $presenter);
136: return $this->baseDir . substr_replace($path, '/presenters', strrpos($path, '/'), 0) . 'Presenter.php';
137: }
138:
139: }
140: