-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.php
More file actions
2097 lines (1969 loc) · 56.4 KB
/
utils.php
File metadata and controls
2097 lines (1969 loc) · 56.4 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
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
/**
* Utility functions
*
* @package Denman_Utils
*/
namespace Denman_Utils\v2;
use ArrayObject;
use DateTime;
use InvalidArgumentException;
use WP_Post;
use WP_Query;
use WP_Term;
use WP_Taxonomy;
defined('ABSPATH') || exit; // Exit if accessed directly.
/**
* Dummy function that returns first argument.
* @since 1.0.0
* @param mixed $var
* @return mixed
*/
function pass_through($var)
{
return $var;
}
/**
* Check if variable is not null.
*
* Since isset() is a PHP language construct, this wrapper allows us to call it using variable functions
* @since 1.0.0
* @param mixed $var
* @return bool
*/
function is_not_null($var): bool
{
return isset($var);
}
function not_empty($var): bool
{
return !empty($var);
}
/**
* Check whether string starts with substring.
* @deprecated 1.2.0
* @since 1.0.0
* @param string $haystack String to search within.
* @param string $needle String to search for.
* @return boolean
*/
function str_starts_with(string $haystack, string $needle): bool
{
_deprecated_function("Denman_Utils\\v2\\str_starts_with", "6.0", "str_starts_with");
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, 0, $length) === $needle);
}
/**
* Check whether string ends with substring.
* @deprecated 1.2.0
* @since 1.0.0
* @param string $haystack String to search within.
* @param string $needle String to search for.
* @return boolean
*/
function str_ends_with(string $haystack, string $needle): bool
{
_deprecated_function("Denman_Utils\\v2\\str_ends_with", "6.0", "str_ends_with");
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
/**
* Ensure that a string starts with a prefix.
*
* @since 1.0.0
* @param string $str Subject.
* @param string $prefix Substring to look for/prepend.
* @return string
*/
function str_prefix(string $str, string $prefix): string
{
if (!\str_starts_with($str, $prefix)) {
$str = $prefix . $str;
}
return $str;
}
/**
* Ensure that a string ends with a postfix
*
* @since 1.0.0
* @param string $str Subject
* @param string $postfix Substring to look for/append
* @return string
*/
function str_postfix(string $str, string $postfix): string
{
if (!\str_ends_with($str, $postfix)) {
$str .= $postfix;
}
return $str;
}
/**
* Ensure that a string begins and ends with another string
*
* @uses str_prefix
* @uses str_postfix
* @since 1.0.0
* @param string $str Subject.
* @param string $bookend Pre/postfix.
* @return string
*/
function str_bookend(string $str, string $bookend): string
{
$bookend = (string) $bookend;
return str_prefix(str_postfix($str, $bookend), $bookend);
}
/**
* Ensure that a string doesn't start with a prefix
*
* @since 1.0.0
* @param string $str Subject.
* @param string $prefix Substring to look for/remove from start.
* @param int $max Optional. Max number of times to unperfix, <0 means no limit. Default -1.
* @return string
*/
function str_unprefix(string $str, string $prefix, int $max = -1): string
{
$max = $max >= 0 ? $max : -1;
$count = 0;
while ($prefix && ($max === -1 || $count < $max) && \str_starts_with($str, $prefix)) {
$str = substr($str, strlen($prefix));
}
return $str;
}
/**
* Ensure that a string doesn't end with a postfix
*
* @since 1.0.0
* @param string $str Subject.
* @param string $prefix Substring to look for/remove from end.
* @param int $max Optional. Max number of times to unpostfix, <0 means no limit. Default -1.
* @return string
*/
function str_unpostfix(string $str, string $postfix, int $max = -1): string
{
$max = $max >= 0 ? $max : -1;
$count = 0;
while ($postfix && ($max === -1 || $count < $max) && \str_ends_with($str, $postfix)) {
$str = substr($str, 0, -strlen($postfix));
}
return $str;
}
/**
* Check for existance of substring within a string
* @deprecated 1.2.0
* @since 1.0.0
* @param string $haystack String to search within.
* @param string $needle String to search for.
* @param bool $case_insensitive Optional. Whether to ignore case when checking. Default false.
* @return bool
*/
function str_contains(string $haystack, string $needle, bool $case_insensitive = false): bool
{
_deprecated_function("Denman_Utils\\v2\\str_contains", "6.0", "str_contains");
if ($case_insensitive) {
$haystack = strtolower($haystack);
$needle = strtolower($needle);
}
return (strpos($haystack, $needle) !== false);
}
/**
* Truncate a string and append an indicator of truncation
* @since 1.0.0
* @param string $str String to truncate.
* @param int $length Max length for $str before truncation occurs.
* @param int $tolerance Optional. Tolerance for triggering truncation. Default 0.
* @param string $after_truncate Optional. String to append after truncation. Default '…'.
* @return string
*/
function str_truncate(string $str, int $length, int $tolerance = 0, string $after_truncate = '…')
{
if ($length && is_int($length) && $length < strlen($str) - abs($tolerance)) {
$str = trim(substr($str, 0, $length)) . $after_truncate;
}
return $str;
}
/**
* Wrap a string with localized quotemarks
* @since 1.0.0
* @param string $str
* @return string
*/
function str_quote(string $str): string
{
return _x("“", "opening quotemark") . $str . _x("”", "closing quotemark");
}
/**
* Sprintf with named placeholders in `%name%` format
*
* @uses str_bookend
* @since 1.0.0
* @param string $format Format string.
* @param string[]|object Array of search/replace pairs, or object with public non-static properties
* @return string
*/
function sprintf_keys(string $format, $pairs): string
{
$pairs = is_object($pairs) ? get_object_vars($pairs) : $pairs;
if (!$pairs || !is_array($pairs)) {
return $format;
}
$placeholders = array_map(function ($key) {
return str_bookend($key, '%');
}, array_keys($pairs));
return str_replace($placeholders, array_values($pairs), $format);
}
/**
* Re-key an array with a callback that returns new keys for each value
* @since 1.0.0
* @param callable $new_key_cb Callback function.
* @param array $array Source array.
* @param bool $key_first Optional. Whether the key should be the first parameter for the callback. Default true.
* @param bool $value_scoped_cb Optional. Whether the callback provided is a non-static method of each value. Default false.
* @return array
*/
function array_map_keys(callable $new_key_cb, array $array, bool $key_first = true, bool $value_scoped_cb = false): array
{
$output = [];
foreach ($array as $key => $value) {
if (!is_callable($new_key_cb)) {
continue;
}
$cb = $value_scoped_cb ? [$value, $new_key_cb] : $new_key_cb;
$cb_args = $key_first ? [$key, $value, $array] : [$value, $key, $array];
$key = call_user_func_array($cb, $cb_args);
$output[$key] = $value;
}
return $output;
}
/**
* Remove empty values from array
* @since 1.0.0
* @param array $array The array to act upon.
* @param boolean $null_only Optional. Whether to strictly compare to null. Default false.
* @return array
*/
function array_clear_empty(array $array, bool $null_only = false): array
{
return array_values(array_filter($array, function ($value) use ($null_only) {
return $null_only && !is_null($value) || !empty($value);
}));
}
/**
* Assert a value as an array. If not an array or ArrayObject, will create new array with $value as contents
* @since 1.0.0
* @param mixed $value Value to assert.
* @param bool $wrap_null Optional. Whether to wrap null values in an array. Default false.
* @return array
*/
function assert_array(mixed $value, bool $wrap_null = false): array
{
if (is_array($value)) {
return $value;
} else if ($value instanceof ArrayObject) {
return $value->getArrayCopy();
} else if (isset($value) || !!$wrap_null) {
return [$value];
} else {
return [];
}
}
/**
* Remove an item from an array, returning the item
* @since 1.0.0
* @param array $array Source array.
* @param string|int $key Key to remove and return value.
* @return mixed
*/
function array_pluck(array &$array, string|int $key): mixed
{
if (!is_array($array) || !array_key_exists($key, $array)) {
return null;
}
$plucked = $array[$key];
unset($array[$key]);
return $plucked;
}
/**
* Returns only array entries whose keys are listed in an inclusion list.
*
* @since 1.0.0
* @uses resolve_arglist
* @uses array_flatten
* @param array $array Original array to operate on.
* @param array ...$included_keys Keys or arrays of keys you want to keep.
* @return array
*/
function array_include_keys(array $array, ...$included_keys): array
{
$included_keys = array_flatten(resolve_arglist($included_keys));
return array_intersect_key($array, array_flip($included_keys));
}
/**
* Returns only array entries whose keys are not listed in an exclusion list.
*
* @since 1.0.0
* @uses resolve_arglist
* @uses array_flatten
* @param array $array Original array to operate on.
* @param array ...$excluded_keys Keys or arrays of keys you want to remove.
* @return array
*/
function array_exclude_keys(array $array, ...$excluded_keys): array
{
$excluded_keys = array_flatten(resolve_arglist($excluded_keys));
return array_diff_key($array, array_flip($excluded_keys));
}
/**
* Flatten nested arrays.
*
* * Returns only array values, keys are lost
* @since 1.0.0
* @param array[]|mixed[] $array Array containing arrays
* @return mixed[]
*/
function array_flatten(array $array): array
{
$array = array_values($array);
$output = [];
foreach (array_values($array) as $value) {
if (is_array($value)) {
$output = array_merge($output, array_flatten($value));
} else {
$output[] = $value;
}
}
return $output;
}
/**
* Get the nth value in an array. Returns nothing if $array is empty or not an array.
*
* @since 1.0.0
* @uses min_max
* @param mixed[] $array
* @param int $n Position to retrieve value from. If negative, counts back from end of array. WIll not overflow array bounds.
* @return mixed
*/
function array_nth(array $array, int $n): mixed
{
if (!is_array($array)) {
return null;
}
$length = count($array);
if (!$length) {
return null;
}
$n = min_max($n, -$length, $length - 1); // don't overflow array bounds
return array_values($array)[$n >= 0 ? $n : $length + $n];
}
/**
* Check if any entry in an array satisfies the callback.
* @since 1.0.0
* @param array $array
* @param callable $callback Validation callback.
* @param int $callback_args_count Optional. Number of arguments to pass to $callback. Default and maximum is 3.
* @return bool
*/
function array_some(array $array, callable $callback, int $callback_args_count = 3): bool
{
foreach ($array as $key => $value) {
if (call_user_func_array($callback, array_slice([$value, $key, $array], 0, $callback_args_count))) {
return true;
}
}
return false;
}
/**
* Get the first entry in an array that satisfies the callback.
* @since 1.2.0 Returns empty array instead of null if no entry satisfies callback
* @since 1.0.0
* @param array $array
* @param callable $callback Validation callback. Is passed the value, key, and full array for each entry checked.
* @param int $callback_args_count Optional. Number of arguments to pass to $callback. Default and maximum is 3.
* @return array
*/
function array_find(array $array, callable $callback, int $callback_args_count = 3): array
{
foreach ($array as $key => $value) {
if (call_user_func_array($callback, array_slice([$value, $key, $array], 0, $callback_args_count))) {
return ["key" => $key, "value" => $value];
}
}
return [];
}
/**
* Use array_merge_recursive to concatenate arrays
* Arguments will be cast to arrays
* @since 1.0.0
* @return array
*/
function array_concat(array $array, array ...$additions): array
{
$arrays = array_map(function ($value) {
return (array) $value;
}, $additions);
array_unshift($arrays, (array) $array);
return call_user_func_array("array_merge_recursive", $arrays);
}
/**
* Create an array where keys & values are parallel.
* @since 1.0.0
* @param array $array
* @return array
*/
function array_parallel(array $array): array
{
return array_combine($array, $array);
}
/**
* Force an array to be associative, replacing numerical indices with the associated value.
* @since 1.0.0
* @param array $array
* @return array
*/
function array_force_assoc(array $array): array
{
$values = array_values($array);
$keys = array_map(function ($key) use ($array) {
return is_numeric($key) ? $array[$key] : $key;
}, array_keys($array));
return array_combine($keys, $values);
}
/**
* Check whether an array has string keys
* @deprecated 1.2.0
* @since 1.1.0
* @param array $array
* @return bool
*/
function array_has_string_keys(array $array): bool
{
_deprecated_function("Denman_Utils\\v2\\array_has_string_keys", "6.0", "array_is_list");
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
/**
* Get the an adjacent key in an array. Returns null if $array is empty, not an array, or the key is not set.
*
* @since 1.1.0
* @throws LengthException
* @param mixed[] $array
* @param string|int $key Key to look adjacent to.
* @param int $adjacence Desired position relative to the position of $key.
* @return mixed|void
*/
function array_key_adjacent(array $array, $key, int $adjacence)
{
if (!is_array($array)) {
return;
}
$length = count($array);
if (!$length) {
return;
}
$keys = array_keys($array);
$start_n = array_search($key, $keys, true);
if ($start_n === false) {
return;
}
return $keys[$start_n + $adjacence] ?? null;
}
/**
* Map an array of objects to just the required properties.
*
* @see unwrap
* @since 1.0.0
* @param object[] $objects Array of objects.
* @param string[]|string $props Object properties to keep.
* @param string $key_var Optional. Property to use as key in the final array.
* @return array[]
*/
function array_object_vars(array $objects, $props, string $key_var = ""): array
{
$objects = (array) $objects;
$props = unwrap($props);
$output = [];
foreach ($objects as $key => $object) {
if (!empty($key_var) && property_exists($object, $key_var)) {
$key = $object->$key_var;
}
if (is_array($props)) {
$vars = [];
foreach ($props as $prop) {
if (property_exists($object, $prop)) {
$vars[$prop] = $object->$prop;
}
}
} else {
if (property_exists($object, $props)) {
$vars = $object->$props;
}
}
$output[$key] = $vars;
}
return $output;
}
/**
* Get the opposite of an array intersection.
* @since 1.2.0
* @param array $arr1
* @param array $arr2
* @return array
*/
function array_divergence(array $arr1, array $arr2): array
{
return array_merge(
array_diff($arr1, $arr2),
array_diff($arr2, $arr1),
);
}
/**
* Unwrap single value arrays.
*
* Will recursively unwrap single-value arrays until left with either a single
* non-array value, or an array with 0 or 2+ values.
* @since 1.0.0
* @param mixed[]|mixed $array Array to potentially unwrap.
* @param int $limit Optional. Max number of layers to unwrap. Default -1 (no limit).
* @return mixed
*/
function unwrap($array, int $limit = -1)
{
$limit = max($limit, -1);
$count = 0;
while ($count != $limit && is_array($array) && count($array) === 1) {
$array = $array[0];
$count += 1;
}
return $array;
}
/**
* Resolves an array with only one value that is a non empty array
* @since 1.0.0
* @param array[] $arglist
* @return array
*/
function resolve_arglist(array $arglist): array
{
if ($arglist[0] && count($arglist) == 1 && is_array($arglist[0])) {
$arglist = array_values($arglist[0]);
}
return $arglist;
}
/**
* Like wp_parse_args, but limits results to keys defined in 2nd parameter.
* @since 1.0.5
* @param string|array|object $args Arguments to parse.
* @param array $defaults_and_allowed_keys Default values and allowed keys.
* @return array
*/
function parse_args(string|array|object $args, array $defaults_and_allowed_keys = []): array
{
$defaults = array_filter($defaults_and_allowed_keys, "is_string", ARRAY_FILTER_USE_KEY);
// Get allowed keys
$allowed_keys = [];
foreach ($defaults_and_allowed_keys as $key => $value) {
if ($key && is_string($key)) {
$allowed_keys[] = $key;
} else if ($value && is_string($value)) {
$allowed_keys[] = $value;
}
}
// Assign defaults
$parsed_args = wp_parse_args($args, $defaults);
// Limit to allowed keys
$allowed_args = array_include_keys($parsed_args, $allowed_keys);
return $allowed_args;
}
/**
* Compare 2 values exactly
* @since 1.0.0
* @param mixed $a
* @param mixed $b
* @return int
*/
function compare_exact($a, $b): int
{
if ($a === $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
/**
* Generate a function to compare 2 objects or associative arrays by the value of a key
* @since 1.2.0
* @param int|string $key
* @param null|callable $callback
* @return callable
*/
function generate_compare_by_key(int|string $key, ?callable $callback = null): callable
{
return (function ($a, $b) use ($key, $callback) {
$a_val = $a[$key];
$b_val = $b[$key];
if ($callback) {
return $callback($a_val, $b_val);
} else {
if ($a_val == $b_val) {
return 0;
}
return ($a_val < $b_val) ? -1 : 1;
}
});
}
/**
* Get the value of a numeric string.
* @since 1.0.0
* @param string $numeric_str
* @return float|int
*/
function numval(string $numeric_str)
{
if (!defined('LOCALE_DECIMAL_POINT') && ($dec = localeconv()['decimal_point'])) {
define('LOCALE_DECIMAL_POINT', $dec);
}
return strpos($numeric_str, LOCALE_DECIMAL_POINT) === false ? intval($numeric_str) : floatval($numeric_str);
}
/**
* Clamp a number to between min and max values
* @since 1.0.0
* @param float|int $num Value to be clamped.
* @param float|int $min Minimum value.
* @param float|int $max Maximum value.
* @return float|int
*/
function min_max($num, $min, $max)
{
return max(min($num, $max), $min);
}
/**
* Get contents of current output buffer and clear without turning buffer off.
* @since 1.0.0
* @return string
*/
function ob_get_refresh(): string
{
$contents = ob_get_contents();
if ($contents !== false) ob_clean();
return $contents ?: "";
}
/**
* Get the buffered output of a callback
* @since 1.0.0
* @param callable $output_fn Function to buffer.
* @param array $args Optional. Arguments for output function.
* @param boolean $output_only Optional. Return only buffered output. Default true.
* @return string|mixed[]
*/
function ob_return(callable $output_fn, array $args = [], bool $output_only = true)
{
if (!is_callable($output_fn)) {
return '';
}
ob_start();
$returned = call_user_func_array($output_fn, (array) $args);
$output = ob_get_clean();
return $output_only ? $output : [$output, $returned, "output" => $output, "return" => $returned];
}
/**
* Like get_template_part() but lets you pass args to the template file.
* Args are available in the template as $template_args array.
* Based on Humanmade's hm_get_template_part().
*
* @since 1.0.0
* @uses resolve_post() to resolve $template_args["post"].
* @global $post
* @param string[]|string $path Path(s) to template file. If passed an array of strings, it will treat attempt to join them with hyphens into a single path. If no such file can be found, it will try again iteratively, dropping the last piece until a valid file can be found.
* @param mixed[]|object|string $template_args Optional. wp_args style argument list, with some special keys. Default empty array.
* @param bool $template_args["set_post_data"] Setup post data for the template
* @param bool $template_args["return"] If truthy, buffer template output and return as string, if `false` return `false`.
* @param WP_Post|int|string $template_args["post"] If seting-up post data, use this post, falling back to the global $post.
* @param mixed[]|object|string $cache_args Optional. Default empty array.
* @return void|string
*/
function get_template_part_with($path, $template_args = [], $cache_args = [])
{
global $post;
if (is_array($path)) {
$path = array_filter($path, "is_string");
} else if (!is_string($path)) {
throw new InvalidArgumentException("\$path must be a string or array of strings");
}
// Iterate over possible file paths
$path = assert_array($path);
$file = null;
$stylesheet_dir = get_stylesheet_directory();
$template_dir = get_template_directory();
while (empty($file) && $path) {
$test_path = str_prefix(join("-", $path), "/") . ".php";
if (file_exists($stylesheet_dir . $test_path)) {
$file = $stylesheet_dir . $test_path;
} elseif (file_exists($template_dir . $test_path)) {
$file = $template_dir . $test_path;
}
array_pop($path);
}
$file = $file ?? "";
$template_args = wp_parse_args($template_args);
$cache_args = wp_parse_args($cache_args);
if ($cache_args) {
foreach ($template_args as $key => $value) {
if (is_scalar($value) || is_array($value)) {
$cache_args[$key] = $value;
} else if (is_object($value) && method_exists($value, 'get_id')) {
$cache_args[$key] = $value->get_id();
}
}
if (($cache = wp_cache_get($file, serialize($cache_args))) !== false) {
if (!empty($template_args['return'])) {
return $cache;
}
echo $cache;
return;
}
}
if (!empty($template_args['set_post_data'])) {
$post = resolve_post($template_args['post'] ?? 0) ?? $post;
setup_postdata($post);
}
ob_start();
$return = require $file;
$data = ob_get_clean();
if (!empty($template_args['set_post_data'])) {
wp_reset_postdata();
}
if ($cache_args) {
wp_cache_set($file, $data, serialize($cache_args), 3600);
}
if (!empty($template_args['return'])) {
return ($return === false ? false : $data);
}
echo $data;
}
/**
* Write to the debug log when unable to use var_dump()
* @since 1.0.0
* @param mixed ...$values A series of values
*/
function log_val(...$values)
{
error_log(print_r($values, true));
}
/**
* Returns the first truthy argument, or the last argument.
* * If passed a single non-empty Array, will return the first truthy value, or the last entry.
*
* @since 1.0.0
* @uses resolve_arglist
* @param mixed[]|mixed ...$values A series or array of values
* @return mixed
*/
function fallback(...$values)
{
$values = resolve_arglist($values);
foreach ($values as $result) {
if (!empty($result)) {
return $result;
}
}
return $result;
}
/**
* Returns the first argument that passes a validation callback, or the last argument.
* * If passed a single non-empty Array, will return the first valid value, or the last entry.
*
* @since 1.0.0
* @throws InvalidArgumentException if $validation_callback is not callable
* @param callable $validation_callback
* @param mixed[]|mixed ...$values
* @return mixed
*/
function fallback_until(callable $validation_callback, ...$values)
{
if (!is_callable($validation_callback)) {
throw new InvalidArgumentException("First argument in fallback_until() was not callable");
}
$values = resolve_arglist($values);
foreach ($values as $result) {
if (call_user_func($validation_callback, $result)) {
return $result;
}
}
return $result;
}
/**
* Pass a variable to a validation callback, assigning the first passing fallback value if it fails.
* * If passed a single non-empty Array, will return the first valid value, or the last entry.
*
* @since 1.0.0
* @param mixed $subject Variable to test/override. Passed by reference.
* @param callable $validation_callback Validates $subject and $values by the truthiness of the return value.
* @param mixed[]|mixed ...$values Fallback variables. If none pass the validation callback, the last will be used.
*/
function fallback_assign(&$subject, callable $validation_callback, ...$values): void
{
if (!is_callable($validation_callback)) {
trigger_error("First argument in validate() was not callable");
return;
}
$values = resolve_arglist($values);
array_unshift($values, $subject);
foreach ($values as $value) {
$subject = $value;
if (call_user_func($validation_callback, $subject)) {
return;
}
}
}
/**
* Run a series of callbacks until one returns a value that satisfies the validation callback, returning that value.
* * Returns either the first valid result, or the result of the last callback.
* @since 1.0.0
* @param callable $validation_callback
* @param callable[]|callable $progressive_callbacks
* @return mixed
*/
function fallback_progression(callable $validation_callback, ...$progressive_callbacks)
{
if (!is_callable($validation_callback)) {
trigger_error("First argument in validate() was not callable");
return;
}
$progressive_callbacks = array_filter(resolve_arglist($progressive_callbacks), "is_callable");
$result = null;
foreach ($progressive_callbacks as $callback) {
$result = call_user_func($callback);
if (call_user_func($validation_callback, $result)) {
return $result;
}
}
return $result;
}
/**
* Resolve a variable to a post if possible.
*
* @uses get_post_by_slug
* @since 1.0.0
* @param WP_Post|int|string $post Optional. Variable to be resolved to a post, by ID or slug.
* @param ?string $post_type Optional. Desired post type, or "any".
* @return WP_Post|null
*/
function resolve_post($post = null, string $post_type = "")
{
if (empty($post)) {
return $GLOBALS['post'] ?? null;
}
switch (gettype($post)) {
case 'integer': // Find by ID
$post = get_post($post);
break;
case 'string': // Find by slug
$post = get_post_by_slug($post, $post_type ?: "any");
break;
}
if (is_a($post, 'WP_Post') && (!$post_type || in_array($post_type, [$post->post_type, "any", ""]))) {
return $post;
}
}
/**
* Resolve a variable to a taxonomy if possible.
* @since 1.0.0
* @param WP_Taxonomy|string $taxonomy Variable to be resolved to a taxonomy.
* @return ?WP_Taxonomy
*/
function resolve_taxonomy($taxonomy)
{
if (is_string($taxonomy)) {
$taxonomy = get_taxonomy($taxonomy);
}
if (is_a($taxonomy, "WP_Taxonomy")) {
return $taxonomy;
}
}
/**
* Get the primary key value of a WordPress object
* @since 1.0.0
* @param WP_Post|WP_Term $obj
* @return int
*/
function resolve_object_id(Object $obj): int
{
$id_props = ["ID", "term_id"];
foreach ($id_props as $prop) {
if (property_exists($obj, $prop)) {
return $obj->{$prop};
}
}
return 0;
}
/**
* Get a flat array of all descendants for a given post.
* @since 1.1.0
* @param WP_Post|int|string|null $post
* @param int $depth
* @param bool $check_post_type
* @return WP_Post[]
*/
function get_post_descendants($post = null, int $depth = -1, bool $check_post_type = true): array
{
$post = resolve_post($post);
if ($check_post_type && !is_post_type_hierarchical($post->post_type)) {
return [];
}
$descendants = [];
$children = get_posts([
"post_type" => $post->post_type,
"post_parent" => $post->ID,
"posts_per_page" => -1
]);
foreach ($children as $child) {
$descendants[] = $child;
if ($depth !== 0) {
$descendants = array_merge($descendants, get_post_descendants($child, $depth - 1, false));
}
}
return $descendants;
}
/**
* Collapse an array to only (a) string keys for truthy values and (b) numerically indexed strings
*
* modeled after [classnames](https://www.npmjs.com/package/classnames) on NPM
*
* @since 1.2.0 Returns string instead of string array
* @since 1.0.0
* @param mixed[] $classes