Assets.php
18.9 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
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
<?php
namespace FakerPress;
/**
* Class used to register and enqueue assets across our plugins.
*
* @since 0.5.1
*/
class Assets {
/**
* A static variable that holds a dynamic instance of the class
*
* @since 0.5.1
* @var null|object The dynamic version of this class
*/
public static $instance = null;
/**
* Stores all the Assets and it's configurations.
*
* @since 0.5.1
*
* @var array
*/
protected $assets = [];
/**
* Stores the localized scripts for reference.
*
* @since 0.5.1
*
* @var array
*/
private $localized = [];
/**
* Static Singleton Factory Method.
*
* @since 0.5.1
*
* @return self
*/
public static function instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Register the Methods in the correct places.
*
* @since 0.5.1
*/
public function __construct() {
// Hook the actual registering of.
add_action( 'init', [ $this, 'register_in_wp' ], 1, 0 );
}
/**
* Register the Assets on the correct hooks.
*
* @since 0.5.1
*
* @return void
*/
public function register_in_wp( $assets = null ) {
if ( is_null( $assets ) ) {
$assets = $this->assets;
}
if ( ! is_array( $assets ) ) {
$assets = [ $assets ];
}
uasort( $assets, 'fp_sort_by_priority' );
foreach ( $assets as $asset ) {
// Asset is already registered.
if ( $asset->is_registered ) {
continue;
}
if ( 'js' === $asset->type ) {
// Script is already registered.
if ( wp_script_is( $asset->slug, 'registered' ) ) {
continue;
}
wp_register_script( $asset->slug, $asset->url, $asset->deps, $asset->version, $asset->in_footer );
// Register that this asset is actually registered on the WP methods.
$asset->is_registered = wp_script_is( $asset->slug, 'registered' );
} else {
// Style is already registered.
if ( wp_style_is( $asset->slug, 'registered' ) ) {
continue;
}
wp_register_style( $asset->slug, $asset->url, $asset->deps, $asset->version, $asset->media );
// Register that this asset is actually registered on the WP methods.
$asset->is_registered = wp_style_is( $asset->slug, 'registered' );
}
// If we don't have an action we don't even register the action to enqueue.
if ( empty( $asset->action ) ) {
continue;
}
// Now add an action to enqueue the registered assets.
foreach ( (array) $asset->action as $action ) {
// Enqueue the registered assets at the appropriate time.
if ( did_action( $action ) > 0 ) {
$this->enqueue();
} else {
add_action( $action, [ $this, 'enqueue' ], $asset->priority );
}
}
}
}
/**
* Enqueues registered assets based on their groups.
*
* @since 0.5.1
*
* @uses Assets::enqueue()
*
* @param string|array $groups Which groups will be enqueued.
*/
public function enqueue_group( $groups ) {
$assets = $this->get();
$enqueue = [];
foreach ( $assets as $asset ) {
if ( empty( $asset->groups ) ) {
continue;
}
$intersect = array_intersect( (array) $groups, $asset->groups );
if ( empty( $intersect ) ) {
continue;
}
$enqueue[] = $asset->slug;
}
$this->enqueue( $enqueue );
}
/**
* Enqueues registered assets.
*
* This method is called on whichever action (if any) was declared during registration.
*
* It can also be called directly with a list of asset slugs to forcibly enqueue, which may be
* useful where an asset is required in a situation not anticipated when it was originally
* registered.
*
* @since 0.5.1
*
* @param string|array $forcibly_enqueue
*/
public function enqueue( $forcibly_enqueue = null ) {
$forcibly_enqueue = array_filter( (array) $forcibly_enqueue );
$assets = $this->get();
foreach ( $assets as $asset ) {
// Should this asset be enqueued regardless of the current filter/any conditional requirements?
$must_enqueue = in_array( $asset->slug, $forcibly_enqueue );
$in_filter = in_array( current_filter(), (array) $asset->action );
// Skip if we are not on the correct filter (unless we are forcibly enqueuing).
if ( ! $in_filter && ! $must_enqueue ) {
continue;
}
// If any single conditional returns true, then we need to enqueue the asset.
if ( empty( $asset->action ) && ! $must_enqueue ) {
continue;
}
// If this asset was late called
if ( ! $asset->is_registered ) {
$this->register_in_wp( $asset );
}
// Default to enqueuing the asset if there are no conditionals,
// and default to not enqueuing it if there *are* conditionals.
$enqueue = empty( $asset->conditionals );
if ( ! $enqueue ) {
// Reset Enqueue.
$enqueue = [];
// Which is the operator?
$conditional_operator = fp_array_get( $asset->conditionals, 'operator', null, 'OR' );
// If we have a set of conditionals we loop on then and get if they are true.
foreach ( $asset->conditionals as $key => $conditional ) {
// Avoid doing anything to the operator
if ( 'operator' === $key ) {
continue;
}
$enqueue[] = call_user_func( $conditional );
}
// By default we use OR for backwards compatibility.
if ( 'OR' === $conditional_operator ) {
$enqueue = in_array( true, $enqueue );
} else {
$enqueue = ! in_array( false, $enqueue );
}
}
/**
* Allows developers to hook-in and prevent an asset from been loaded.
*
* @since 0.5.1
*
* @param bool $enqueue If we should enqueue or not a given asset.
* @param object $asset Which asset we are dealing with.
*/
$enqueue = apply_filters( 'fakerpress_asset_enqueue', $enqueue, $asset );
/**
* Allows developers to hook-in and prevent an asset from been loaded
*
* @since 0.5.1
*
* @param bool $enqueue If we should enqueue or not a given asset.
* @param object $asset Which asset we are dealing with.
*/
$enqueue = apply_filters( "fakerpress_asset_enqueue_{$asset->slug}", $enqueue, $asset );
if ( ! $enqueue && ! $must_enqueue ) {
continue;
}
if ( 'js' === $asset->type ) {
wp_enqueue_script( $asset->slug );
// Only localize on JS and if we have data.
if ( ! empty( $asset->localize ) ) {
// Makes sure we have an Array of Localize data.
if ( is_object( $asset->localize ) ) {
$localization = [ $asset->localize ];
} else {
$localization = (array) $asset->localize;
}
/**
* Check to ensure we haven't already localized it before.
*
* @since 0.5.1
*/
foreach ( $localization as $localize ) {
if ( in_array( $localize->name, $this->localized ) ) {
continue;
}
// If we have a Callable as the Localize data we execute it.
if ( is_callable( $localize->data ) ) {
$localize->data = call_user_func( $localize->data, $asset );
}
wp_localize_script( $asset->slug, $localize->name, $localize->data );
$this->localized[] = $localize->name;
}
}
} else {
wp_enqueue_style( $asset->slug );
}
$asset->already_enqueued = true;
}
}
/**
* Returns the path to a minified version of a js or css file, if it exists.
* If the file does not exist, returns false.
*
* @since 0.5.1
*
* @param string $url The absolute URL to the un-minified file.
*
* @return string|false The url to the minified version or false, if file not found.
*/
public static function maybe_get_min_file( $url ) {
static $wpmu_plugin_url;
static $wp_plugin_url;
static $wp_content_url;
static $plugins_url;
static $base_dirs;
$urls = [];
if ( ! isset( $wpmu_plugin_url ) ) {
$wpmu_plugin_url = set_url_scheme( WPMU_PLUGIN_URL );
}
if ( ! isset( $wp_plugin_url ) ) {
$wp_plugin_url = set_url_scheme( WP_PLUGIN_URL );
}
if ( ! isset( $wp_content_url ) ) {
$wp_content_url = set_url_scheme( WP_CONTENT_URL );
}
if ( ! isset( $plugins_url ) ) {
$plugins_url = plugins_url();
}
if ( ! isset( $base_dirs ) ) {
$base_dirs[ WPMU_PLUGIN_DIR ] = wp_normalize_path( WPMU_PLUGIN_DIR );
$base_dirs[ WP_PLUGIN_DIR ] = wp_normalize_path( WP_PLUGIN_DIR );
$base_dirs[ WP_CONTENT_DIR ] = wp_normalize_path( WP_CONTENT_DIR );
}
if ( 0 === strpos( $url, $wpmu_plugin_url ) ) {
// URL inside WPMU plugin dir.
$base_dir = $base_dirs[ WPMU_PLUGIN_DIR ];
$base_url = $wpmu_plugin_url;
} elseif ( 0 === strpos( $url, $wp_plugin_url ) ) {
// URL inside WP plugin dir.
$base_dir = $base_dirs[ WP_PLUGIN_DIR ];
$base_url = $wp_plugin_url;
} elseif ( 0 === strpos( $url, $wp_content_url ) ) {
// URL inside WP content dir.
$base_dir = $base_dirs[ WP_CONTENT_DIR ];
$base_url = $wp_content_url;
} elseif ( 0 === strpos( $url, $plugins_url ) ) {
$base_dir = $base_dirs[ WP_PLUGIN_DIR ];
$base_url = $plugins_url;
} else {
// Resource needs to be inside wp-content or a plugins dir.
return false;
}
$script_debug = defined( 'SCRIPT_DEBUG' ) && fp_is_truthy( SCRIPT_DEBUG );
// Strip the plugin URL and make this relative.
$relative_location = str_replace( $base_url, '', $url );
if ( $script_debug ) {
// Add the actual url after having the min file added.
$urls[] = $relative_location;
}
// If needed add the Min Files.
if ( substr( $relative_location, -3, 3 ) === '.js' ) {
$urls[] = substr_replace( $relative_location, '.min', - 3, 0 );
} elseif ( substr( $relative_location, -4, 4 ) === '.css' ) {
$urls[] = substr_replace( $relative_location, '.min', - 4, 0 );
}
if ( ! $script_debug ) {
// Add the actual url after having the min file added.
$urls[] = $relative_location;
}
// Check for all Urls added to the array.
foreach ( $urls as $partial_path ) {
$file_path = wp_normalize_path( $base_dir . $partial_path );
$file_url = $base_url . $partial_path;
if ( file_exists( $file_path ) ) {
return $file_url;
}
}
// If we don't have any real file return false.
return false;
}
public function get_resource_url( $asset = null ) {
$extension = pathinfo( $asset->file, PATHINFO_EXTENSION );
$is_vendor = strpos( $asset->file, 'vendor/' ) !== false ? true : false;
$resource_path = 'src/resources/';
if ( ! $is_vendor ) {
switch ( $extension ) {
case 'css':
$resource_path .= 'css/';
break;
case 'js':
$resource_path .= 'js/';
break;
case 'scss':
$resource_path .= 'scss/';
break;
case 'pcss':
$resource_path .= 'pcss/';
break;
}
}
$resource = $resource_path . $asset->file;
$file = wp_normalize_path( $asset->origin_path . $resource );
// Turn the Path into a URL
$url = plugins_url( basename( $asset->file ), $file );
/**
* Filters the resource URL
*
* @since 0.5.1
*
* @param $url
* @param $resource
* @param $asset
*/
$url = apply_filters( 'fakerpress_asset_resource_url', $url, $resource, $asset );
return $url;
}
/**
* Register an Asset and attach a callback to the required action to display it correctly.
*
* @since 0.5.1
*
* @param object $origin The main object for the plugin you are enqueueing the asset for.
* @param string $slug Slug to save the asset - passes through `sanitize_title_with_dashes()`.
* @param string $file The asset file to load (CSS or JS), including non-minified file extension.
* @param array $deps The list of dependencies.
* @param string|array|null $action The WordPress action(s) to enqueue on, such as `wp_enqueue_scripts`,
* `admin_enqueue_scripts`, or `login_enqueue_scripts`.
* @param string|array $arguments {
* Optional. Array or string of parameters for this asset.
*
* @type array|string|null $action The WordPress action(s) this asset will be enqueued on.
* @type int $priority Priority in which this asset will be loaded on the WordPress action.
* @type string $file The relative path to the File that will be enqueued, uses the $origin to get the full path.
* @type string $type Asset Type, `js` or `css`.
* @type array $deps An array of other asset as dependencies.
* @type string $version Version number, used for cache expiring.
* @type string $media Used only for CSS, when to load the file.
* @type bool $in_footer A boolean determining if the javascript should be loaded on the footer.
* @type array|object $localize {
* Variables needed on the JavaScript side.
*
* @type string $name Name of the JS variable.
* @type string|array $data Contents of the JS variable.
* }
* @type callable[] $conditionals An callable method or an array of them, that will determine if the asset is loaded or not.
* }
*
* @return object|false The registered object or false on error.
*/
public function register( $origin, $slug, $file, $deps = [], $action = null, $arguments = [] ) {
// Prevent weird stuff here.
$slug = sanitize_title_with_dashes( $slug );
if ( $this->exists( $slug ) ) {
return $this->get( $slug );
}
if ( is_string( $origin ) ) {
// Origin needs to be a class with a `instance` method and a Version constant.
if ( class_exists( $origin ) && method_exists( $origin, 'instance' ) && defined( $origin . '::VERSION' ) ) {
$origin = call_user_func( [ $origin, 'instance' ] );
}
}
if ( is_object( $origin ) ) {
$origin_name = get_class( $origin );
if ( ! defined( $origin_name . '::VERSION' ) ) {
// If we have a Object and we don't have instance or version.
return false;
}
} else {
return false;
}
// Fetches the version on the Origin Version constant.
$version = constant( $origin_name . '::VERSION' );
// Default variables to prevent notices.
$defaults = [
'slug' => null,
'file' => false,
'url' => false,
'action' => null,
'priority' => 10,
'type' => null,
'deps' => [],
'groups' => [],
'version' => $version,
'media' => 'all',
'in_footer' => true,
'is_registered' => false,
'origin_path' => null,
'origin_url' => null,
'origin_name' => null,
// Bigger Variables at the end.
'localize' => [],
'conditionals' => [],
];
// Merge Arguments.
$asset = (object) wp_parse_args( $arguments, $defaults );
// Enforce these one.
$asset->slug = $slug;
$asset->file = $file;
$asset->deps = $deps;
$asset->action = $action;
$asset->origin_file = $origin::$_file;
$asset->origin_path = trailingslashit( ! empty( $origin->plugin_path ) ? $origin->plugin_path : $origin->path() );
$asset->origin_name = $origin_name;
// Origin URL might throw notices so we double check.
$asset->origin_url = trailingslashit( ! empty( $origin->plugin_url ) ? $origin->plugin_url : $origin->url() );
// If we don't have a type on the arguments we grab from the File path.
if ( is_null( $asset->type ) ) {
if ( substr( $asset->file, -3, 3 ) === '.js' ) {
$asset->type = 'js';
} elseif ( substr( $asset->file, -4, 4 ) === '.css' ) {
$asset->type = 'css';
}
}
// If asset type is wrong don't register.
if ( ! in_array( $asset->type, [ 'js', 'css' ], true ) ) {
return false;
}
/**
* Filter to change version number on assets.
*
* @since 0.5.1
*
* @param string $version
* @param object $asset
*/
$asset->version = apply_filters( 'fakerpress_asset_version', $asset->version, $asset );
// Clean these
$asset->priority = absint( $asset->priority );
$asset->in_footer = (bool) $asset->in_footer;
$asset->media = esc_attr( $asset->media );
// Ensures that we have a priority over 1.
if ( $asset->priority < 1 ) {
$asset->priority = 1;
}
// Setup the actual URL.
if ( filter_var( $asset->file, FILTER_VALIDATE_URL ) ) {
$asset->url = $asset->file;
} else {
$asset->url = $this->maybe_get_min_file( $this->get_resource_url( $asset ) );
}
// Parse the Localize asset arguments.
$asset = $this->parse_argument_localize( $asset );
// Looks for a single conditional callable and places it in an Array.
if ( ! empty( $asset->conditionals ) && is_callable( $asset->conditionals ) ) {
$asset->conditionals = [ $asset->conditionals ];
}
// Groups is always an array of unique strings.
if ( ! empty( $asset->groups ) ) {
$asset->groups = (array) $asset->groups;
$asset->groups = array_filter( $asset->groups, 'is_string' );
$asset->groups = array_unique( $asset->groups );
}
/**
* Filter an Asset loading variables.
*
* @since 0.5.1
*
* @param object $asset
*/
$asset = apply_filters( 'fakerpress_asset_pre_register', $asset );
// Set the Asset on the array of notices.
$this->assets[ $slug ] = $asset;
// Sorts by priority.
uasort( $this->assets, 'fp_sort_by_priority' );
// Return the Slug because it might be modified.
return $asset;
}
/**
* Parse the localize argument for a given asset object.
*
* @since 0.5.1
*
* @param stdClass $asset Argument that set that asset.
*
* @return stdClass
*/
public function parse_argument_localize( \stdClass $asset ) {
if ( empty( $asset->localize ) ) {
return $asset;
}
if ( ! is_array( $asset->localize ) && ! is_object( $asset->localize ) ) {
return $asset;
}
// Cast to array for safety.
$asset->localize = (array) $asset->localize;
// Allow passing of a single instance.
if ( ! empty( $asset->localize['name'] ) ) {
// Reset to empty when name was not empty data was not set.
$asset->localize = ! isset( $asset->localize['data'] ) ? [] : [ (object) $asset->localize ];
}
// Cast all instances as object.
$asset->localize = array_map( function( $values ) {
return (object) $values;
}, $asset->localize );
return $asset;
}
/**
* Removes an Asset from been registered and enqueue.
*
* @since 0.5.1
*
* @param string $slug Slug of the Asset.
*
* @return bool
*/
public function remove( $slug ) {
if ( ! $this->exists( $slug ) ) {
return false;
}
unset( $this->assets[ $slug ] );
return true;
}
/**
* Get the Asset Object configuration.
*
* @since 0.5.1
*
* @param string $slug Slug of the Asset.
*
* @return array|object|null Array of asset objects, single asset object, or null if looking for a single asset but
* it was not in the array of objects.
*/
public function get( $slug = null ) {
uasort( $this->assets, 'fp_sort_by_priority' );
if ( is_null( $slug ) ) {
return $this->assets;
}
// Prevent weird stuff here.
$slug = sanitize_title_with_dashes( $slug );
if ( ! empty( $this->assets[ $slug ] ) ) {
return $this->assets[ $slug ];
}
return null;
}
/**
* Checks if an Asset exists.
*
* @since 0.5.1
*
* @param string $slug Slug of the Asset.
*
* @return bool
*/
public function exists( $slug ) {
return is_object( $this->get( $slug ) ) ? true : false;
}
}