-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoload.php
More file actions
558 lines (496 loc) · 15.1 KB
/
autoload.php
File metadata and controls
558 lines (496 loc) · 15.1 KB
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
<?php
/**
* The autoloader API.
*
* The autoloading class with namespace mapping.
* An alternative to the composer autoloader.
*
* -----------------------------------
* DEVELOPED-MAINTAINED-SUPPORTED BY
* -----------------------------------
* ███║ ███╗ ████████████████
* ███║ ███║ ═════════██████╗
* ███║ ███║ ╔══█████═╝
* ████████████║ ╚═█████
* ███║═════███║ █████╗
* ███║ ███║ █████═╝
* ███║ ███║ ████████████████╗
* ╚═╝ ╚═╝ ═══════════════╝
*
* @package TheWebSolver\Core
* @author Shesh Ghimire <shesh@thewebsolver.com>
* @version 1.0
*/
namespace TheWebSolver;
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
// Prevent other autoloaders autoload TheWebSolver Autoloader class.
if ( ! class_exists( '\\TheWebSolver\\Autoloader', false ) ) {
/**
* Autoloader class.
*
* @link https://getcomposer.org/doc/04-schema.md#psr-4
* @example usage
* ### If class files are present in the same directory:
* - `root/Includes/Helper/Helper_Class.php`
* - `root/Includes/Helper/General/Another_Class.php`
* - `root/Includes/API/General_API.php`
*
* ```
* // From project root, init autoloader.
* use TheWebSolver\Autoloader;
*
* $loader = new Autoloader();
* $map = array('TheWebSolver\\Core\\' => 'Includes');
* $loaders->root(__DIR__)->path($map)->register();
* ```
*
* ### If class files are present in different directories:
* - `root/Includes/Helper/Helper_Class.php`
* - `root/Includes/Template/General/Another_Class.php`
* - `root/Source/API/General_API.php`
*
* Below is the structure how namespace and classname should be for different directories.
* ```
* // File: Helper_Class.php
* namespace TheWebSolver\Core\Helper;
* class Helper_Class {}
*
* // File: Another_Class.php
* namespace TheWebSolver\Core\Template\General;
* class Another_Class {}
*
* // File: General_API.php
* namespace TheWebSolver\Feature\Source\API;
* class General_API {}
*
* // Lets autoload above structure files.
* // Subdirectory names after which namespace maps.
* use TheWebSolver\Autoloader;
*
* $loader = new Autoloader();
* $map = array(
* 'TheWebSolver\\Core\\' => 'Includes',
* 'TheWebSolver\\Feature\\' => 'Source',
* );
*
* // From project root, init autoloader.
* $loader->root(__DIR__)->path($map)->register();
* ```
*/
class Autoloader {
/**
* The project root.
*
* @var string
* @since 1.0
*/
public $root;
/**
* The current project directory name.
*
* @var string
* @since 1.0
*/
public $dir;
/**
* The mapped namespace with it's directory name.
*
* @var (string|string[])[]
* @since 1.0
*/
public $paths;
/**
* Classes set for inclusion.
*
* @var string[]
* @since 1.0
*/
private $classes = array();
/**
* The class to include file for.
*
* @var string
* @since 1.0
*/
private $class = '';
/**
* The autoload status.
*
* @var bool[]
* @since 1.0
*/
private $autoload = array();
/**
* On debug, files are not included.
*
* @var bool
* @since 1.0
*/
private $debug = false;
/**
* Creates full path for the given directory.
*
* @param string $path The path to be appended to root.
* @return string
* @since 1.0
*/
private function set( string $path ): string {
return trailingslashit( $this->root ) . untrailingslashit( $path );
}
/**
* Sets project root.
*
* @param string $dir The project root directory path. Usually `__DIR__`.
* @return Autoloader
* @since 1.0
*/
public function root( string $dir ): Autoloader {
$this->root = $dir;
$this->dir = basename( $this->root );
return $this;
}
/**
* Sets namespace mapping directory name(s).
*
* @param (string|string[])[] $name Mapping namespace prefix as key and directory
* (as string) or directories (as array).
* @return Autoloader
* @link https://getcomposer.org/doc/04-schema.md#psr-4
* @since 1.0
*/
public function path( array $name ): Autoloader {
$this->paths = $name;
return $this;
}
/**
* Sets debug mode.
*
* @param bool $enable Found file is not included if debug is true.
* @return Autoloader
* @since 1.0
*/
public function debug( bool $enable ): Autoloader {
$this->debug = $enable;
return $this;
}
/**
* Gets file from mapped path created using class parts.
*
* @param string[] $parts The classname parts.
* @param string $path The path to append parts to.
* @return string $path The file with full path that matches namespace.
* @since 1.0
*/
private function file( array $parts, string $path ): string {
foreach ( $parts as $part ) {
$path .= "/$part";
}
$path .= '.php';
return $path;
}
/**
* Creates directory paths part from the class.
*
* @param string $namespace The namespace.
* @return string[]
* @since 1.0
*/
private function parts( string $namespace ): array {
$parts = explode( '\\', substr( $this->class, strlen( $namespace ) ) );
return $parts ?: array();
}
/**
* Prevent loading if autoload is set to false.
*
* @throws \LogicException Can't load current class using autoloader.
* @since 1.0
*/
protected function block() {
if ( class_exists( $this->class, false ) ) {
throw new \LogicException(
'Unable to load class:"' . $this->class . '" because autoload is set to "false".'
);
}
}
/**
* Includes mapped directories.
*
* @param string $file The file to include.
* @return bool
* @since 1.0
*/
private function include( string $file ): bool {
$this->autoload[ $file ] = false;
// Bail if file is not readable.
if ( ! is_readable( $file ) ) {
return false;
}
if ( ! $this->debug ) {
include $file;
}
$this->autoload[ $file ] = true;
$this->classes[ $this->class ] = $file;
return true;
}
/**
* Includes mapped directories for autoloading.
*
* @return bool True if file found and included, false otherwise.
* @link https://getcomposer.org/doc/04-schema.md#psr-4
* @since 1.0
*/
private function map(): bool {
if ( ! is_array( $this->paths ) || empty( $this->paths ) ) {
return false;
}
$files = array();
/**
* The prefix for classmap prefix.
*
* @var string $namespace
*/
foreach ( $this->paths as $namespace => $dir ) {
// Remove preceding and succeeding slashes and add succeeding one.
$ns = trim( $namespace, '\\' ) . '\\';
// Ignore classes not in the given namespace.
if ( strpos( $this->class, $ns ) !== 0 ) {
continue;
}
$parts = $this->parts( $ns );
// Ignore non-classmap.
if ( empty( $parts ) ) {
continue;
}
if ( is_string( $dir ) ) {
if ( $this->include( $file = $this->file( $parts, $this->set( $dir ) ) ) ) {
$files[] = $file;
}
} elseif ( is_array( $dir ) ) {
foreach ( $dir as $path ) {
if ( $this->include( $file = $this->file( $parts, $this->set( $path ) ) ) ) {
$files[] = $file;
}
}
}
}
return ! empty( $files );
}
/**
* Includes file if mapping successful.
*
* @param string $class The full class to instantiate.
* @return bool True if autoloaded, false otherwise.
* @since 1.0
*/
public function autoload( string $class ): bool {
$this->class = $class;
return $this->map();
}
/**
* Registers classes for autoloading.
*
* @param bool $throw Specifies whether spl_autoload_register() should throw
* exceptions when the autoload_function cannot be
* registered. Ignored since 8.0.
* @param bool $prepend If true, spl_autoload_register() will prepend
* the autoloader on the autoload stack instead of
* appending it.
* @return bool
* @since 1.0
*/
public function register( bool $throw = true, bool $prepend = false ): bool {
return spl_autoload_register( array( $this, 'autoload' ), $throw, $prepend );
}
/**
* Validates if path is autoloaded.
*
* @param bool $path Whether path is autoloaded or not.
* @return bool
* @since 1.0
*/
public function valid( bool $path ): bool {
return true === $path;
}
/**
* Gets mapped paths.
*
* @return bool[] Filepath as index, true as value.
* @since 1.0
*/
public function get(): array {
return array_filter( $this->get_all(), array( $this, 'valid' ) );
}
/**
* Gets all mapped paths.
*
* It includes those files that do not get mapped.
*
* @return bool[] Filepath as index, autoloaded (true) or not (false) as value.
* @since 1.0
*/
public function get_all(): array {
return $this->autoload;
}
/**
* Gets mapped classes.
*
* @return string[] Class as index, filepath as value.
* @since 1.0
*/
public function classes(): array {
return $this->classes;
}
/**
* Gets the template path.
*
* @return string
* @since 1.0
*/
public function default_path(): string {
return apply_filters( 'tws_default_template_path_' . $this->dir, 'templates/' . $this->dir . '/' );
}
/**
* Locates a template file and return the path for inclusion.
*
* This is the load order:
* - yourtheme/$template_path/$template_name
* - yourtheme/$template_name
* - $default_path/$template_name
*
* @param mixed $template_name The template file name.
* @param string $template_path The template path.
* @param string $default_path The default path.
* @return string
* @since 1.0
*/
public function locate( $template_name, $template_path = '', $default_path = '' ) {
// Set the template path.
if ( ! $template_path ) {
$template_path = $this->default_path();
}
if ( ! $default_path ) {
$default_path = trailingslashit( $this->root ) . 'templates/';
}
// Theme priority when looking for the template file.
$template = locate_template( array( trailingslashit( $template_path ) . $template_name ) );
// Default to plugins directory if not found in theme.
if ( ! $template ) {
$template = $default_path . $template_name;
}
/**
* WPHOOK: Filter -> Send back the located template file.
*
* @param string $template The located template file.
* @param string $template_name The template file name.
* @param string $template_path The template path passed as param.
* @since 1.0
*/
return apply_filters( 'tws_locate_template_file_' . $this->dir, $template, $template_name, $template_path );
}
/**
* Gets the template part.
*
* @param string $slug The first part of the template file name.
* @param string $name The second part of the template file name after ***-***.
* @param array $args The args passed to the template file.
* @since 1.0
*/
public function template_part( string $slug, string $name = '', array $args = array() ) {
if ( ! empty( $args ) ) {
extract( $args ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract
}
/**
* Look in yourtheme/{dirname}/slug-name.php and yourtheme/{dirname}/slug.php.
*
* - {dirname} defaults to "templates/{$this->dir}/" unless used filter to change it.
* - $this->dir is the project directory name and can be:
* - in dev env: `create-wordpress-project`
* - after bundle: user provided `config.core.slug` value from config.user.json file.
*
* @var string
*/
$template = locate_template(
array(
$this->default_path() . "parts/{$slug}-{$name}.php",
$this->default_path() . "parts/{$slug}.php",
)
);
/**
* WPHOOK: Filter -> change the template directory path.
*
* Defaults to `$this->root/template-parts`.
*
* @param string $default_path The default template path.
* @param string $template The located template file in themes.
* @param array $args The template args.
* @var string
* @since 1.0
*/
$template_path = apply_filters( 'tws_locate_template_path_' . $this->dir, $this->root . '/template-parts', $template, $args );
// Get default slug-name.php.
if ( ! $template && $name && file_exists( $template_path . "/{$slug}-{$name}.php" ) ) {
$template = $template_path . "/{$slug}-{$name}.php";
}
if ( ! $template && ! $name && file_exists( $template_path . "/{$slug}.php" ) ) {
$template = $template_path . "/{$slug}.php";
}
/**
* WPHOOK: Filter -> change template part files from 3rd-party plugins.
*
* @param string $template The located template file.
* @param string $slug The first part of template file name from param.
* @param string $name The second part of the template file name after `-` from param.
* @var string
* @since 1.0
*/
$template = apply_filters( 'tws_locate_template_part_' . $this->dir, $template, $slug, $name );
if ( $template ) {
include $template;
}
}
/**
* Gets template file that can be overridden from themes.
*
* @param string $template_name The template file name.
* @param array $args The arguments to be passed to template file.
* @param string $template_path The template path.
* @param string $default_path The default path.
* @return void
* @since 1.0
*/
public function template( string $template_name, array $args = array(), string $template_path = '', string $default_path = '' ) {
if ( ! empty( $args ) ) {
extract( $args ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract
}
$located = $this->locate( $template_name, $template_path, $default_path );
/**
* WPHOOK: Action -> Fires before getting template file.
*
* @param string $template_name The template file name from param.
* @param string $template_path The template path from param.
* @param string $located The located file path.
* @param array $args The arguments to be passed to template file from param.
* @since 1.0
*/
do_action( 'tws_before_get_template_' . $this->dir, $template_name, $template_path, $located, $args );
// Bail with wrong path info.
if ( ! file_exists( $located ) ) {
_doing_it_wrong( __METHOD__, sprintf( '"%s" does not exist.', esc_html( $located ) ), '1.0' );
return;
}
// Include the located template file.
include $located;
/**
* WPHOOK: Action -> Fires after getting template file.
*
* @param string $template_name The template file name from param.
* @param string $template_path The template path from param.
* @param string $located The located file path.
* @param array $args The arguments to be passed to template file from param.
* @since 1.0
*/
do_action( 'tws_after_get_template_' . $this->dir, $template_name, $template_path, $located, $args );
}
}
}