/
Chequer.php
1080 lines (930 loc) · 41.6 KB
/
Chequer.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
/*
* CHEQUER for PHP
*
* Copyright (c)2013 Rafal Lindemann <rl@stamina.pl>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. *
*/
namespace Chequer {
interface Chequerable {
/**
* @param $operator Operator name
* @param $value Value to operate on
* @param $rule Operator parameter
* @param $caller Chequer object calling this. If this function doesn't support this operator,
* it should call $caller->chequerOperator(..., $caller)
*/
function chequerOperator( $operator, $value, $rule, $caller );
/**
* @param $typecast Typecast name
* @param $callArgs Empty array for @typecast, array($value) for @typecast()
* @param $caller Chequer object calling this. If this function doesn't support this typecast,
* it should call $caller->chequerTypecast(..., $caller)
*/
function chequerTypecast( $typecast, $callArgs, $caller );
}
}
namespace {
class Chequer implements \Chequer\Chequerable {
protected $query;
protected $matchAll;
protected $deepArrays;
protected $shorthandSyntax = true;
protected $strictMode = false;
static protected $globalOperators = array(
'=' => 'eq',
'==' => 'eq',
'===' => 'same',
'>' => 'gt',
'>=' => 'gte',
'<' => 'lt',
'<=' => 'lte',
'!' => 'not',
'!=' => 'ne',
'~' => 'regex',
'&&' => 'and',
'||' => 'orvalue',
'+' => 'add',
'-' => 'sub',
'*' => 'mult',
'/' => 'div',
':=' => 'set',
';' => 'noop',
'rules' => 'rule',
);
static protected $globalTypecasts = array();
static protected $globalRules = array();
protected $operators;
protected $specialChars = '$.@';
protected $typecasts = array();
protected $rules = array();
/**
* @param $query Default query
* @param $matchAll Default matchAll
* @param $deepArrays Enable searching for subkeys in arrays
*/
function __construct( $query = false, $matchAll = null, $deepArrays = true ) {
$this->query = $query;
$this->matchAll = $matchAll;
$this->deepArrays = $deepArrays;
$this->operators = self::$globalOperators;
$this->typecasts = self::$globalTypecasts;
$this->rules = self::$globalRules;
}
/** @return Chequer */
public static function create( $query = false, $matchAll = null, $deepArrays = true ) {
return new self($query, $matchAll, $deepArrays);
}
public function getQuery() {
return $this->query;
}
/** @return self */
public function setQuery( $query ) {
$this->query = $query;
return $this;
}
public function getDeepArrays() {
return $this->deepArrays;
}
/** Enable searching for subkeys in subarrays. Set it to the deepest level this function
* should work.
* @return self
*/
public function setDeepArrays( $deepArrays ) {
$this->deepArrays = $deepArrays;
return $this;
}
public function getMatchAll() {
return $this->matchAll;
}
/** @return self */
public function setMatchAll( $matchAll ) {
$this->matchAll = $matchAll;
return $this;
}
public function getShorthandSyntax() {
return $this->shorthandSyntax;
}
/**
* Enables or disables support for shorthand syntax:
*
* "$gt 25"
*
* @return self */
public function setShorthandSyntax( $shorthandSyntax ) {
$this->shorthandSyntax = $shorthandSyntax;
return $this;
}
public function getStrictMode() {
return $this->strictMode;
}
/**
* Strict mode will throw exceptions
*
* @return self */
public function setStrictMode( $strictMode ) {
$this->strictMode = $strictMode;
return $this;
}
/** @return self */
public function addTypecasts($typecasts) {
$this->typecasts = array_merge($this->typecasts, $typecasts);
return $this;
}
/** @return self */
public function addTypecast($name, $typecast) {
$this->typecasts[$name] = $typecast;
return $this;
}
/**
* Adds predefined rules.
*
* @return self */
public function addRules($rules) {
$this->rules = array_merge($this->rules, $rules);
return $this;
}
/**
* Adds a predefined rule.
*
* @return self */
public function addRule($name, $rule) {
$this->rules[$name] = $rule;
return $this;
}
public function getRules() {
return $this->rules;
}
public static function addGlobalOperators($operators) {
self::$globalOperators = array_merge(self::$globalOperators, $operators);
}
public static function getGlobalOperators() {
return self::$globalOperators;
}
public static function addGlobalTypecasts($typecasts) {
self::$globalTypecasts = array_merge(self::$globalTypecasts, $typecasts);
}
public static function getGlobalTypecasts() {
return self::$globalTypecasts;
}
public static function addGlobalRules($rules) {
self::$globalRules = array_merge(self::$globalRules, $rules);
}
public static function getGlobalRules() {
return self::$globalRules;
}
/** Checks rules against current server environment.
* Available keys are everything from $_SERVER, _ENV, _COOKIE, _SESSION, _GET, _POST, _REQUEST.
*
* */
public static function checkEnvironment( $query, $matchAll = true ) {
$ch = new Chequer($query, $matchAll);
$table = array(
$_SERVER,
'_SERVER' => $_SERVER,
'_ENV' => $_ENV,
'_COOKIE' => isset($_COOKIE) ? $_COOKIE : array(),
'_SESSION' => isset($_SESSION) ? $_SESSION : array(),
'_GET' => isset($_GET) ? $_GET : array(),
'_POST' => isset($_POST) ? $_POST : array(),
'_REQUEST' => isset($_REQUEST) ? $_REQUEST : array(),
);
return $ch->check($table);
}
public static function checkValue( $value, $query, $matchAll = null ) {
$ch = new self($query, $matchAll);
return $ch->check($value);
}
/** Creates Chequer instance with query in shorthand syntax. This way you don't have to prepend it with '$ '.
* @param $query Any non-string query will be queried traditionally.
* @return Chequer
* */
public static function shorthand($query, $matchAll = null) {
if (is_string($query) && $query && $query{0} !== '$') $query = '$ ' . $query;
return new self($query, $matchAll = null);
}
public function __invoke( $value ) {
return $this->check($value);
}
public function __toString() {
return is_string($this->query) ? $this->query : json_encode($this->query,
PHP_VERSION_ID > 50400 ? JSON_UNESCAPED_SLASHES : 0);
}
/** Checks the value against the instance's query
*
* See Readme.md for documentation
*/
public function check( $value, $matchAll = null ) {
return $this->query($value, $this->query, $matchAll === null ? $this->matchAll : $matchAll);
}
/** Alias for check()
*/
public function evaluate( $value, $matchAll = null ) {
return $this->check($value, $matchAll);
}
/** Run the query for every element in the array or iterator and return the results.
* Non-numeric keys are preserved.
*
* @param $filter If TRUE, results equal to NULL will not be included in the result.
*/
public function walk($data, $filter = true) {
$results = array();
foreach($data as $key => $value) {
if (($result = $this->query($value, $this->query)) !== null || !$filter) {
if (is_int($key)) {
$results[] = $result;
} else {
$results[$key] = $result;
}
}
}
return $results;
}
/** Run the query for every element in the array or iterator and merge the results together.
*
* Arrays are merged, scalars are pushed to the end, NULLs are discarded.
*/
public function merge($data) {
$results = array();
foreach($data as $key => $value) {
if (($result = $this->query($value, $this->query)) !== null) {
if (is_array($result)) {
$results = array_merge($results, $result);
} else {
$results[] = $result;
}
}
}
return $results;
}
/** Checks the value against provided shorthand query.
* @param $query Any non-string query will be queried traditionally. You don't have to prepend it with '$ '
* */
public function shorthandQuery($value, $query) {
if (is_string($query) && ($length = strlen($query)) > 0) {
// remove '$ '
if ($length > 2 && $query{0} === '$' && $query{1} === ' ') $query = substr($query, 2);
return $this->shorthandQueryRun($value, $query);
} else {
return $this->query($value, $query);
}
}
/** Checks the value against provided query
*
* See Readme.md for documentation
*
* @param $value Value to check
* @param $query Query to match
* @param $matchAll TRUE to require all first level queries, FALSE to require only one
* */
public function query( $value, $query, $matchAll = null ) {
if ($query === null || $query === false) {
// null and false are compared strictly
return $value === $query;
} elseif (is_scalar($query)) {
if ($this->shorthandSyntax && is_string($query) && strlen($query) > 1 && ($query{0} === '$' || $query{0} === '\\')) {
// shorthand syntax
if ($query{0} === '\\' && $query{1} === '$') {
// unescape and compare
return $value == substr($query, 1);
}
// make '$ $op...' into '$op...'
if ($query[1] === ' ') $query = substr($query, 2);
return $this->shorthandQueryRun($value, $query);
} elseif (is_array($value) && is_bool($query) == false) {
// string/number queries are searched in arrays
return in_array($query, $value);
} else {
// other scalar queries are compared non-strictly
return $value == $query;
}
} elseif (is_object($query) && is_callable($query)) {
// callable queries
if ($query instanceof Chequer) return $query->check($value, $matchAll);
return call_user_func($query, $value, $query, $matchAll);
}
// query is an array....
if ($matchAll === null)
$matchAll = false === (isset($query[0]) && is_scalar($query[0]));
$result = null;
try {
foreach ($query as $key => $rule) {
$result = null;
if (is_int($key)) {
$result = $this->query($value, $rule);
} elseif ($key{0} === '$') {
if ($key === '$') {
$matchAll = ($rule === 'OR' || $rule === 'or') ? false : $rule == true;
} elseif ($key{1} === ' ') {
$result = $this->query($this->shorthandQueryRun($value, substr($key, 2)), $rule);
} else {
$result = $this->chequerOperator(substr($key, 1), $value, $rule);
}
} else { // look in the array/hashmap
$result = $this->querySubkey($value, $key, $rule, $this->deepArrays);
// for unknown keys check null value
if ($result === null) $result = $this->query(null, $rule);
}
if ($result === null) continue;
if ($matchAll && !$result) return false;
if (!$matchAll && $result) return true;
}
} catch (\Chequer\ParseBreakException $e) {
$result = $e->result;
}
return count($query) == 1 ? $result : $matchAll;
}
public function chequerOperator($operator, $value, $rule, $caller = null) {
if ($operator[0] === '$') $operator = substr($operator, 1);
if (isset($this->operators[$operator])) {
if (is_string($this->operators[$operator])) {
$operator = $this->operators[$operator];
} else {
return call_user_func($this->operators[$operator], $value, $rule);
}
}
// if it's not aliased or user-defined, we try to ask the value itself
if ($value instanceof \Chequer\Chequerable && $caller === null) {
return $value->chequerOperator($operator, $value, $rule, $this);
}
return call_user_func(array($this, 'operator_' . $operator), $value, $rule);
}
/** Calls or returns a typecast object */
public function chequerTypecast($typecast, $callArgs = array(), $caller = null) {
if (array_key_exists($typecast, $this->typecasts)) {
$typecastObj = $this->typecasts[$typecast];
if (count($callArgs) == 0 && ($typecastObj instanceof Closure) == false) {
return $typecastObj;
} elseif (!is_scalar($typecastObj) && is_callable($typecastObj)) {
return call_user_func_array($typecastObj, $callArgs);
} else {
throw new \Chequer\ParseException("Typecast '$typecast' cannot be called!");
}
}
// if it's not user-defined, we try to ask the value itself
if ($callArgs && $callArgs[0] instanceof \Chequer\Chequerable && $caller === null) {
return $callArgs[0]->chequerTypecast($typecast, $callArgs, $this);
}
return call_user_func(array($this, 'typecast_' . $typecast), $callArgs);
}
protected function getSubkeyValue( $value, $key, $deepArrays = 0, $findMethod = false ) {
if (!is_array($value) && !is_object($value)) {
if ($this->strictMode)
throw new \Chequer\ParseException("Array or object required for key matching on $key.");
else
return null;
}
if (is_array($value) || $value instanceof ArrayAccess) {
if (isset($value[$key])) return $value[$key];
}
if (is_object($value)) {
if ($findMethod && method_exists($value, $key)) {
return array($value, $key);
}
if (isset($value->$key)) return $value->$key;
}
if ($deepArrays > 0 && is_array($value) && isset($value[0])) {
--$deepArrays;
for ($i = 0, $length = count($value); $i < $length, isset($value[$i]); ++$i) {
$subvalue = $value[$i];
if (is_array($subvalue) || is_object($subvalue)) {
$subresult = $this->getSubkeyValue($subvalue, $key, $deepArrays, $findMethod);
if ($subresult !== null) return $subresult;
}
}
}
if ($this->strictMode)
throw new \Chequer\ParseException("Subkey $key not found.");
return null;
}
protected function querySubkey( $value, $key, $rule, $deepArrays = 0 ) {
if ($key[0] === '.' || $key[0] === '@') {
// handle complex subkeys
$value = $this->shorthandQueryRun($value, $key);
} else {
// handle simple ones
$value = $this->getSubkeyValue($value, $key, $deepArrays);
}
return $this->query($value, $rule);
}
protected function shorthandQueryRun($value, $query) {
// split query into tokens
$tokens = new \Chequer\Tokenizer($query, '/\$[a-z!~&^*\-+=\/|%<>]+|(?<![.@\d])-?(?:\d+\.)?\d+|[!~&\^*\-+=\/|%<>:]{1,3}|\d+|[a-z]+|\s+|./i');
$result = $this->shorthandParse($tokens, $value);
if ($tokens->current !== null) throw new \Chequer\ParseException("Query finished prematurely!");
return $result;
}
protected static $shcOperator = array(
'$' => 1, '!' => 1, '~' => 1, '&' => 1, '^' => 1, '*' => 1, '-' => 1, '+' => 1,
'=' => 1, '/' => 1, '|' => 1, '%' => 1, '<' => 1, '>' => 1, ';' => 1,
'?' => 1
);
protected static $shcWhitespace = array(
' ' => 1, "\t" => 1, "\r" => 1, "\n" => 1
);
protected static $shcStopchar = array(
'$' => 1, '!' => 1, '~' => 1, '&' => 1, '^' => 1, '*' => 1, '-' => 1, '+' => 1,
'=' => 1, '/' => 1, '|' => 1, '%' => 1, '<' => 1, '>' => 1, ';' => 1,
'?' => 1,
'.' => 1, '@' => 1, ',' => 1, ':' => 1,
'(' => 1, ')' => 1,
'\'' => 1, '"' => 1,
' ' => 1, "\t" => 1, "\r" => 1, "\n" => 1
);
/** Collects the value from tokens. Stops only on operators or EOT. */
protected function shorthandCollectValues(\Chequer\Tokenizer $tokens, $contextValue, &$value) {
// was anything collected?
$collected = false;
$whitespace = '';
while ($tokens->current !== null && $tokens->current !== ')') {
$char = $tokens->current[0];
$valueItem = null;
if ($char === '(') {
// parenthesis! read it...
$tokens->getToken();
// evaluate
$valueItem = $this->shorthandParse($tokens, $contextValue);
if ($tokens->current === '.') {
$subkeyValue = $valueItem;
goto extractSubkey;
}
} elseif ((isset(self::$shcOperator[$char]) && ($char !== '-' || !is_numeric($tokens->current)))
|| $char === ',' || $char === ':') {
// an operator, array or hashmap
return $collected;
} elseif (isset(self::$shcWhitespace[$char])) {
// a whitespace
$whitespace .= $tokens->getToken();
continue;
} elseif ($char === '"' || $char === '\'') {
// quoted string
$whitespace = '';
$valueItem = substr($tokens->getToken(array($char => true)), 1);
// read outstanding quote
$tokens->getToken();
} elseif ($char === '.' || $char === '@') {
// subkeys!
$subkeyValue = $contextValue;
extractSubkey:
do {
$subkey = $tokens->getToken(self::$shcStopchar);
if ($subkey === '.') {
// do nothing, use current subkeyValue
} elseif ($subkey === '@') {
throw new \Chequer\ParseException("Empty @ operator!");
} elseif ($subkey[0] === '@') {
// object typecasting
$typecast = substr($subkey, 1);
if ($tokens->current === '(') {
// method call
$tokens->getToken();
$arguments = $this->shorthandParse($tokens, $contextValue, true, 0);
if (!$arguments) $arguments = array($subkeyValue);
$subkeyValue = $this->chequerTypecast( $typecast, $arguments );
} else {
// just return the typecast's object
$subkeyValue = $this->chequerTypecast( $typecast );
}
} else {
// standard subkey
$subkey = substr($subkey, 1);
if ($tokens->current === '(') {
// method call
$tokens->getToken();
$arguments = $this->shorthandParse($tokens, $contextValue, true, 0);
$method = $this->getSubkeyValue($subkeyValue, $subkey, $this->deepArrays, true);
if (!is_callable($method)) {
if ($this->strictMode) {
throw new \Chequer\ParseException("Subkey '$subkey' is not callable!");
} else $subkeyValue = null;
}
if (!$arguments) $arguments = array();
$subkeyValue = call_user_func_array($method, $arguments);
} else {
$subkeyValue = $this->getSubkeyValue($subkeyValue, $subkey, $this->deepArrays);
}
}
} while ($subkeyValue !== null && $tokens->current === '.' || $tokens->current === '@');
$valueItem = $subkeyValue;
} else {
// the rest is a string/number/bool/null
$valueItem = $tokens->getToken();
if (is_numeric($valueItem)) {
$valueItem = $valueItem + 0;
} elseif ($valueItem === 'TRUE') {
$valueItem = true;
} elseif ($valueItem === 'FALSE') {
$valueItem = false;
} elseif ($valueItem === 'NULL') {
$valueItem = null;
}
}
// collect the value
if ($collected) {
// if already collected anything, we are concatenating... everything has to be a string...
if (!is_scalar($value)) $value = is_array($value) ? '(Array)' : (string)$value;
if (!is_scalar($valueItem)) $valueItem = is_array($valueItem) ? '(Array)' : (string)$valueItem;
}
$value = $collected ? $value . $whitespace . $valueItem : $valueItem;
$collected = true;
$whitespace = '';
};
return $collected;
}
protected function shorthandParse(\Chequer\Tokenizer $tokens, $contextValue
, $allowKeys = true, $arrayKey = null, $value = null, $hasValue = false
) {
$arrayValue = null;
$conditionalFF = 0;
while ($tokens->current !== null && $tokens->current !== ')') {
try {
$operator = null;
$parameter = null;
// collect the values
if (!$hasValue) {
$value = null;
if (!($hasValue = $this->shorthandCollectValues($tokens, $contextValue, $value))) {
$value = $contextValue;
}
}
// return on EOT or parenthesis close...
if ($tokens->current === null || $tokens->current === ')') {
// ')' will be read after loop
break;
} elseif ($tokens->current === ',') {
// array
if (!$allowKeys) return $value;
$tokens->getToken();
if ($arrayKey === null) {
$arrayValue = $hasValue ? array($value) : array();
} else {
// store value on previous key
$arrayValue[$arrayKey] = $value;
}
$arrayKey = count($arrayValue);
$hasValue = false;
} elseif ($tokens->current === ':') {
if ($conditionalFF) {
// ternary FALSE
$conditionalFF = false;
$tokens->getToken();
$this->shorthandFastforward($tokens, array(':' => true, ',' => true, ')' => true));
continue;
} else {
// hashmap key
if (!$allowKeys) return $value;
$tokens->getToken();
$arrayKey = is_scalar($value) ? $value : (string)$value;
$hasValue = false;
}
} elseif ($tokens->current === '?') {
// ternary TRUE
$hasValue = false;
$tokens->getToken();
if ($value) {
// skip part after ':'
$conditionalFF = true;
continue;
} else {
// skip until ':'
$this->shorthandFastforward($tokens, array(',' => true, ')' => true, ':' => true));
if ($tokens->current === ':') $tokens->getToken();
continue;
}
} else {
// we have an operator for sure.
if ($tokens->current[0] !== '$') {
// shorthand syntax, read as is
$operator = $tokens->getToken();
} else {
// full syntax, Read until whitespace
$operator = $tokens->getToken(self::$shcStopchar);
}
// collect the parameters
if (!$this->shorthandCollectValues($tokens, $operator === '=>' ? $value : $contextValue, $parameter)) {
// another operator?
if ($tokens->current !== null && $tokens->current !== ')'
&& $tokens->current !== ',' && $tokens->current !== ':'
&& $tokens->current !== '?'
) {
$parameter = $this->shorthandParse($tokens, $operator === '=>' ? $value : $contextValue, false, null, $value, $hasValue);
}
}
$value = $operator === '=>' ? $parameter : $this->chequerOperator($operator, $value, $parameter);
$hasValue = true;
}
} catch (\Chequer\ParseBreakException $e) {
// fast forward to the end
$this->shorthandFastforward($tokens, array(',' => true, ')' => true));
//$tokens->getToken(); // read it
$value = $e->result;
$hasValue = true;
}
}; // while tokens last
// read ')'
$tokens->getToken();
if ($arrayKey !== null && $hasValue) {
$arrayValue[$arrayKey] = $value;
}
return $arrayValue === null ? $value : $arrayValue;
}
protected function shorthandFastforward(Chequer\Tokenizer $tokens, $until) {
$nesting = 0;
while(($token = $tokens->current) !== null) {
$char = $token[0];
if ($char === '"' || $char === '\'') {
$tokens->getToken(array($char => true));
} elseif ($char === '(') {
++$nesting;
} elseif ($nesting && $char === ')') {
--$nesting;
} elseif (!$nesting && isset($until[$char])) {
// got it!
return;
}
$tokens->getToken();
}
}
/* ---------- operators ------------------------------------------------- */
protected static function toString($a, $serialize = true) {
if (is_object($a) && method_exists($a, '__toString')) {
return (string)$a;
} elseif ($serialize && (is_object($a) || is_array($a))) {
return serialize($a);
}
return (string)$a;
}
protected static function unifyTypes(&$a, &$b) {
if (is_scalar($a) && !is_scalar($b)) {
$b = self::toString($b);
} elseif (!is_scalar($a) && is_scalar($b)) {
$a = self::toString($a);
} elseif (!is_scalar($a) && !is_scalar($b) && gettype($a) != gettype($b)) {
$a = self::toString($a);
$b = self::toString($b);
}
}
protected function operator_not( $value, $rule ) {
return !$this->query($value, $rule);
}
protected function operator_eq( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value == $rule;
}
protected function operator_ne( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value != $rule;
}
protected function operator_same( $value, $rule ) {
return $value === $rule;
}
protected function operator_nc( $value, $rule ) {
$value = self::toString($value);
$rule = self::toString($rule);
return mb_strtolower($value) === mb_strtolower($rule);
}
protected function operator_gt( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value > $rule;
}
protected function operator_gte( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value >= $rule;
}
protected function operator_lt( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value < $rule;
}
protected function operator_lte( $value, $rule ) {
self::unifyTypes($value, $rule);
return $value <= $rule;
}
protected function operator_between( $value, $rule ) {
if (count($rule) != 2)
throw new Chequer\ParseException('Two element array required for $between!');
self::unifyTypes($value, $rule[0]);
self::unifyTypes($value, $rule[1]);
return $value >= $rule[0] && $value <= $rule[1];
}
protected function operator_in( $value, $rule ) {
if (is_scalar($rule)) return $value == $rule;
return in_array($value, $rule);
}
protected function operator_or( $value, $rule ) {
if (is_scalar($rule)) {
if ($value || $rule) {
throw new Chequer\ParseBreakException(true);
} else {
return false;
}
} else {
return $this->query($value, $rule, false);
}
}
protected function operator_orvalue( $value, $rule ) {
if ($value) {
throw new Chequer\ParseBreakException($value);
} elseif ($rule) {
throw new Chequer\ParseBreakException($rule);
} else {
return $rule;
}
}
protected function operator_and( $value, $rule ) {
if (is_scalar($rule)) {
if ($value && $rule) {
return true;
} else {
throw new Chequer\ParseBreakException(false);
}
} else {
return $this->query($value, $rule, true);
}
}
protected function operator_regex( $value, $rule ) {
$value = self::toString($value);
if ($rule[0] !== '/' && $rule[0] !== '#' && $rule[0] !== '~') {
$rule = "~{$rule}~";
}
return preg_match($rule, $value) == true;
}
protected function operator_check( $value, $rule ) {
return call_user_func($rule, $value);
}
protected function operator_size( $value, $rule ) {
$length = is_string($value) ? mb_strlen($value) : count($value);
return $this->query($length, $rule);
}
protected function operator_eval( $value, $rule ) {
if (!is_array($rule)) throw new \Chequer\ParseException('$eval rule should be an array!');
foreach($rule as $query) {
$value = $this->query($value, $query);
}
return $value;
}
protected function operator_rule( $value, $rules ) {
if (!is_array($rules)) $rules = preg_split('/\s*,?\s+/', trim($rules));
if (count($rules) > 1) {
$query = array('$' => 'AND');
foreach($rules as $rule) {
if ($rule === 'AND') {
$query['$'] = 'AND';
} elseif ($rule === 'OR') {
$query['$'] = 'OR';
} else {
if (($not = ($rule{0} === '!'))) {
$rule = substr($rule, 1);
}
if (!isset($this->rules[$rule])) throw new \Chequer\ParseException("Rule '$rule' is undefined!");
$query[] = $not ? array('$not' => $this->rules[$rule]) : $this->rules[$rule];
}
}
return $this->query($value, $query);
} else {
if (!isset($this->rules[$rules[0]])) throw new \Chequer\ParseException("Rule '{$rules[0]}' is undefined!");
return $this->query($value, $this->rules[$rules[0]]);
}
}
protected function operator_add( $value, $operand ) {
if ($value === null && $operand === null) return null;
if (is_numeric($value) && is_numeric($operand)) {
return $value + $operand;
}
if (is_array($operand)) {
return array_merge((array)$value, $operand);
}
if (is_array($value)) {
$value[] = $operand;
return $value;
}
return $value . $operand;
}
protected function operator_sub( $value, $operand ) {
if ($value === null && $operand === null) return null;
if (is_numeric($value) && is_numeric($operand)) {
return $value - $operand;
}
if (is_array($operand)) {
return array_diff((array)$value, $operand);
}
if (is_array($value)) {
return array_filter($value, function($a) use ($operand) {return $a !== $operand;});
}
return str_replace($operand, '', $value);
}
protected function operator_mult( $value, $operand ) {
if ($value === null && $operand === null) return null;
if (is_numeric($value) && is_numeric($operand)) {
return $value * $operand;
}
if ($this->strictMode)
throw new \Chequer\ParseException("Bad operand types for *");
else
return null;
}
protected function operator_div( $value, $operand ) {
if (is_numeric($value) && is_numeric($operand)) {
return $value / $operand;
}
if ($this->strictMode)
throw new \Chequer\ParseException("Bad operand types for /");
else
return null;
}
protected function operator_abs( $value, $operand ) {
return abs($operand);
}
protected function operator_set( $value, $operand ) {
$parts = explode('.', $value);
if (!$parts) throw new \Chequer\ParseException("No typecast name given!");
// check if this is a global or built-in typecast
if (isset(self::$globalTypecasts[$parts[0]])) throw new \Chequer\ParseException("Typecast '$value' is global and cannot be changed!");
if (method_exists($this, 'typecast_' . $parts[0])) throw new \Chequer\ParseException("Typecast '$value' is built-in and cannot be changed!");
$current =& $this->typecasts;
foreach($parts as $part) {
if (!isset($current[$part])) $current[$part] = array();
$current =& $current[$part];
}
$current = $operand;
return $operand;
}
protected function operator_noop( $value, $operand ) {
return $operand;
}
protected function operator_max( $value, $operand ) {
if (is_array($operand)) {
return max($operand);
} else return max($value, $operand);
}
protected function operator_min( $value, $operand ) {
if (is_array($operand)) {
return min($operand);
} else return min($value, $operand);