final added, code clean-ups
[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@mxchange.org>
6  * @version             0.3.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.mxchange.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 $thisInstance = 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::$thisInstance = $this;
119         }
120
121         /**
122          * Getter for an instance of this class
123          *
124          * @return      $thisInstance           An instance of this class
125          */
126         public final static function getInstance () {
127                 return self::$thisInstance;
128         }
129
130         /**
131          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
132          *
133          * @param               $basePath               The relative base path to PATH constant for all classes
134          * @param               $ignoreList     An optional list (array or string) of directory names which shall be ignored
135          * @return      void
136          */
137         public function loadClasses ($basePath, $ignoreList = array() ) {
138                 // Convert string to array
139                 if (!is_array($ignoreList)) $ignoreList = array($ignoreList);
140
141                 // Directories which our class loader ignores by default while
142                 // deep-scanning the directory structure. See scanLocalPath() for
143                 // details.
144                 $ignoreList[] = ".";
145                 $ignoreList[] = "..";
146                 $ignoreList[] = ".htaccess";
147
148                 // Keep it in class for later usage
149                 $this->ignoreList = $ignoreList;
150
151                 // Set base directory which holds all our classes, we should use an
152                 // absolute path here so is_dir(), is_file() and so on will always
153                 // find the correct files and dirs.
154                 $basePath2 = realpath($basePath);
155
156                 // If the basePath is false it is invalid
157                 if ($basePath2 === false) {
158                         // TODO: Do not die here.
159                         die("Cannot read {$basePath} !");
160                 } else {
161                         // Set base path
162                         $basePath = $basePath2;
163                 }
164
165                 // Load all super classes (backward, why ever this name... :-? )
166                 // We don't support sub directories here...
167                 $this->scanLocalPath($basePath);
168
169                 // While there are directories in our list scan them for classes
170                 $cnt = 0;
171                 while ($cnt != $this->dirList->count()) {
172                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
173                                 // Get current path
174                                 $currPath = $idx->current();
175
176                                 // Remove the current entry or else this will lead into a infinite loop
177                                 $this->dirList->offsetSet($idx->key(), "");
178
179                                 // Scan the directory
180                                 $this->scanLocalPath($currPath);
181                         }
182
183                         // Check if we can leave
184                         $cnt = 0;
185                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
186                                 if ($idx->current() == "") $cnt++;
187                         }
188                 }
189         }
190
191         /**
192         * The local path scanner. A found class will be loaded immediately
193         * @param                $localPath      The local path which shall be recursively scanned for include files
194         * @return               void
195         */
196         private function scanLocalPath ($localPath) {
197                 // Empty path names will be silently ignored
198                 if (empty($localPath)) return;
199
200                 // TODO: No dies here, mayybe this should be rewritten to throw an exception?
201                 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($localPath);
202                 while ($dirClass = $dirInstance->readDirectoryExcept($this->ignoreList)) {
203                         // We need the relative dir name as an array index some lines below
204                         $dirClass2 = $dirClass;
205
206                         // A nice replacement for a simple dot ;)
207                         $dirClass = sprintf("%s/%s", $localPath, $dirClass);
208
209                         // Is a readable file with configured prefix and suffix? All other
210                         // files will silently be ignored!
211                         //* DEBUG: */ print "Prefix=".$this->prefix."(".substr($dirClass2, 0 , $this->preLen).")\n";
212                         //* DEBUG: */ print "Suffix=".$this->suffix."(".substr($dirClass2, -$this->sufLen, $this->sufLen).")\n";
213                         //* DEBUG: */ print "ENTRY={$dirClass}\n";
214                         if (
215                                  (is_file($dirClass))
216                         && (is_readable($dirClass))
217                         && (substr($dirClass2, 0 , $this->preLen) == $this->prefix)
218                         && (substr($dirClass2, -$this->sufLen, $this->sufLen) == $this->suffix)
219                         ) {
220                                 // Class found so load it instantly
221                                 //* DEBUG: */ print "CLASS={$dirClass}\n";
222                                 $this->classes->append($dirClass);
223                                 $this->classCnt++;
224                         } elseif (is_dir($dirClass) && !in_array($dirClass2, $this->ignoreList)) {
225                                 // Directory found and added to list
226                                 //* DEBUG: */ print "DIR={$dirClass}\n";
227                                 if ($dirClass2 == "interfaces") {
228                                         $this->scanLocalPath($dirClass);
229                                 } else {
230                                         $this->dirList->append($dirClass);
231                                 }
232                                 $this->dirCnt++;
233                         }
234                         //* DEBUG: */ print "LOOP!\n";
235                 } // END - while
236
237                 // Close directory handler
238                 $dirInstance->closeDirectory();
239
240                 // Output counter in debug mode
241                 if (defined('DEBUG_MODE')) print(sprintf("[%s:] <strong>%d</strong> Klassendateien in <strong>%d</strong> Verzeichnissen gefunden und geladen.<br />\n",
242                         __CLASS__,
243                         $this->classCnt,
244                         $this->dirCnt
245                 ));
246         }
247
248         /**
249          * Includes all found classes
250          * @return      void
251          */
252         public function includeAllClasses () {
253                 if (is_object($this->classes)) {
254                         // Load all classes
255                         for ($idx = $this->classes->getIterator(); $idx->valid(); $idx->next()) {
256                                 // Load current class
257                                 //* DEBUG: */ print "Class=".$idx->current()."\n";
258                                 require_once($idx->current());
259                         }
260
261                         // Re-initialize the classes list
262                         $this->classes = new ArrayObject();
263                 }
264         }
265
266         /**
267          * Load extra config files
268          *
269          * @return      void
270          */
271         public function loadExtraConfigs () {
272                 // Backup old prefix
273                 $oldPrefix = $this->prefix;
274
275                 // Set new prefix (temporary!)
276                 $this->prefix = "config-";
277                 $this->preLen = strlen($this->prefix);
278
279                 // Set base directory
280                 $basePath = sprintf("%sinc/config/", PATH);
281
282                 // Load all classes from the config directory
283                 $this->loadClasses($basePath);
284
285                 // Set the prefix back
286                 $this->prefix = $oldPrefix;
287                 $this->preLen = strlen($this->prefix);
288         }
289 }
290
291 // Initial load of core classes and the FrameworkDirectoryPointer class
292 require_once(sprintf("%sinc/classes/interfaces/class_FrameworkInterface%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
293 require_once(sprintf("%sinc/classes/main/class_BaseFrameworkSystem%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
294 require_once(sprintf("%sinc/classes/main/io/class_FrameworkDirectoryPointer%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
295
296 // Initialize the class loader
297 $loader = new ClassLoader(FrameworkConfiguration::getInstance());
298
299 // [EOF]
300 ?>