0.3.0 inital import
[mailer.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 <roland __NOSPAM__ [at] __REMOVE_ME__ mxchange [dot] org>
6  * @version     1.1
7  *
8  * ----------------------------------
9  * 1.1
10  *  - loadClasses rewritten to fix some notices
11  * 1.0
12  *  - Initial release
13  * ----------------------------------
14  */
15 class ClassLoader {
16         /**
17          * Configuration array
18          */
19         private $cfg = array();
20
21         /**
22          * An ArrayObject for found classes
23          */
24         private $classes = null;
25
26         /**
27          * Suffix with extension for all class files
28          */
29         private $prefix = "class_";
30
31         /**
32          * Suffix with extension for all class files
33          */
34         private $suffix = ".php";
35
36         /**
37          * Length of the suffix. Will be overwritten later.
38          */
39         private $sufLen = 0;
40
41         /**
42          * Length of the prefix. Will be overwritten later.
43          */
44         private $preLen = 0;
45
46         /**
47          * A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
48          * @see scanLocalPath
49          */
50         private $ignoreList = array();
51
52         /**
53          * An ArrayList object for include directories
54          */
55         private $dirList = null;
56
57         /**
58          * Debug this class loader? (true = yes, false = no)
59          */
60         private $debug = false;
61
62         /**
63          * Counter for scanned directories (debug output)
64          */
65         private $dirCnt = 0;
66
67         /**
68          * Counter for loaded classes (debug output)
69          */
70         private $classCnt = 0;
71
72         /**
73          * Instance of this class
74          */
75         private static $thisInstance = null;
76
77         /**
78          * The *public* constructor
79          *
80          * @param               $cfgInstance            Configuration class instance
81          * @return      void
82          */
83         public function __construct (FrameworkConfiguration $cfgInstance) {
84                 // Init the array list
85                 $this->dirList = new ArrayObject();
86
87                 // Set suffix and prefix from configuration
88                 $this->suffix = $cfgInstance->readConfig("class_suffix");
89                 $this->prefix = $cfgInstance->readConfig("class_prefix");
90
91                 // Estimate length of prefix and suffix for substr() function (cache)
92                 $this->sufLen = strlen($this->suffix);
93                 $this->preLen = strlen($this->prefix);
94
95                 // Set configuration instance
96                 $this->cfgInstance = $cfgInstance;
97
98                 // Initialize the classes list
99                 $this->classes = new ArrayObject();
100
101                 // Set own instance
102                 self::$thisInstance = $this;
103         }
104
105         /**
106          * Getter for an instance of this class
107          *
108          * @return      $thisInstance           An instance of this class
109          */
110         public final static function getInstance () {
111                 return self::$thisInstance;
112         }
113
114         /**
115          * Scans recursively a local path for class files which must have a prefix and a suffix as given by $this->suffix and $this->prefix
116          *
117          * @param               $basePath               The relative base path to PATH constant for all classes
118          * @param               $ignoreList     An optional list (array or string) of directory names which shall be ignored
119          * @return      void
120          */
121         public function loadClasses ($basePath, $ignoreList = array() ) {
122                 // Convert string to array
123                 if (!is_array($ignoreList)) $ignoreList = array($ignoreList);
124
125                 // Directories which our class loader ignores by default while
126                 // deep-scanning the directory structure. See scanLocalPath() for
127                 // details.
128                 $ignoreList[] = ".";
129                 $ignoreList[] = "..";
130                 $ignoreList[] = ".htaccess";
131
132                 // Keep it in class for later usage
133                 $this->ignoreList = $ignoreList;
134
135                 // Set base directory which holds all our classes, we should use an
136                 // absolute path here so is_dir(), is_file() and so on will always
137                 // find the correct files and dirs.
138                 $basePath2 = realpath($basePath);
139
140                 // If the basePath is false it is invalid
141                 if ($basePath2 === false) {
142                         // TODO: Do not die here.
143                         die("Cannot read {$basePath} !");
144                 } else {
145                         // Set base path
146                         $basePath = $basePath2;
147                 }
148
149                 // Load all super classes (backward, why ever this name... :-? )
150                 // We don't support sub directories here...
151                 $this->scanLocalPath($basePath);
152
153                 // While there are directories in our list scan them for classes
154                 $cnt = 0;
155                 while ($cnt != $this->dirList->count()) {
156                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
157                                 // Get current path
158                                 $currPath = $idx->current();
159
160                                 // Remove the current entry or else this will lead into a infinite loop
161                                 $this->dirList->offsetSet($idx->key(), "");
162
163                                 // Scan the directory
164                                 $this->scanLocalPath($currPath);
165                         }
166
167                         // Check if we can leave
168                         $cnt = 0;
169                         for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
170                                 if ($idx->current() == "") $cnt++;
171                         }
172                 }
173         }
174
175         /**
176         * The local path scanner. A found class will be loaded immediately
177         * @param                $localPath      The local path which shall be recursively scanned for include files
178         * @return               void
179         */
180         private function scanLocalPath ($localPath) {
181                 // Empty path names will be silently ignored
182                 if (empty($localPath)) return;
183
184                 // TODO: No dies here, mayybe this should be rewritten to throw an exception?
185                 $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($localPath);
186                 while ($dirClass = $dirInstance->readDirectoryExcept($this->ignoreList)) {
187                         // We need the relative dir name as an array index some lines below
188                         $dirClass2 = $dirClass;
189
190                         // A nice replacement for a simple dot ;)
191                         $dirClass = sprintf("%s/%s", $localPath, $dirClass);
192
193                         // Is a readable file with configured prefix and suffix? All other
194                         // files will silently be ignored!
195                         //* DEBUG: */ print "Prefix=".$this->prefix."(".substr($dirClass2, 0 , $this->preLen).")\n";
196                         //* DEBUG: */ print "Suffix=".$this->suffix."(".substr($dirClass2, -$this->sufLen, $this->sufLen).")\n";
197                         //* DEBUG: */ print "ENTRY={$dirClass}\n";
198                         if (
199                            (is_file($dirClass))
200                         && (is_readable($dirClass))
201                         && (substr($dirClass2, 0 , $this->preLen) == $this->prefix)
202                         && (substr($dirClass2, -$this->sufLen, $this->sufLen) == $this->suffix)
203                         ) {
204                                 // Class found so load it instantly
205                                 //* DEBUG: */ print "CLASS={$dirClass}\n";
206                                 $this->classes->append($dirClass);
207                                 $this->classCnt++;
208                         } elseif (is_dir($dirClass) && !in_array($dirClass2, $this->ignoreList)) {
209                                 // Directory found and added to list
210                                 //* DEBUG: */ print "DIR={$dirClass}\n";
211                                 if ($dirClass2 == "interfaces") {
212                                         $this->scanLocalPath($dirClass);
213                                 } else {
214                                         $this->dirList->append($dirClass);
215                                 }
216                                 $this->dirCnt++;
217                         }
218                         //* DEBUG: */ print "LOOP!\n";
219                 } // END - while
220
221                 // Close directory handler
222                 $dirInstance->closeDirectory();
223
224                 // Output counter in debug mode
225                 if (defined('DEBUG_MODE')) print(sprintf("[%s:] <strong>%d</strong> Klassendateien in <strong>%d</strong> Verzeichnissen gefunden und geladen.<br />\n",
226                         __CLASS__,
227                         $this->classCnt,
228                         $this->dirCnt
229                 ));
230         }
231
232         /**
233          * Includes all found classes
234          * @return      void
235          */
236         public function includeAllClasses () {
237                 if (is_object($this->classes)) {
238                         // Load all classes
239                         for ($idx = $this->classes->getIterator(); $idx->valid(); $idx->next()) {
240                                 // Load current class
241                                 //* DEBUG: */ print "Class=".$idx->current()."\n";
242                                 require_once($idx->current());
243                         }
244
245                         // Re-initialize the classes list
246                         $this->classes = new ArrayObject();
247                 }
248         }
249 }
250
251 // Initial load of core classes and the FrameworkDirectoryPointer class
252 require_once(sprintf("%sinc/classes/interfaces/class_FrameworkInterface%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
253 require_once(sprintf("%sinc/classes/main/class_BaseFrameworkSystem%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
254 require_once(sprintf("%sinc/classes/main/io/class_FrameworkDirectoryPointer%s", PATH, FrameworkConfiguration::getInstance()->readConfig("php_extension")));
255
256 // Initialize the class loader
257 $loader = new ClassLoader(FrameworkConfiguration::getInstance());
258
259 // [EOF]
260 ?>