Rewrite of initInstance(), more eval() rewritten to call_user_func_array()
[shipsimu.git] / inc / loader / class_ClassLoader.php
1 <?php
2 /**
3  * This class loads class include files with a specific prefix and suffix
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright(c) 2007, 2008 Roland Haeder, this is free software
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  *
24  * ----------------------------------
25  * 1.1
26  *  - loadClasses rewritten to fix some notices
27  * 1.0
28  *  - Initial release
29  * ----------------------------------
30  */
31 class ClassLoader {
32         /**
33          * Configuration array
34          */
35         private $cfg = array();
36
37         /**
38          * An ArrayObject for found classes
39          */
40         private $classes = null;
41
42         /**
43          * Suffix with extension for all class files
44          */
45         private $prefix = "class_";
46
47         /**
48          * Suffix with extension for all class files
49          */
50         private $suffix = ".php";
51
52         /**
53          * Length of the suffix. Will be overwritten later.
54          */
55         private $sufLen = 0;
56
57         /**
58          * Length of the prefix. Will be overwritten later.
59          */
60         private $preLen = 0;
61
62         /**
63          * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
64          * @see scanLocalPath
65          */
66         private $ignoreList = array();
67
68         /**
69          * An ArrayList object for include directories
70          */
71         private $dirList = null;
72
73         /**
74          * Debug this class loader? (true = yes, false = no)
75          */
76         private $debug = false;
77
78         /**
79          * Counter for scanned directories (debug output)
80          */
81         private $dirCnt = 0;
82
83         /**
84          * Counter for loaded classes (debug output)
85          */
86         private $classCnt = 0;
87
88         /**
89          * Instance of this class
90          */
91         private static $selfInstance = null;
92
93         /**
94          * The *public* constructor
95          *
96          * @param               $cfgInstance            Configuration class instance
97          * @return      void
98          */
99         public function __construct (FrameworkConfiguration $cfgInstance) {
100                 // Init the array list
101                 $this->dirList = new ArrayObject();
102
103                 // Set suffix and prefix from configuration
104                 $this->suffix = $cfgInstance->readConfig('class_suffix');
105                 $this->prefix = $cfgInstance->readConfig('class_prefix');
106
107                 // Estimate length of prefix and suffix for substr() function (cache)
108                 $this->sufLen = strlen($this->suffix);
109                 $this->preLen = strlen($this->prefix);
110
111                 // Set configuration instance
112                 $this->cfgInstance = $cfgInstance;
113
114                 // Initialize the classes list
115                 $this->classes = new ArrayObject();
116
117                 // Set own instance
118                 self::$selfInstance = $this;
119         }
120
121         /**
122          * Getter for an instance of this class
123          *
124          * @return      $selfInstance           An instance of this class
125          */
126         public final static function getInstance () {
127                 // Is the instance there?
128                 if (is_null(self::$selfInstance)) {
129                         // Get a new one
130                         self::$selfInstance = new ClassLoader(FrameworkConfiguration::getInstance());
131                 } // END - if
132
133                 // Return the instance
134                 return self::$selfInstance;
135         }
136
137         /**
138          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
139          *
140          * @param               $basePath               The relative base path to PATH constant for all classes
141          * @param               $ignoreList     An optional list (array or string) of directory names which shall be ignored
142          * @return      void
143          */
144         public function loadClasses ($basePath, $ignoreList = array() ) {
145                 // Convert string to array
146                 if (!is_array($ignoreList)) $ignoreList = array($ignoreList);
147
148                 // Directories which our class loader ignores by default while
149                 // deep-scanning the directory structure. See scanLocalPath() for
150                 // details.
151                 $ignoreList[] = ".";
152                 $ignoreList[] = "..";
153                 $ignoreList[] = ".htaccess";
154                 $ignoreList[] = ".svn";
155
156                 // Keep it in class for later usage
157                 $this->ignoreList = $ignoreList;
158
159                 // Set base directory which holds all our classes, we should use an
160                 // absolute path here so is_dir(), is_file() and so on will always
161                 // find the correct files and dirs.
162                 $basePath2 = realpath($basePath);
163
164                 // If the basePath is false it is invalid
165                 if ($basePath2 === false) {
166                         // TODO: Do not die here.
167                         die("Cannot read {$basePath} !");
168                 } else {
169                         // Set base path
170                         $basePath = $basePath2;
171                 }
172
173                 // Load all super classes (backward, why ever this name... :-? )
174                 // We don't support sub directories here...
175                 $this->scanLocalPath($basePath);
176
177                 // While there are directories in our list scan them for classes
178                 $cnt = 0;
179                 while ($cnt != $this->dirList->count()) {
180                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
181                                 // Get current path
182                                 $currPath = $idx->current();
183
184                                 // Remove the current entry or else this will lead into a infinite loop
185                                 $this->dirList->offsetSet($idx->key(), "");
186
187                                 // Scan the directory
188                                 $this->scanLocalPath($currPath);
189                         } // END - for
190
191                         // Check if we can leave
192                         $cnt = 0;
193                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
194                                 if ($idx->current() == "") $cnt++;
195                         } // END - for
196                 } // END - while
197         }
198
199         /**
200         * The local path scanner. A found class will be loaded immediately
201         * @param                $localPath      The local path which shall be recursively scanned for include files
202         * @return               void
203         */
204         private function scanLocalPath ($localPath) {
205                 // Empty path names will be silently ignored
206                 if (empty($localPath)) return;
207
208                 // TODO: No dies here, mayybe this should be rewritten to throw an exception?
209                 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($localPath);
210                 while ($dirClass = $dirInstance->readDirectoryExcept($this->ignoreList)) {
211                         // We need the relative dir name as an array index some lines below
212                         $dirClass2 = $dirClass;
213
214                         // A nice replacement for a simple dot ;)
215                         $dirClass = sprintf("%s/%s", $localPath, $dirClass);
216
217                         // Is a readable file with configured prefix and suffix? All other
218                         // files will silently be ignored!
219                         //* DEBUG: */ print "Prefix=".$this->prefix."(".substr($dirClass2, 0 , $this->preLen).")\n";
220                         //* DEBUG: */ print "Suffix=".$this->suffix."(".substr($dirClass2, -$this->sufLen, $this->sufLen).")\n";
221                         //* DEBUG: */ print "ENTRY={$dirClass}\n";
222                         if (
223                                  (is_file($dirClass))
224                         && (is_readable($dirClass))
225                         && (substr($dirClass2, 0 , $this->preLen) == $this->prefix)
226                         && (substr($dirClass2, -$this->sufLen, $this->sufLen) == $this->suffix)
227                         ) {
228                                 // Class found so load it instantly
229                                 //* DEBUG: */ print "CLASS={$dirClass}\n";
230                                 $this->classes->append($dirClass);
231                                 $this->classCnt++;
232                         } elseif (is_dir($dirClass) && !in_array($dirClass2, $this->ignoreList)) {
233                                 // Directory found and added to list
234                                 //* DEBUG: */ print "DIR={$dirClass}\n";
235                                 $this->dirList->append($dirClass);
236                                 $this->dirCnt++;
237                         }
238                         //* DEBUG: */ print "LOOP!\n";
239                 } // END - while
240
241                 // Close directory handler
242                 $dirInstance->closeDirectory();
243                 unset($dirInstance);
244
245                 // Output counter in debug mode
246                 if (defined('DEBUG_MODE')) print(sprintf("[%s:] <strong>%d</strong> Klassendateien in <strong>%d</strong> Verzeichnissen gefunden und geladen.<br />\n",
247                         __CLASS__,
248                         $this->classCnt,
249                         $this->dirCnt
250                 ));
251         }
252
253         /**
254          * Includes all found classes
255          * @return      void
256          */
257         public function includeAllClasses () {
258                 if (is_object($this->classes)) {
259                         // Load all classes
260                         for ($idx = $this->classes->getIterator(); $idx->valid(); $idx->next()) {
261                                 // Load current class
262                                 //* DEBUG: */ print "Class=".$idx->current()."\n";
263                                 require_once($idx->current());
264                         } // END - for
265
266                         // Re-initialize the classes list
267                         $this->classes = new ArrayObject();
268                 } // END - if
269         }
270
271         /**
272          * Load extra config files
273          *
274          * @return      void
275          */
276         public function loadExtraConfigs () {
277                 // Backup old prefix
278                 $oldPrefix = $this->prefix;
279
280                 // Set new prefix (temporary!)
281                 $this->prefix = "config-";
282                 $this->preLen = strlen($this->prefix);
283
284                 // Set base directory
285                 $basePath = sprintf("%sinc/config/", PATH);
286
287                 // Load all classes from the config directory
288                 $this->loadClasses($basePath);
289
290                 // Set the prefix back
291                 $this->prefix = $oldPrefix;
292                 $this->preLen = strlen($this->prefix);
293         }
294 }
295
296 // Initial load of core classes and the FrameworkDirectoryPointer class
297 require_once(sprintf("%sinc/classes/interfaces/class_FrameworkInterface%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
298 require_once(sprintf("%sinc/classes/main/class_BaseFrameworkSystem%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
299 require_once(sprintf("%sinc/classes/main/io/class_FrameworkDirectoryPointer%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
300
301 // [EOF]
302 ?>