-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kickstart.php
executable file
·1414 lines (1344 loc) · 42 KB
/
Kickstart.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php //#SCOPE_OS_PUBLIC
/*******************************************************************************
#LIC_FULL
@author Troy Hurteau <jthurtea@ncsu.edu>
Utility class for starting up an application and preparing the framework.
Also provides autoloading.
*******************************************************************************/
require_once(LIBRARY_PATH . '/Saf/Filter/Truthy.php');
require_once(LIBRARY_PATH . '/Saf/Status.php');
require_once(LIBRARY_PATH . '/Saf/Debug.php');
require_once(LIBRARY_PATH . '/Saf/Layout.php');
//#TODO #1.0.0 update function header docs
class Saf_Kickstart {
/**
* instructs an inserter to add the new item to the start of the list
* @var bool
*/
const POSITION_BEFORE = TRUE;
/**
* instructs an inserter to add the new item to the end of the list
* @var unknown_type
*/
const POSITION_AFTER = FALSE;
const CAST_STRING = 0;
const CAST_BOOL = 1;
const CAST_INT = 2;
const CAST_FLOAT = 3;
const CAST_COMMA_ARRAY = 4;
const CAST_SPACE_ARRAY = 5;
const CAST_NEWLINE_ARRAY = 6;
const CAST_CSV = 7;
const CAST_TSV = 8;
const CAST_JSON = 9;
const CAST_XML_MAP = 10;
const MODE_AUTODETECT = NULL;
const MODE_NONE = 'none';
const MODE_SAF = 'saf';
const MODE_ZFMVC = 'zendmvc';
const MODE_ZFNONE = 'zendbare';
const MODE_LF5 = 'laravel5'; //#TODO #2.0.0 support Laravel
const MODE_ZF3 = 'zend3'; //#TODO #2.0.0 support Zend 3
const REGEX_VAR =
'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/';
const REGEX_CLASS =
'/class\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)[\s{]/';
const REGEX_PARENT_CLASS =
'/class\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\s+extends\s+([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+[\s{]/';
/**
* indicates the mode that the environment as been initialized in
* @var string
*/
protected static $_kicked = NULL;
/**
* indicates that the internal lists have been normalized
*/
protected static $_initialized = FALSE;
/**
* indicates that the internal autoloader is in charge
* @var bool
*/
protected static $_autoloadingInstalled = FALSE;
protected static $_controllerPath = 'Controller';
protected static $_modelPath = 'Model';
/**
* list of class prefixes and paths for autoloading
* @var array
*/
protected static $_autoloaders = array(
'' => array(
'[[APPLIATION_PATH]]/models',
)
);
/**
* list of named autoloaders and the callable they use for resolution
* @var array
*/
protected static $_specialAutoloaders = array(
'controller' => array(
'Saf_Kickstart::resolveControllerPath' => 'Saf_Kickstart::resolveControllerPath'
)
);
/**
* list of library autoloaders and the callable they use for resolution
* @var array
*/
protected static $_libraries = array(
'Saf' => array(
'Saf_Kickstart::resolveClassPath' => 'Saf_Kickstart::resolveClassPath'
)
);
/**
* specifies the path to the exception display view script
* defaults to (set to) APPLICATION_PATH . '/views/scripts/error/error.php'
* the first time exceptionDisplay() is called if not already set by
* setExceptionDisplayScript().
* @var string
*/
protected static $_exceptionView = NULL;
/**
* Accepts a constant name and optional default value. Will attempt to
* see if the constant is already defined. If not it will see if there
* is a local dot file in the pwd or path that specifies this value.
* If neither of these are true it will use the provided default or
* die with a failure message in the event there is no value source.
* @param string $constantName constant to look for and set
* @param mixed $constantDefault default value to use if none are available
* @param int $cast class constant to coerce any loaded values into, provided defaults not coerced, defaults to string
* @return true or execution is halted
*/
public static function defineLoad($constantName, $constantDefault = NULL, $cast = self::CAST_STRING)
{
if (is_array($constantName)){
foreach($constantName as $currentConstantIndex => $currentConstantValue) {
$currentConstantName =
is_array($currentConstantValue)
? $currentConstantIndex
: $currentConstantValue;
$currentDefault =
is_array($currentConstantValue) && array_key_exists(0, $currentConstantValue)
? $currentConstantValue[0]
: $constantDefault;
$currentCast =
is_array($currentConstantValue) && array_key_exists(1, $currentConstantValue)
? $currentConstantValue[1]
: $cast;
self::defineLoad($currentConstantName, $currentDefault, $currentCast);
}
return TRUE;
}
$constantName = self::filterConstantName($constantName);
$sourceFileMatch = self::dotFileMatch($constantName);
$sourceFilename =
is_array($sourceFileMatch)
? $sourceFileMatch[0]
: $sourceFileMatch;
$lowerConstantName = strtolower($constantName);
$failureMessage = 'This application is not fully configured. '
. "Please set a value for {$constantName}. "
. (
$sourceFilename
? "There is a {$sourceFilename} file that may specify this configuration option, but it is not readable."
: "This value can be specified locally in a .{$lowerConstantName} file."
);
if (!defined($constantName)) {
if ($sourceFileMatch) {
$sourceValue = self::load($sourceFileMatch);
define($constantName, self::cast($sourceValue, $cast));
} else if (!is_null($constantDefault)) {
define($constantName, $constantDefault);
} else {
die($failureMessage);
}
}
return TRUE;
}
public static function valueLoad($valueName, $valueDefault = NULL, $cast = self::CAST_STRING)
{
if (is_array($valueName)){
$return = array();
foreach($valueName as $currentValueIndex => $currentValue) {
$currentValueName =
is_array($currentValue)
? $currentValueIndex
: $currentValue;
$currentDefault =
is_array($currentValue) && array_key_exists(0, $currentValue)
? $currentValue[0]
: $valueDefault;
$currentCast =
is_array($currentValue) && array_key_exists(1, $currentValue)
? $currentValue[1]
: $cast;
$return[$valueName] = self::valueLoad($currentValueName, $currentDefault, $currentCast);
}
return $return;
}
$valueName = self::filterConstantName($valueName);
$sourceFileMatch = self::dotFileMatch($valueName);
$sourceFilename =
is_array($sourceFileMatch)
? $sourceFileMatch[0]
: $sourceFileMatch;
$lowerValueName = strtolower($valueName);
$failureMessage = 'This application is not fully configured. '
. "Please set a value for {$valueName}. "
. (
$sourceFilename
? "There is a {$sourceFilename} file that may specify this configuration option, but it is not readable."
: "This value can be specified locally in a .{$lowerValueName} file."
);
if ($sourceFileMatch) {
$sourceValue = self::load($sourceFileMatch);
return self::cast($sourceValue, $cast);
} else if (!is_null($valueDefault)) {
return $valueDefault;
} else {
die($failureMessage);
}
}
public static function mapLoad($valueName, $memberCast = self::CAST_STRING)
{
$valueName = self::filterConstantName($valueName);
$sourceFileMatch = self::dotFileMatch($valueName, TRUE);
$sourceFilename =
is_array($sourceFileMatch)
? $sourceFileMatch[0]
: $sourceFileMatch;
$lowerValueName = strtolower($valueName);
$failureMessage = 'This application is not fully configured. '
. "Please set a map of values for {$valueName}. "
. (
$sourceFilename
? "There is a {$sourceFilename} file that may specify this configuration option, but it is not readable."
: "This value can be specified locally in a .{$lowerValueName} file."
);
if ($sourceFileMatch) {
$sourceValues = self::load($sourceFileMatch);
$castValues = array();
foreach($sourceValues as $index=>$value) {
$castValues[$index] = self::cast($value, $memberCast);
}
return $castValues;
} else if (!is_null($valueDefault)) {
return $valueDefault;
} else {
die($failureMessage);
}
}
public static function filterConstantName($name)
{
$filteredName = preg_replace('/[^A-Za-z0-9_\x7f-\xff]/', '', $name);
return strtoupper($filteredName);
}
protected static function load($sourceConfig, $lineBreak = PHP_EOL, $delim = ':')
{
if (is_array($sourceConfig)) {
$lines = explode($lineBreak, trim(file_get_contents($sourceConfig[0])));
if ('' != trim($sourceConfig[1])) {
$matchLine = NULL;
foreach($lines as $line) {
$upperMatch = strtoupper(trim($sourceConfig[1]) . $delim);
$upperLine = strtoupper($line);
if (strpos($upperLine,$upperMatch) === 0) {
$matchLine = trim(substr($line, strlen($upperMatch)));
break;
}
}
return $matchLine;
} else {
$values = array();
foreach($lines as $line) {
$index = NULL;
$indexEnd = strpos($line, $delim);
if ($indexEnd !== FALSE) {
$index = substr($line, 0, $indexEnd);
$values[$index] = trim(substr($line, $indexEnd + strlen($delim)));
} else {
$values[] = $line;
}
}
return $values;
}
} else {
return (trim(file_get_contents($sourceConfig)));
}
}
protected static function _filterDotFileName($constantName)
{
$lowerConstantName = strtolower($constantName);
$safeConstantName = preg_replace('/[^a-z0-9_.]/', '', $lowerConstantName);
$prefSource = self::_prefFileSource('.' . $safeConstantName);
return
strlen($safeConstantName) > 1
? "{$prefSource}/.{$safeConstantName}"
: FALSE;
}
protected static function _filterDoubleDotFileName($constantName)
{
$lowerConstantName = strtolower($constantName);
$safeConstantName = preg_replace('/[^a-z0-9_.]/', '', $lowerConstantName);
$prefSource = self::_prefFileSource('..' . $safeConstantName, FALSE);
if (strlen($safeConstantName) <= 1) {
return FALSE;
}
if (is_array($prefSource)) {
$result = array();
foreach($prefSource as $prefSourceOption) {
$result[] = "{$prefSourceOption}/..{$safeConstantName}";
}
return $result;
} else {
return "{$prefSource}/..{$safeConstantName}";
}
}
protected static function _prefFileSource($file, $ifExists = TRUE)
{
return (
defined('APPLICATION_PATH')
? (
file_exists(APPLICATION_PATH . "/{$file}")
? APPLICATION_PATH
: ($ifExists ? '.' : array(APPLICATION_PATH, '.'))
) : '.'
);
}
public static function dotFileMatch($constantName, $allowMulti = FALSE)
{
$sourceFilename = self::_filterDotFileName($constantName);
if(is_readable($sourceFilename)){
return $sourceFilename;
} else {
return self::_doubleDotFileScan($constantName, $allowMulti);
}
}
protected static function _doubleDotFileScan($constantName, $allowMulti = FALSE)
{
$sourceFilename = self::_filterDoubleDotFileName($constantName);
if (!is_array($sourceFilename)) {
$sourceFilename = array($sourceFilename);
}
$scans = array();
foreach($sourceFilename as $currentSourceFilename) {
$components = explode('_', $currentSourceFilename);
foreach($components as $componentIndex => $componentName) {
$fullMatch = implode('_', array_slice($components, 0, $componentIndex + 1));
if ($fullMatch != $currentSourceFilename) {
$scans[] = array(
$fullMatch,
implode('_', array_slice($components, $componentIndex + 1))
);
} else if ($allowMulti && is_readable($fullMatch)) {
return array($fullMatch, '');
}
}
}
foreach($scans as $scanParts) {
if (is_readable($scanParts[0])) {
$lines = explode(PHP_EOL, trim(file_get_contents($scanParts[0])));
foreach($lines as $line) {
$upperMatch = strtoupper($scanParts[1]);
$upperLine = strtoupper($line);
if (strpos($upperLine, $upperMatch) === 0) {
return $scanParts;
}
}
}
}
return NULL;
}
public static function dotFileExists($constantName)
{
$sourceFilename = self::_filterDotFileName($constantName);
return is_readable($sourceFilename);
}
public static function envRead($filepath)
{
$return = array();
if (file_exists($filepath) && is_readable($filepath)) {
$lines = explode(PHP_EOL,file_get_contents($filepath));
foreach($lines as $line) {
$line = trim($line);
$split = strpos($line,'=');
if ($split) {
$var = substr($line,0,$split);
$val = substr($line,$split + 1);
$return[$var] = $val;
}
}
}
return $return;
}
/**
* Inserts a new filepath into the path if is not already present. It may
* be relative to a specific other path or the whole list. If the specified
* other path is not present, the new path always goes to the end. The
* specified is also translated into a realpath() for matching purposes. If the
* new path was already present it's old locaiton is removed. This function
* will only add valid, exiecutable paths. Returns true if the path is added.
* @param string $filepath to add
* @param string $preposition optional specification of after (default) or before
* @param string $place for relative placement with preposition.
* @return boolean
*/
public static function addInPath($filepath, $preposition = self::POSITION_AFTER, $place = '*')
{
$realNewPath = realpath($filepath);
if(!$realNewPath){
return FALSE;
}
$oldPaths = explode(PATH_SEPARATOR, ini_get('include_path'));
$newPaths = array();
$placed = FALSE;
$realPlace = realpath($place);
foreach ($oldPaths as $path) {
$currentRealPath = realpath($path);
$currentMatchesNew = (
($currentRealPath && ($currentRealPath == $realNewPath))
|| $path == $filepath
);
$currentMatchesPlace = (
($currentRealPath && ($currentRealPath == $realPlace))
|| $path == $place
);
if (self::POSITION_BEFORE == $preposition && !$placed) {
if ('*' == $place || $currentMatchesPlace) {
$newPaths[] = $realNewPath;
if (!$currentMatchesNew) {
$newPaths[] = $path;
}
$placed = TRUE;
}
} else if (!$placed) {
if ('*' == $place || $currentMatchesPlace) {
if (!$currentMatchesNew) {
$newPaths[] = $path;
}
$newPaths[] = $realNewPath;
$placed = TRUE;
}
} else if (!$currentMatchesNew) {
$newPaths[] = $path;
}
/* if(strpos($filepath, PATH_SEPARATOR) !== 0
? file_exists(realpath($path . $filepath))
: file_exists(realpath($path . PATH_SEPARATOR . $filepath))
){
return TRUE;
}*/
}
if (!$placed) {
$newPaths[] = $realNewPath;
}
ini_set('include_path', implode(PATH_SEPARATOR, $newPaths));
return TRUE;
}
/**
* Manually checks the path (not always pwd) to see if the file to be included
* is there. Implemented as such because some differences seem to be present
* between PHP implementations.
* @param string filepath relative path to the file or folder in question.
* @return boolean
*/
public static function fileExistsInPath($filepath)
{
if(strpos($filepath, '/') === 0) {
return file_exists($filepath);
}
$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
foreach($paths as $path){
if (file_exists(realpath("{$path}/{$filepath}"))){
return TRUE;
}
}
return FALSE;
}
/**
* @param string $filepath
* @param int $order
*/
public static function addIfNotInPath($filePath, $order = self::POSITION_AFTER)
{
$includePaths = explode(PATH_SEPARATOR, get_include_path());
$inPath = FALSE;
foreach($includePaths as $includePath) {
if (realpath($includePath) == realpath($filePath)) {
$inPath = TRUE;
break;
}
}
if (!$inPath) {
if ($order === self::POSITION_AFTER) {
$includePaths[] = $filePath;
} else {
$includePaths = array_unshift($includePaths, $filePath);
}
set_include_path(implode(PATH_SEPARATOR, $includePaths));
}
}
public static function translatePath($path)
{
return str_replace(
array(
'[[APPLICATION_PATH]]',
'[[LIBRARY_PATH]]',
'[[PUBLIC_PATH]]',
'[[INSTALL_PATH]]'
), array(
APPLICATION_PATH,
LIBRARY_PATH,
PUBLIC_PATH,
INSTALL_PATH
), $path
);
}
/**
* Converts a classname and base file path into a full path based
* on Zend Framework class naming conventions. i.e. _ to /
*
*/
public static function resolveClassPath($className, $basePath = '')
{
if ('' == $basePath) {
$basePath = LIBRARY_PATH;
}
$classNameComponents = explode('_', $className);
$classPath = $basePath;
foreach ($classNameComponents as $nameComponent) {
$classPath .= "/{$nameComponent}";
}
$classPath .= '.php'; //#TODO #2.0.0 handle other file formats
return $classPath;
}
public static function resolveControllerClassName($controllerName)
{
$nameSuffix = 'Controller';
$className = ucfirst($controllerName);
return
strpos($className, $nameSuffix) == FALSE
|| strrpos($className, $nameSuffix) != strlen($className) - strlen($nameSuffix)
? $className .= $nameSuffix
: $className;
}
/**
* Converts a controller class name into a filepath
* @param string $className
*/
public static function resolveControllerPath($controllerName, $coerce = TRUE)
{
$controllerPath = APPLICATION_PATH . '/' . self::$_controllerPath . '/';
$className = $coerce ? self::resolveControllerClassName($controllerName) : $controllerName;
if (!is_readable($controllerPath)) {
throw new Exception('This application does not support controllers.');
}
return(self::resolveClassPath($className, $controllerPath));
}
/**
* casts a value into a different type
* @param mixed $value
* @param int $cast matching one of the CAST_ class constants
* @return mixed
*/
public static function cast($value, $cast)
{
switch ($cast) {
case self::CAST_BOOL :
return Saf_Filter_Truthy::filter($value);
default: //#TODO #2.0.0 support the other cast features
return $value;
}
}
/**
* checks to see if a string is a valid class/variable name
* @param string $string
* @return bool
*/
public static function isValidNameToken($string)
{
$pattern = self::REGEX_VAR;
return preg_match($pattern, $string);
}
/**
* scan a file for the first class definition and return the class name
* @param string $file path
* @returns string class
*/
public static function getClassIn($file)
{
$file = file_get_contents($file);
$pattern = self::REGEX_CLASS;
$matches = NULL;
preg_match($pattern, $file, $matches);
return
$matches && array_key_exists(1, $matches)
? $matches[1]
: '';
}
/**
* scan a file for the first class definition extending another class
* and return the parent class name
* @param string $file path
* @returns string class
*/
public static function getParentClassIn($file)
{
$file = file_get_contents($file);
$pattern = self::REGEX_PARENT_CLASS;
$matches = NULL;
preg_match($pattern, $file, $matches);
return
$matches && array_key_exists(1, $matches)
? $matches[1]
: '';
}
public static function isAutoloading()
{
return self::$_autoloadingInstalled;
}
/**
* Turns on autoloading. Optionally, it can prep for explicit use
* of self::autoload only.
* @param bool $takeover defaults to TRUE
*/
public static function initializeAutoloader($takeover = TRUE)
{
//#TODO #3.0.0 allow for uninstall
if ($takeover && !self::$_autoloadingInstalled) {
spl_autoload_register('Saf_Kickstart::autoload');
self::$_autoloadingInstalled = TRUE;
}
if (self::$_initialized) {
return;
}
foreach(self::$_libraries as $libraryPrefix => $callableList) {
foreach($callableList as $callableIndex => $callable) {
if (
!is_a($callable,'ReflectionFunctionAbstract', FALSE)
&& (
!is_array($callable)
|| !array_key_exists(0,$callable)
|| !array_Key_exists(1,$callable)
|| !is_object($callable[0])
|| !is_a($callable[1],'ReflectionFunctionAbstract', FALSE)
)
) {
self::$_libraries[$libraryPrefix][$callableIndex] = self::_instantiateCallable($callable);
}
}
}
foreach(self::$_specialAutoloaders as $loaderName => $callableList) {
foreach($callableList as $callableIndex => $callable) {
if (
!is_a($callable,'ReflectionFunctionAbstract', FALSE)
&& (
!is_array($callable)
|| !array_key_exists(0,$callable)
|| !array_Key_exists(1,$callable)
|| !is_object($callable[0])
|| !is_a($callable[1],'ReflectionFunctionAbstract', FALSE)
)
) {
self::$_specialAutoloaders[$loaderName][$callableIndex] = self::_instantiateCallable($callable);
}
}
}
foreach(self::$_autoloaders as $prefix => $paths) {
foreach($paths as $pathIndex => $path) {
self::$_autoloaders[$prefix][$pathIndex] = self::translatePath($path);
}
}
self::$_initialized = TRUE;
}
/**
* Attempts to autoload a class by name, checking it against known class
* name prefixes for libraries (using an optional user provided path
* resolution method), or for other files using the Zend Framework naming
* conventions in one or more registered paths.
* Autoloading come preconfigured to look in the APPLICATION_PATH/models/
* (matching any class), and LIBRARY_PATH/Saf/ (matching prefix 'Saf_') paths.
* Libraries alway take precidence over other matching rules.
* The first existing match file will be included.
* If a $specialLoader is specified, only that loader is searched.
* Special loaders are only searched when specified.
* @param string $className name of class to be found/loaded
* @param string $specialLoader limits the search to a specific special loader
*
*/
public static function autoload($className, $specialLoader = '')
{
if (class_exists($className, FALSE)) {
return TRUE;
}
if (!self::$_autoloadingInstalled && class_exists('Zend_Loader_Autoloader', FALSE)) {
$zendAutoloader = Zend_Loader_Autoloader::getInstance();
$currentSetting = $zendAutoloader->suppressNotFoundWarnings();
$zendAutoloader->suppressNotFoundWarnings(TRUE);
$zendResult = Zend_Loader_Autoloader::autoload($className);
$zendAutoloader->suppressNotFoundWarnings($currentSetting);
return $zendResult;
}
if (!self::$_initialized) {
self::initializeAutoloader(FALSE);
}
if ($specialLoader) {
if (!is_array($specialLoader)) {
$specialLoader = array();
}
foreach($specialLoader as $loader) {
if (array_key_exists($specialLoader, self::$_specialAutoloaders)) {
foreach(self::$_specialAutoloaders[$specialLoader] as $callableList) {
foreach ($callableList as $callableSet) {
if(is_array($callableSet)) {
$callableInstance = $callableSet[0];
$callableReflector = $callableSet[1];
} else {
$callableInstance = NULL;
$callableReflector = $callableSet;
}
$classFile = $callableReflector->invoke($callableInstance, $className);
if (
$classFile
&& self::fileExistsInPath($classFile)
) {
require_once($classFile);
if (!class_exists($className, FALSE)) {
throw new Exception('Failed to special autoload class'
. (
class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled()
? " {$className}"
: ''
) . '. Found class file, but no definition inside.'
);
}
return TRUE;
}
}
}
} else {
throw new Exception('Failed to special autoload class'
. (
class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled()
? " {$className}"
: ''
) . '. invalid loader specified.'
);
}
}
return FALSE;
}
foreach(self::$_libraries as $classPrefix => $callableList) {
if (strpos($className, $classPrefix) === 0) {
foreach ($callableList as $callableSet) {
if(is_array($callableSet)) {
$callableInstance = $callableSet[0];
$callableReflector = $callableSet[1];
} else {
$callableInstance = NULL;
$callableReflector = $callableSet;
}
// if (!is_object($callableReflector)) {
// print_r(array($className,$classPrefix,$callableList));
// throw new Exception('huh');
// }
$classFile = $callableReflector->invoke($callableInstance, $className);
if (
$classFile
&& self::fileExistsInPath($classFile)
) {
require_once($classFile);
if (!class_exists($className, FALSE)) {
throw new Exception('Failed to autoload class'
. (
class_exists('Saf_Debug',FALSE) && Saf_Debug::isEnabled()
? " {$className}"
: ''
)
. '. Found a library, but no definition inside.'
);
}
return TRUE;
}
}
}
}
foreach (self::$_autoloaders as $classPrefix => $pathList) {
if ('' == $classPrefix || strpos($className, $classPrefix) === 0) {
foreach($pathList as $path) {
$classFile = self::resolveClassPath($className, $path);
if (
$classFile
&& self::fileExistsInPath($classFile)
) {
require_once($classFile);
if (!class_exists($className, FALSE)) {
throw new Exception('Failed to autoload class'
. (
class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled()
? " {$className}"
: ''
)
. '. Found a file, but no definition inside.'
);
}
return TRUE;
}
}
}
}
if (!class_exists($className, FALSE)) {
throw new Exception('Failed resolving file to autoload class'
. (
class_exists('Saf_Debug', FALSE) && Saf_Debug::isEnabled()
? " {$className}"
: ''
)
. '.'
);
}
return TRUE;
}
/**
* Registers a new library for autoloading. Default behavior is to
* try to load from the LIBRARY_PATH using Zend Framework naming conventions.
*
*/
public static function addLibrary($libraryPrefix, $resolutionCallable = NULL, $preposition = self::POSITION_AFTER)
{
self::initializeAutoloader(FALSE);
if ('' == $resolutionCallable || is_null($resolutionCallable)) {
$resolutionCallable = 'Saf_Kickstart::resolveClassPath';
}
$instantiatedCallable = self::_instantiateCallable($resolutionCallable);
if (array_key_exists($libraryPrefix, self::$_libraries)) {
if ($preposition) {
self::$_libraries[$libraryPrefix] = array_merge(
array(
$resolutionCallable => $instantiatedCallable
),
self::$_libraries[$libraryPrefix]
);
} else {
self::$_libraries[$libraryPrefix][$resolutionCallable] =
self::_instantiateCallable($resolutionCallable);
}
return;
}
foreach(self::$_libraries as $existingPrefix => $existingLibrary){
if (strpos($existingPrefix, $libraryPrefix) === 0) {
$newLibMap = array();
foreach(self::$_libraries as $currentPrefix => $currentSpec) {
if ($currentPrefix == $existingPrefix) {
$newLibMap[$libraryPrefix] = array($resolutionCallable => instantiatedCallable);
$newLibMap[$currentPrefix] = $currentSpec;
} else {
$newLibMap[$currentPrefix] = $currentSpec;
}
}
self::$_libraries = $newLibMap;
return;
}
}
self::$_libraries[$libraryPrefix] = array(
$resolutionCallable => $instantiatedCallable
);
}
public static function getLibrarySpec()
{
self::initializeAutoloader(FALSE);
return self::$_libraries;
}
/**
* remove the library resolver specified, or all entries for that library if null
* @param string $libraryPrefix
* @param string $callable
*/
public static function removeLibrary($libraryPrefix, $callable = NULL)
{ //#TODO #3.0.0 translate non-string callables
self::initializeAutoloader(FALSE);
if (!array_key_exists($libraryPrefix, self::$_libraries)) {
return FALSE;
}
if (is_null($callable)) {
unset(self::$_libraries[$libaryPrefix]);
return array($libraryPrefix => $callable);
}
if (array_key_exists($callable, self::$_libraries[$libaryPrefix])) {
unset(self::$_libraries[$libaryPrefix][$callable]);
return array($libraryPrefix => $callable);
}
return FALSE;
}
/**
* Registers one or more new prefix/path pairs. Prefixes may be the empty
* string to match any class. Paths may be empty to match the path.
*
*/
public static function addAutoloader($prefix, $path, $preposition = self::POSITION_AFTER)
{
self::initializeAutoloader(FALSE);
$path = self::translatePath($path);
if (array_key_exists($prefix, self::$_autoloaders)) {
if ($preposition) {
self::$_autoloaders[$prefix] = array_merge(
array($path),
self::$_autoloaders[$prefix]
);
} else {
self::$_autoloaders[$prefix][] = $path;
}
return;
}
foreach(self::$_autoloaders as $existingPrefix => $existingPaths){
if (strpos($existingPrefix, $prefix) === 0) {
$newMap = array();
foreach(self::$_autoloaders as $currentPrefix => $currentSpec) {
if ($currentPrefix == $existingPrefix) {
$newMap[] = $path;
$newMap[] = $currentSpec;
} else {
$newMap[] = $currentSpec;
}
}
self::$_autoloaders = $newMap;
return;
}
}
self::$_autoloaders[$prefix] = array($path);
}
/**
* Unregisters an autoloader. It can remove only one matching path, or
* all that are registered. Libraries cannot be removed once added.
*
*/
public static function removeAutoloader($prefix, $path = NULL)
{
self::initializeAutoloader(FALSE);
if (!array_key_exists($prefix, self::$_autoloaders)) {
return FALSE;
}
if (is_null($path)) {
unset(self::$_autoloaders[$prefix]);
return array($prefix => $path);
}
if (array_key_exists($path, self::$_autoloaders[$prefix])) {
unset(self::$_autoloaders[$prefix][$path]);
return array($prefix => $path);
}
return FALSE;
}
public static function getPathSpec()
{
self::initializeAutoloader(FALSE);
return self::$_autoloaders;
}
/**
* Registers one or more new name/resolution pairs.
* @param string $name
* @param string $callable
* @param bool $preposition
*/
public static function addSpecialAutoloader($name, $resolutionCallable = NULL , $preposition = self::POSITION_AFTER)
{
self::initializeAutoloader(FALSE);
if ('' == $resolutionCallable || is_null($resolutionCallable)) {
$resolutionCallable = 'Saf_Kickstart::resolveClassPath';
}
$instantiatedCallable = self::_instantiateCallable($resolutionCallable);
if (array_key_exists($name, self::$_specialAutoloaders)) {