-
Notifications
You must be signed in to change notification settings - Fork 31
/
file.php
1258 lines (1187 loc) · 48.3 KB
/
file.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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* File handling in moodlecheck
*
* @package local_moodlecheck
* @copyright 2012 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// phpcs:disable moodle.Commenting.VariableComment.Missing
// phpcs:disable moodle.Commenting.MissingDocblock.Missing
// phpcs:disable moodle.Commenting.VariableComment.TagNotAllowed
defined('MOODLE_INTERNAL') || die;
/**
* Handles one file being validated
*
* @package local_moodlecheck
* @copyright 2012 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class local_moodlecheck_file {
private const MODIFIERS = [T_ABSTRACT, T_PRIVATE, T_PUBLIC, T_PROTECTED, T_STATIC, T_VAR, T_FINAL, T_CONST];
protected $filepath = null;
protected $needsvalidation = null;
protected $errors = null;
protected $tokens = null;
protected $tokenscount = 0;
protected $classes = null;
protected $interfaces = null;
protected $traits = null;
protected $functions = null;
protected $filephpdocs = null;
protected $allphpdocs = null;
/**
* Creates an object from path to the file
*
* @param string $filepath
*/
public function __construct($filepath) {
$this->filepath = str_replace(DIRECTORY_SEPARATOR, "/", $filepath);
}
/**
* Cleares all cached stuff to free memory
*/
protected function clear_memory() {
$this->tokens = null;
$this->tokenscount = 0;
$this->classes = null;
$this->interfaces = null;
$this->traits = null;
$this->functions = null;
$this->filephpdocs = null;
$this->allphpdocs = null;
}
/**
* Returns true if this file is inside specified directory
*
* @param string $dirpath
* @return bool
*/
public function is_in_dir($dirpath) {
// Normalize dir path to also work with Windows style directory separators...
$dirpath = str_replace(DIRECTORY_SEPARATOR, "/", $dirpath);
if (substr($dirpath, -1) != '/') {
$dirpath .= '/';
}
return substr($this->filepath, 0, strlen($dirpath)) == $dirpath;
}
/**
* Retuns true if the file needs validation (is PHP file)
*
* @return bool
*/
public function needs_validation() {
if ($this->needsvalidation === null) {
$this->needsvalidation = true;
$pathinfo = pathinfo($this->filepath);
if (empty($pathinfo['extension']) || ($pathinfo['extension'] != 'php' && $pathinfo['extension'] != 'inc')) {
$this->needsvalidation = false;
}
}
return $this->needsvalidation;
}
/**
* Validates a file over registered rules and returns an array of errors
*
* @return array
*/
public function validate() {
if ($this->errors !== null) {
return $this->errors;
}
$this->errors = [];
if (!$this->needs_validation()) {
return $this->errors;
}
// If the file doesn't have tokens, has one or misses open tag, report it as one more error and stop processing.
if (!$this->get_tokens() ||
count($this->get_tokens()) === 1 ||
(isset($this->get_tokens()[0][0]) && $this->get_tokens()[0][0] !== T_OPEN_TAG)) {
$this->errors[] = [
'line' => 1,
'severity' => 'error',
'message' => get_string('error_emptynophpfile', 'local_moodlecheck'),
'source' => 'Ø',
];
return $this->errors;
}
foreach (local_moodlecheck_registry::get_enabled_rules() as $code => $rule) {
$ruleerrors = $rule->validatefile($this);
if (count($ruleerrors)) {
$this->errors = array_merge($this->errors, $ruleerrors);
}
}
$this->clear_memory();
return $this->errors;
}
/**
* Return the filepath of the file.
*
* @return string
*/
public function get_filepath() {
return $this->filepath;
}
/**
* Returns a file contents converted to array of tokens.
*
* Each token is an array with two elements: code of token and text
* For simple 1-character tokens the code is -1
*
* @return array
*/
public function &get_tokens() {
if ($this->tokens === null) {
$source = file_get_contents($this->filepath);
$this->tokens = @token_get_all($source);
$this->tokenscount = count($this->tokens);
$inquotes = -1;
for ($tid = 0; $tid < $this->tokenscount; $tid++) {
if (is_string($this->tokens[$tid])) {
// Simple 1-character token.
$this->tokens[$tid] = [-1, $this->tokens[$tid]];
}
// And now, for the purpose of this project we don't need strings with variables inside to be parsed
// so when we find string in double quotes that is split into several tokens and combine all content in one token.
if ($this->tokens[$tid][0] == -1 && $this->tokens[$tid][1] == '"') {
if ($inquotes == -1) {
$inquotes = $tid;
$this->tokens[$tid][0] = T_STRING;
} else {
$this->tokens[$inquotes][1] .= $this->tokens[$tid][1];
$this->tokens[$tid] = [T_WHITESPACE, ''];
$inquotes = -1;
}
} else if ($inquotes > -1) {
$this->tokens[$inquotes][1] .= $this->tokens[$tid][1];
$this->tokens[$tid] = [T_WHITESPACE, ''];
}
}
}
return $this->tokens;
}
/**
* Returns all artifacts (classes, interfaces, traits) found in file
*
* Returns 3 arrays (classes, interfaces and traits) of objects where each element represents an artifact:
* ->type : token type of the artifact (T_CLASS, T_INTERFACE, T_TRAIT)
* ->typestring : type of the artifact as a string ('class', 'interface', 'trait')
* ->name : name of the artifact
* ->tagpair : array of two elements: id of token { for the class and id of token } (false if not found)
* ->phpdocs : phpdocs for this artifact (instance of local_moodlecheck_phpdocs or false if not found)
* ->boundaries : array with ids of first and last token for this artifact.
* ->hasextends : boolean indicating whether this artifact has an `extends` clause
* ->hasimplements : boolean indicating whether this artifact has an `implements` clause
*
* @return array with 3 elements (classes, interfaces & traits), each being an array.
*/
public function get_artifacts() {
$types = [T_CLASS, T_INTERFACE, T_TRAIT]; // We are interested on these.
$artifacts = array_combine($types, $types);
if ($this->classes === null) {
$this->classes = [];
$this->interfaces = [];
$this->traits = [];
$tokens = &$this->get_tokens();
for ($tid = 0; $tid < $this->tokenscount; $tid++) {
if (isset($artifacts[$this->tokens[$tid][0]])) {
if ($this->previous_nonspace_token($tid) === "::") {
// Skip use of the ::class special constant.
continue;
}
if ($this->previous_nonspace_token($tid) == 'new') {
// This looks to be an anonymous class.
$tpid = $tid; // Let's keep the original $tid and use own for anonymous searches.
if ($this->next_nonspace_token($tpid) == '(') {
// It may be an anonymous class with parameters, let's skip them
// by advancing till we find the corresponding bracket closing token.
$level = 0; // To control potential nesting of brackets within the params.
while ($tpid = $this->next_nonspace_token($tpid, true)) {
if ($this->tokens[$tpid][1] == '(') {
$level++;
}
if ($this->tokens[$tpid][1] == ')') {
$level--;
// We are back to level 0, we are done (have walked over all params).
if ($level === 0) {
$tpid = $tpid;
break;
}
}
}
}
if ($this->next_nonspace_token($tpid) == '{') {
// An anonymous class in the format `new class {`.
continue;
}
if ($this->next_nonspace_token($tpid) == 'extends') {
// An anonymous class in the format `new class extends otherclasses {`.
continue;
}
if ($this->next_nonspace_token($tpid) == 'implements') {
// An anonymous class in the format `new class implements someinterface {`.
continue;
}
}
$artifact = new stdClass();
$artifact->type = $artifacts[$this->tokens[$tid][0]];
$artifact->typestring = $this->tokens[$tid][1];
$artifact->tid = $tid;
$artifact->name = $this->next_nonspace_token($tid);
$artifact->phpdocs = $this->find_preceeding_phpdoc($tid);
$artifact->tagpair = $this->find_tag_pair($tid, '{', '}');
$artifact->hasextends = false;
$artifact->hasimplements = false;
if ($artifact->tagpair) {
// Iterate over the remaining tokens in the class definition (until opening {).
foreach (array_slice($this->tokens, $tid, $artifact->tagpair[0] - $tid) as $token) {
if ($token[0] == T_EXTENDS) {
$artifact->hasextends = true;
}
if ($token[0] == T_IMPLEMENTS) {
$artifact->hasimplements = true;
}
}
}
$artifact->boundaries = $this->find_object_boundaries($artifact);
switch ($artifact->type) {
case T_CLASS:
$this->classes[] = $artifact;
break;
case T_INTERFACE:
$this->interfaces[] = $artifact;
break;
case T_TRAIT:
$this->traits[] = $artifact;
break;
}
}
}
}
return [T_CLASS => $this->classes, T_INTERFACE => $this->interfaces, T_TRAIT => $this->traits];
}
/**
* Like {@see get_artifacts()}, but returns classes, interfaces and traits in a single flat array.
*
* @return stdClass[]
* @see get_artifacts()
*/
public function get_artifacts_flat(): array {
$artifacts = $this->get_artifacts();
return array_merge($artifacts[T_CLASS], $artifacts[T_INTERFACE], $artifacts[T_TRAIT]);
}
/**
* Returns all classes found in file
*
* Returns array of objects where each element represents a class:
* $class->name : name of the class
* $class->tagpair : array of two elements: id of token { for the class and id of token } (false if not found)
* $class->phpdocs : phpdocs for this class (instance of local_moodlecheck_phpdocs or false if not found)
* $class->boundaries : array with ids of first and last token for this class
*/
public function &get_classes() {
return $this->get_artifacts()[T_CLASS];
}
/**
* Returns all functions (including class methods) found in file
*
* Returns array of objects where each element represents a function:
* $function->tid : token id of the token 'function'
* $function->name : name of the function
* $function->phpdocs : phpdocs for this function (instance of local_moodlecheck_phpdocs or false if not found)
* TODO: Delete this because it's not used anymore (2023). See #97
* $function->class : containing class object (false if this is not a class method)
* $function->owner : containing artifact object (class, interface, trait, or false if this is not a method)
* $function->fullname : name of the function with class name (if applicable)
* $function->accessmodifiers : tokens like static, public, protected, abstract, etc.
* $function->tagpair : array of two elements: id of token { for the function and id of token } (false if not found)
* $function->argumentstoken : array of tokens found inside function arguments
* $function->arguments : array of function arguments where each element is [typename, variablename]
* $function->boundaries : array with ids of first and last token for this function
*
* @return array
*/
public function &get_functions() {
if ($this->functions === null) {
$this->functions = [];
$tokens = &$this->get_tokens();
for ($tid = 0; $tid < $this->tokenscount; $tid++) {
if ($this->tokens[$tid][0] == T_USE) {
// Skip the entire use statement, to avoid interpreting "use function" as a function.
$tid = $this->end_of_statement($tid);
continue;
}
if ($this->tokens[$tid][0] == T_FUNCTION) {
$function = new stdClass();
$function->tid = $tid;
$function->fullname = $function->name = $this->next_nonspace_token($tid, false, ['&']);
// Skip anonymous functions.
if ($function->name == '(') {
continue;
}
$function->phpdocs = $this->find_preceeding_phpdoc($tid);
$function->class = $this->is_inside_class($tid);
$function->owner = $this->is_inside_artifact($tid);
if ($function->owner !== false) {
$function->fullname = $function->owner->name . '::' . $function->name;
}
$function->accessmodifiers = $this->find_access_modifiers($tid);
if (!in_array(T_ABSTRACT, $function->accessmodifiers)) {
$function->tagpair = $this->find_tag_pair($tid, '{', '}');
} else {
$function->tagpair = false;
}
$argumentspair = $this->find_tag_pair($tid, '(', ')', ['{', ';']);
if ($argumentspair !== false && $argumentspair[1] - $argumentspair[0] > 1) {
$function->argumentstokens = $this->break_tokens_by(
array_slice($tokens, $argumentspair[0] + 1, $argumentspair[1] - $argumentspair[0] - 1) );
} else {
$function->argumentstokens = [];
}
$function->arguments = [];
foreach ($function->argumentstokens as $argtokens) {
// If the token is completely empty then it's not an argument. This happens, for example, with
// trailing commas in parameters, allowed since PHP 8.0 and break_tokens_by() returns it that way.
if (empty($argtokens)) {
continue;
}
$possibletypes = [];
$variable = null;
$splat = false;
if (PHP_VERSION_ID < 80000) {
$maxindex = array_key_last($argtokens);
// In PHP 7.4 and earlier, the namespace was parsed separately, for example:
// \core\course would be come '\', 'core', '\', 'course'.
// From PHP 8.0 this becomes '\core\course'.
// To address this we modify the tokens to match the PHP 8.0 format.
// This is a bit of a hack, but it works.
// Note: argtokens contains arrays of [token index, string content, line number].
for ($j = 0; $j < $maxindex; $j++) {
if ($argtokens[$j][0] === T_NS_SEPARATOR || $argtokens[$j][0] === T_STRING) {
$argtokens[$j][0] = T_STRING;
$initialtoken = $j;
for ($namespacesearch = $j + 1; $namespacesearch < $maxindex; $namespacesearch++) {
switch ($argtokens[$namespacesearch][0]) {
case T_STRING:
case T_NS_SEPARATOR:
break;
default:
break 2;
}
$argtokens[$initialtoken][1] .= $argtokens[$namespacesearch][1];
unset($argtokens[$namespacesearch]);
$j = $namespacesearch;
}
}
}
}
$argtokens = array_values($argtokens);
for ($j = 0; $j < count($argtokens); $j++) {
if (version_compare(PHP_VERSION, '8.1.0') >= 0) {
// T_READONLY introduced in PHP 8.1.
if ($argtokens[$j][0] === T_READONLY) {
continue;
}
}
switch ($argtokens[$j][0]) {
// Skip any whitespace, or argument visibility.
case T_COMMENT:
case T_DOC_COMMENT:
case T_WHITESPACE:
case T_PUBLIC:
case T_PROTECTED:
case T_PRIVATE:
continue 2;
case T_VARIABLE:
// The variale name, adding in the vardiadic if required.
$variable = ($splat) ? '...' . $argtokens[$j][1] : $argtokens[$j][1];
continue 2;
case T_ELLIPSIS:
// For example ...$example
// Variadic function.
$splat = true;
continue 2;
}
switch ($argtokens[$j][1]) {
case '|':
// Union types.
case '&':
// Return by reference.
continue 2;
case '?':
// Nullable type.
$possibletypes[] = 'null';
continue 2;
case '=':
// Default value.
$j = count($argtokens);
continue 2;
}
$possibletypes[] = $argtokens[$j][1];
}
$type = implode('|', $possibletypes);
$function->arguments[] = [$type, $variable];
}
$function->boundaries = $this->find_object_boundaries($function);
$this->functions[] = $function;
}
}
}
return $this->functions;
}
/**
* Finds and returns object boundaries
*
* $obj is an object representing function, class or variable. This function
* returns token ids for the very first token applicable to this object
* to the very last
*
* @param stdClass $obj
* @return array
*/
public function find_object_boundaries($obj) {
$boundaries = [$obj->tid, $obj->tid];
$tokens = &$this->get_tokens();
if (!empty($obj->tagpair)) {
$boundaries[1] = $obj->tagpair[1];
} else {
// Find the next ; char.
for ($i = $boundaries[1]; $i < $this->tokenscount; $i++) {
if ($tokens[$i][1] == ';') {
$boundaries[1] = $i;
break;
}
}
}
if (isset($obj->phpdocs) && $obj->phpdocs instanceof local_moodlecheck_phpdocs) {
$boundaries[0] = $obj->phpdocs->get_original_token_id();
} else {
// Walk back until we meet one of the characters that means that we are outside of the object.
for ($i = $boundaries[0] - 1; $i >= 0; $i--) {
$token = $tokens[$i];
if (in_array($token[0], [T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_CLOSE_TAG])) {
break;
} else if (in_array($token[1], ['{', '}', '(', ';', ',', '['])) {
break;
}
}
// Walk forward to the next meaningful token skipping all spaces and comments.
for ($i = $i + 1; $i < $boundaries[0]; $i++) {
if (!in_array($tokens[$i][0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
break;
}
}
$boundaries[0] = $i;
}
return $boundaries;
}
/**
* Checks if the token with id $tid in inside some class
*
* @param int $tid
* @return stdClass|false containing class or false if this is not a member
*/
public function is_inside_class($tid) {
$classes = &$this->get_classes();
$classescnt = count($classes);
for ($clid = 0; $clid < $classescnt; $clid++) {
if ($classes[$clid]->boundaries[0] <= $tid && $classes[$clid]->boundaries[1] >= $tid) {
return $classes[$clid];
}
}
return false;
}
/**
* Checks if the token with id $tid in inside some artifact (class, interface, or trait).
*
* @param int $tid
* @return stdClass|false containing artifact or false if this is not a member
*/
public function is_inside_artifact(int $tid) {
$artifacts = $this->get_artifacts_flat();
foreach ($artifacts as $artifact) {
if ($artifact->boundaries[0] <= $tid && $artifact->boundaries[1] >= $tid) {
return $artifact;
}
}
return false;
}
/**
* Checks if the token with id $tid in inside some function or class method
*
* @param int $tid
* @return stdClass|false containing function or false if this is not inside a function
*/
public function is_inside_function($tid) {
$functions = &$this->get_functions();
$functionscnt = count($functions);
for ($fid = 0; $fid < $functionscnt; $fid++) {
if ($functions[$fid]->boundaries[0] <= $tid && $functions[$fid]->boundaries[1] >= $tid) {
return $functions[$fid];
}
}
return false;
}
/**
* Checks if token with id $tid is a whitespace
*
* @param int $tid
* @return boolean
*/
public function is_whitespace_token($tid) {
$this->get_tokens();
return (isset($this->tokens[$tid][0]) && $this->tokens[$tid][0] == T_WHITESPACE);
}
/**
* Returns how many line feeds are in this token
*
* @param int $tid
* @return int
*/
public function is_multiline_token($tid) {
$this->get_tokens();
return substr_count($this->tokens[$tid][1], "\n");
}
/**
* Returns the first token which is not whitespace following the token with id $tid
*
* Also returns false if no meaningful token found till the end of file
*
* @param int $tid
* @param bool $returnid
* @param array $alsoignore
* @return int|false
*/
public function next_nonspace_token($tid, $returnid = false, $alsoignore = []) {
$this->get_tokens();
for ($i = $tid + 1; $i < $this->tokenscount; $i++) {
if (!$this->is_whitespace_token($i) && !in_array($this->tokens[$i][1], $alsoignore)) {
if ($returnid) {
return $i;
} else {
return $this->tokens[$i][1];
}
}
}
return false;
}
/**
* Returns the first token which is not whitespace before the token with id $tid
*
* Also returns false if no meaningful token found till the beginning of file
*
* @param int $tid
* @param bool $returnid
* @param array $alsoignore
* @return int|false
*/
public function previous_nonspace_token($tid, $returnid = false, $alsoignore = []) {
$this->get_tokens();
for ($i = $tid - 1; $i > 0; $i--) {
if (!$this->is_whitespace_token($i) && !in_array($this->tokens[$i][1], $alsoignore)) {
if ($returnid) {
return $i;
} else {
return $this->tokens[$i][1];
}
}
}
return false;
}
/**
* Returns the next semicolon or close tag following $tid, or the last token of the file, whichever comes first.
*
* @param int $tid starting token
* @return int index of the next semicolon or close tag following $tid, or the last token of the file, whichever
* comes first
*/
public function end_of_statement($tid) {
for (; $tid < $this->tokenscount; $tid++) {
if ($this->tokens[$tid][1] == ";" || $this->tokens[$tid][0] == T_CLOSE_TAG) {
// Semicolons and close tags (?>) end statements.
return $tid;
}
}
// EOF also ends statements.
return $tid;
}
/**
* Returns all modifiers (private, public, static, ...) preceeding token with id $tid
*
* @param int $tid
* @return array
*/
public function find_access_modifiers($tid) {
$tokens = &$this->get_tokens();
$modifiers = [];
for ($i = $tid - 1; $i >= 0; $i--) {
if ($this->is_whitespace_token($i)) {
// Skip.
continue;
} else if (in_array($tokens[$i][0], self::MODIFIERS)) {
$modifiers[] = $tokens[$i][0];
} else {
break;
}
}
return $modifiers;
}
/**
* Finds phpdocs preceeding the token with id $tid
*
* skips words abstract, private, public, protected and non-multiline whitespaces
*
* @param int $tid
* @return local_moodlecheck_phpdocs|false
*/
public function find_preceeding_phpdoc($tid) {
$tokens = &$this->get_tokens();
$modifiers = $this->find_access_modifiers($tid);
for ($i = $tid - 1; $i >= 0; $i--) {
if ($this->is_whitespace_token($i)) {
if ($this->is_multiline_token($i) > 1) {
// More that one line feed means that no phpdocs for this element exists.
return false;
}
} else if ($tokens[$i][0] == T_DOC_COMMENT) {
return $this->get_phpdocs($i);
} else if (in_array($tokens[$i][0], $modifiers)) {
// Just skip.
continue;
} else if (in_array($tokens[$i][1], ['{', '}', ';'])) {
// This means that no phpdocs exists.
return false;
} else if ($tokens[$i][0] == T_COMMENT) {
// This probably needed to be doc_comment.
return false;
} else {
// No idea what it is!
// TODO: change to debugging
// echo "************ Unknown preceeding token id = {$tokens[$i][0]}, text = '{$tokens[$i][1]}' **************<br>".
return false;
}
}
return false;
}
/**
* Skips any tokens that _could be_ part of a type of a typed property definition.
*
* @param int $tid the token before which a type is expected
* @return int the token id (`< $tid`) directly before the first token of the type. If there is no type, this will
* be the token directly preceding `$tid`.
*/
private function skip_preceding_type(int $tid): int {
for ($i = $tid - 1; $i >= 0; $i--) {
if ($this->is_whitespace_token($i)) {
continue;
}
$token = $this->tokens[$i];
if (in_array($token[0], self::MODIFIERS)) {
// This looks like the last modifier. Return the token after it.
return $i + 1;
} else if (in_array($token[1], ['{', '}', ';'])) {
// We've gone past the beginning of the statement. This isn't possible in valid PHP, but still...
// Return the first token of the statement we were in.
return $i + 1;
}
// This is something else. Let's assume it to be part of the property's type and skip it.
}
// We've gone all the way to the start of the file, which shouldn't be possible in valid PHP.
return 0;
}
/**
* Finds the next pair of matching open and close symbols (usually some sort of brackets)
*
* @param int $startid id of token where we start looking from
* @param string $opensymbol opening symbol (, { or [
* @param string $closesymbol closing symbol ), } or ] respectively
* @param array $breakifmeet array of symbols that are not allowed not preceed the $opensymbol
* @return array|false array of ids of two corresponding tokens or false if not found
*/
public function find_tag_pair($startid, $opensymbol, $closesymbol, $breakifmeet = []) {
$openid = false;
$counter = 0;
// Also break if we find closesymbol before opensymbol.
$breakifmeet[] = $closesymbol;
for ($i = $startid; $i < $this->tokenscount; $i++) {
if ($openid === false && in_array($this->tokens[$i][1], $breakifmeet)) {
return false;
} else if ($openid !== false && $this->tokens[$i][1] == $closesymbol) {
$counter--;
if ($counter == 0) {
return [$openid, $i];
}
} else if ($this->tokens[$i][1] == $opensymbol) {
if ($openid === false) {
$openid = $i;
}
$counter++;
}
}
return false;
}
/**
* Finds the next pair of matching open and close symbols (usually some sort of brackets)
*
* @param array $tokens array of tokens to parse
* @param int $startid id of token where we start looking from
* @param string $opensymbol opening symbol (, { or [
* @param string $closesymbol closing symbol ), } or ] respectively
* @param array $breakifmeet array of symbols that are not allowed not preceed the $opensymbol
* @return array|false array of ids of two corresponding tokens or false if not found
*/
public function find_tag_pair_inlist(&$tokens, $startid, $opensymbol, $closesymbol, $breakifmeet = []) {
$openid = false;
$counter = 0;
// Also break if we find closesymbol before opensymbol.
$breakifmeet[] = $closesymbol;
$tokenscount = count($tokens);
for ($i = $startid; $i < $tokenscount; $i++) {
if ($openid === false && in_array($tokens[$i][1], $breakifmeet)) {
return false;
} else if ($openid !== false && $tokens[$i][1] == $closesymbol) {
$counter--;
if ($counter == 0) {
return [$openid, $i];
}
} else if ($tokens[$i][1] == $opensymbol) {
if ($openid === false) {
$openid = $i;
}
$counter++;
}
}
return false;
}
/**
* Locates the file-level phpdocs and returns it
*
* @return string|false either the contents of phpdocs or false if not found
*/
public function find_file_phpdocs() {
$tokens = &$this->get_tokens();
if ($this->filephpdocs === null) {
$found = false;
for ($tid = 0; $tid < $this->tokenscount; $tid++) {
if (in_array($tokens[$tid][0], [T_OPEN_TAG, T_WHITESPACE, T_COMMENT])) {
// All allowed before the file-level phpdocs.
$found = false;
} else if ($tokens[$tid][0] == T_DOC_COMMENT) {
$found = $tid;
break;
} else {
// Found something else.
break;
}
}
if ($found !== false) {
// Now let's check that this is not phpdocs to the next function or class or define.
$nexttokenid = $this->next_nonspace_token($tid, true);
if ($nexttokenid !== false) { // Still tokens to look.
$nexttoken = $this->tokens[$nexttokenid];
if ($this->is_whitespace_token($tid + 1) && $this->is_multiline_token($tid + 1) > 1) {
// At least one empty line follows, it's all right.
$found = $tid;
} else if (in_array($nexttoken[0],
[T_DOC_COMMENT, T_COMMENT, T_REQUIRE_ONCE, T_REQUIRE, T_IF, T_INCLUDE_ONCE, T_INCLUDE])) {
// Something non-documentable following, ok.
$found = $tid;
} else if ($nexttoken[0] == T_STRING && $nexttoken[1] == 'defined') {
// Something non-documentable following.
$found = $tid;
} else if (in_array($nexttoken[0], [T_CLASS, T_ABSTRACT, T_INTERFACE, T_FUNCTION])) {
// This is the doc comment to the following class/function.
$found = false;
}
// TODO: change to debugging.
// } else {
// echo "************ "
// echo "Unknown token following the first phpdocs in "
// echo "{$this->filepath}: id = {$nexttoken[0]}, text = '{$nexttoken[1]}'"
// echo " **************<br>"
// }.
}
}
$this->filephpdocs = $this->get_phpdocs($found);
}
return $this->filephpdocs;
}
/**
* Returns all parsed phpdocs block found in file
*
* @return array
*/
public function &get_all_phpdocs() {
if ($this->allphpdocs === null) {
$this->allphpdocs = [];
$this->get_tokens();
for ($id = 0; $id < $this->tokenscount; $id++) {
if (($this->tokens[$id][0] == T_DOC_COMMENT || $this->tokens[$id][0] === T_COMMENT)) {
$this->allphpdocs[$id] = new local_moodlecheck_phpdocs($this->tokens[$id], $id);
}
}
}
return $this->allphpdocs;
}
/**
* Returns one parsed phpdocs block found in file
*
* @param int $tid token id of phpdocs
* @return local_moodlecheck_phpdocs
*/
public function get_phpdocs($tid) {
if ($tid === false) {
return false;
}
$this->get_all_phpdocs();
if (isset($this->allphpdocs[$tid])) {
return $this->allphpdocs[$tid];
} else {
return false;
}
}
/**
* Given an array of tokens breaks them into chunks by $separator
*
* @param array $tokens
* @param string $separator one-character separator (usually comma)
* @return array of arrays of tokens
*/
public function break_tokens_by($tokens, $separator = ',') {
$rv = [];
if (!count($tokens)) {
return $rv;
}
$rv[] = [];
for ($i = 0; $i < count($tokens); $i++) {
if ($tokens[$i][1] == $separator) {
$rv[] = [];
} else {
$nextpair = false;
if ($tokens[$i][1] == '(') {
$nextpair = $this->find_tag_pair_inlist($tokens, $i, '(', ')');
} else if ($tokens[$i][1] == '[') {
$nextpair = $this->find_tag_pair_inlist($tokens, $i, '[', ']');
} else if ($tokens[$i][1] == '{') {
$nextpair = $this->find_tag_pair_inlist($tokens, $i, '{', '}');
}
if ($nextpair !== false) {
// Skip to the end of the tag pair.
for ($j = $i; $j <= $nextpair[1]; $j++) {
$rv[count($rv) - 1][] = $tokens[$j];
}
$i = $nextpair[1];
} else {
$rv[count($rv) - 1][] = $tokens[$i];
}
}
}
// Now trim whitespaces.
for ($i = 0; $i < count($rv); $i++) {
if (count($rv[$i]) && $rv[$i][0][0] == T_WHITESPACE) {
array_shift($rv[$i]);
}
if (count($rv[$i]) && $rv[$i][count($rv[$i]) - 1][0] == T_WHITESPACE) {
array_pop($rv[$i]);
}
}
return $rv;
}
/**
* Returns line number for the token with specified id
*
* @param int $tid id of the token
*/
public function get_line_number($tid) {
$tokens = &$this->get_tokens();
if (count($tokens[$tid]) > 2) {
return $tokens[$tid][2];
} else if ($tid == 0) {
return 1;
} else {
return $this->get_line_number($tid - 1) + count(preg_split('/\n/', $tokens[$tid - 1][1])) - 1;
}
}
}
/**
* Handles one phpdocs
*
* @package local_moodlecheck
* @copyright 2012 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class local_moodlecheck_phpdocs {
/** @var array static property storing the list of valid,
* well known, phpdocs tags, always accepted.
* @link http://manual.phpdoc.org/HTMLSmartyConverter/HandS/ */
public static $validtags = [
// Behat tags.
'Given',
'Then',
'When',
// PHPUnit tags.
'codeCoverageIgnore',
'codeCoverageIgnoreStart',
'codeCoverageIgnoreEnd',
'covers',
'coversDefaultClass',
'coversNothing',