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