-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path.coderabbit.yaml
More file actions
1627 lines (1430 loc) · 47.4 KB
/
.coderabbit.yaml
File metadata and controls
1627 lines (1430 loc) · 47.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
chat:
auto_reply: false
reviews:
review_status: true
auto_review:
enabled: true
base_branches:
- next
drafts: true
path_instructions:
- path: "**/*"
instructions: |
Apply the following Clean Code guidelines to all files, as summarized by [wojteklu's Clean Code gist](https://gist.githubusercontent.com/wojteklu/73c6914cc446146b8b533c0988cf8d29/raw/c7a44d774fc3b09a0d5f0f58888550ba0ac694b9/clean_code.md):
Code is clean if it can be understood easily – by everyone on the team. Clean code can be read and enhanced by a developer other than its original author. With understandability comes readability, changeability, extensibility and maintainability.
## General rules
1. Follow standard conventions.
2. Keep it simple stupid. Simpler is always better. Reduce complexity as much as possible.
3. Boy scout rule. Leave the campground cleaner than you found it.
4. Always find root cause. Always look for the root cause of a problem.
## Design rules
1. Keep configurable data at high levels.
2. Prefer polymorphism to if/else or switch/case.
3. Separate multi-threading code.
4. Prevent over-configurability.
5. Use dependency injection.
6. Follow Law of Demeter. A class should know only its direct dependencies.
## Understandability tips
1. Be consistent. If you do something a certain way, do all similar things in the same way.
2. Use explanatory variables.
3. Encapsulate boundary conditions. Boundary conditions are hard to keep track of. Put the processing for them in one place.
4. Prefer dedicated value objects to primitive type.
5. Avoid logical dependency. Don't write methods which works correctly depending on something else in the same class.
6. Avoid negative conditionals.
## Names rules
1. Choose descriptive and unambiguous names.
2. Make meaningful distinction.
3. Use pronounceable names.
4. Use searchable names.
5. Replace magic numbers with named constants.
6. Avoid encodings. Don't append prefixes or type information.
## Functions rules
1. Small.
2. Do one thing.
3. Use descriptive names.
4. Prefer fewer arguments.
5. Have no side effects.
6. Don't use flag arguments. Split method into several independent methods that can be called from the client without the flag.
## Comments rules
1. Always try to explain yourself in code.
2. Don't be redundant.
3. Don't add obvious noise.
4. Don't use closing brace comments.
5. Don't comment out code. Just remove.
6. Use as explanation of intent.
7. Use as clarification of code.
8. Use as warning of consequences.
## Source code structure
1. Separate concepts vertically.
2. Related code should appear vertically dense.
3. Declare variables close to their usage.
4. Dependent functions should be close.
5. Similar functions should be close.
6. Place functions in the downward direction.
7. Keep lines short.
8. Don't use horizontal alignment.
9. Use white space to associate related things and disassociate weakly related.
10. Don't break indentation.
## Objects and data structures
1. Hide internal structure.
2. Prefer data structures.
3. Avoid hybrids structures (half object and half data).
4. Should be small.
5. Do one thing.
6. Small number of instance variables.
7. Base class should know nothing about their derivatives.
8. Better to have many functions than to pass some code into a function to select a behavior.
9. Prefer non-static methods to static methods.
## Tests
1. One assert per test.
2. Readable.
3. Fast.
4. Independent.
5. Repeatable.
## Code smells
1. Rigidity. The software is difficult to change. A small change causes a cascade of subsequent changes.
2. Fragility. The software breaks in many places due to a single change.
3. Immobility. You cannot reuse parts of the code in other projects because of involved risks and high effort.
4. Needless Complexity.
5. Needless Repetition.
6. Opacity. The code is hard to understand.
- path: "**/*.php"
instructions: |
Flag any usage of error_log() as it should be replaced with proper Monolog logging mechanisms provided by [zmsslim](https://github.com/it-at-m/eappointment/blob/b52b5d59c5013615d7fbfeaf595f3fdc047017d1/zmsslim/src/Slim/Bootstrap.php#L76) which should be setup in the App/Application of each module:
1. For error handling: Use the proper Monolog logging framework with error levels
2. For application info logs: Use the proper Monolog logging framework with info levels
3. For debugging: Use a dedicated debug logger or remove debug statements
4. For CLI output: Use a CLI output handler or symfony/console
5. The application [log levels](https://github.com/it-at-m/eappointment/blob/b52b5d59c5013615d7fbfeaf595f3fdc047017d1/zmsslim/src/Slim/Bootstrap.php#L60) are as follows DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, and EMERGENCY
Example replacement:
```php
// Instead of:
error_log("Import failed - " . $e->getMessage());
// Use:
$log->error("Import failed", ['error' => $e->getMessage()]);
```
Flag specific logging violations:
1. error_log(), var_dump(), print_r(), die(), exit() usage (except proper error logging in catch blocks)
2. Any debug output that should use proper Monolog logging
3. Debug constants like DEBUG = true
4. Debug logging that should be removed in production
5. Commented debug code that should be cleaned up
Example replacements:
```php
// Instead of:
error_log("Error occurred");
var_dump($data);
die('debug point');
// Use:
$log->error("Error occurred", ['context' => 'processing']);
$log->debug('Data dump', ['data' => $data]);
// Remove die() statements entirely
```
Exception handling should use proper logging:
```php
// Instead of:
try {
$result = $this->process();
} catch (Exception $e) {
error_log("Processing failed: " . $e->getMessage());
}
// Use:
try {
$result = $this->process();
} catch (Exception $e) {
$log->error("Processing failed", ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
}
```
Use appropriate log levels:
```php
// Instead of:
error_log("User logged in");
error_log("Processing data...");
// Use:
$log->info("User logged in", ['user_id' => $userId, 'ip' => $ipAddress]);
$log->debug("Processing data", ['data_size' => count($data), 'processor' => 'batch']);
```
Use appropriate log levels:
```php
// Instead of:
var_dump($data);
die('debug point');
// Use:
$log->debug('Data dump', ['data' => $data]);
// Remove debug statements entirely
```
Flag TODO/FIXME comments that indicate technical debt:
1. TODO comments without clear action items
2. FIXME comments indicating broken functionality
3. HACK comments indicating temporary workarounds
4. XXX comments indicating problematic code
These should be converted to proper issues or addressed:
```php
// Instead of:
// TODO: fix this later
// FIXME: this is broken
// Use:
// Create proper issue and reference it
// @see Issue #123: Refactor validation logic
```
Flag @SuppressWarnings annotations that may indicate code quality issues:
1. Excessive use of @SuppressWarnings
2. Suppressing warnings without proper justification
3. Suppressing warnings that could be fixed with refactoring
Consider refactoring instead of suppressing:
```php
// Instead of:
/**
* @SuppressWarnings(Complexity)
*/
public function complexMethod() { /* 200 lines */ }
// Use:
// Break down into smaller, focused methods
public function processData() {
$this->validateInput();
$this->transformData();
$this->saveResults();
}
```
Flag potential security vulnerabilities:
1. Hardcoded passwords, secrets, or API keys
2. Use of dangerous functions: eval(), exec(), system(), shell_exec()
3. Dynamic includes/requires with user input
4. SQL injection vulnerabilities (direct variable interpolation)
5. XSS vulnerabilities (unfiltered output)
Example fixes:
```php
// Instead of:
eval($userInput);
include($_GET['file']);
// Use:
// Avoid eval() entirely
// Use whitelist validation for includes
$allowedFiles = ['config.php', 'template.php'];
if (in_array($file, $allowedFiles)) {
include($file);
}
```
Flag database security issues:
1. Direct variable interpolation in SQL queries
2. Missing parameter binding
3. Use of deprecated mysql_* functions
4. Unfiltered user input in database operations
Example fixes:
```php
// Instead of:
$query = "SELECT * FROM users WHERE id = $userId";
// Use:
$query = "SELECT * FROM users WHERE id = ?";
$stmt->bind_param('i', $userId);
```
Flag code complexity issues:
1. Methods longer than 50 lines
2. Classes with too many responsibilities
3. Deep nesting (more than 3 levels)
4. Cyclomatic complexity > 10
5. Missing type hints and return types
Consider refactoring:
```php
// Instead of:
public function processEverything($data) {
// 100+ lines of mixed logic
}
// Use:
public function processData(array $data): Result {
$this->validate($data);
$transformed = $this->transform($data);
return $this->save($transformed);
}
```
Flag configuration and environment issues:
1. Hardcoded configuration values
2. Missing environment variable checks
3. Debug settings enabled in production code
4. Inconsistent configuration patterns
Example fixes:
```php
// Instead of:
const DEBUG = true;
const DB_PASSWORD = 'hardcoded_password';
// Use:
const DEBUG = getenv('APP_DEBUG') === 'true';
const DB_PASSWORD = getenv('DB_PASSWORD') ?: throw new Exception('DB_PASSWORD not set');
```
Flag poor error handling:
1. Empty catch blocks
2. Generic exception catching
3. Missing error logging
4. Silent failures
5. Inconsistent error response formats
Example improvements:
```php
// Instead of:
try {
$result = $this->process();
} catch (Exception $e) {
// Empty catch block
}
// Use:
try {
$result = $this->process();
} catch (SpecificException $e) {
$log->error('Processing failed', ['error' => $e->getMessage()]);
throw new ProcessException('Failed to process data', 0, $e);
}
```
Flag performance issues:
1. N+1 query problems
2. Unnecessary database queries in loops
3. Large data processing without pagination
4. Missing caching opportunities
5. Inefficient string concatenation in loops
Example fixes:
```php
// Instead of:
foreach ($users as $user) {
$profile = $this->getUserProfile($user->id); // N+1 query
}
// Use:
$userIds = array_column($users, 'id');
$profiles = $this->getUserProfiles($userIds); // Single query
```
Flag deprecated/legacy code usage:
1. Any usage of @deprecated methods, classes, or properties
2. Calls to deprecated functions (look for @deprecated in docblocks or comments)
3. Encourage migration to newer APIs or patterns
Example:
```php
// Instead of:
/** @deprecated Use newMethod() instead */
public function oldMethod() {}
$this->oldMethod();
// Use:
$this->newMethod();
```
Flag excessive function parameters:
1. Functions/methods with more than 4-5 parameters (especially if many are optional)
2. Suggest refactoring to use objects or associative arrays for complex parameter sets
Example:
```php
// Instead of:
public function foo($a, $b, $c, $d, $e, $f) {}
// Use:
public function foo(FooOptions $options) {}
```
Flag global/static state:
1. Use of global variables
2. Excessive use of static properties (except for constants)
3. Encourage dependency injection or instance-based design
Example:
```php
// Instead of:
global $myVar;
// Use:
$this->myVar;
```
Flag anonymous functions in loops:
1. Creation of closures inside loops (foreach, for, while)
2. Suggest moving closure definition outside the loop
Example:
```php
// Instead of:
foreach ($items as $item) {
$callback = function($x) { return $x * 2; };
$result[] = $callback($item);
}
// Use:
$callback = function($x) { return $x * 2; };
foreach ($items as $item) {
$result[] = $callback($item);
}
```
Flag unnecessary type casting:
1. Unnecessary or redundant type casts (e.g., (int)(int)$x)
2. Type casts that can be avoided by using proper types
Example:
```php
// Instead of:
$x = (int)(int)$y;
// Use:
$x = (int)$y;
```
Flag unoptimized loops:
1. Nested loops with potential for O(n^2) or worse complexity, especially if not commented
2. Loops that can be replaced with built-in functions or more efficient algorithms
Example:
```php
// Instead of:
foreach ($a as $x) {
foreach ($b as $y) {
if ($x === $y) { ... }
}
}
// Use:
$bSet = array_flip($b);
foreach ($a as $x) {
if (isset($bSet[$x])) { ... }
}
```
- path: "**/*.php"
instructions: |
# PHP Variables - Clean Code Rules
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Use meaningful and pronounceable variable names
```php
// Bad:
$ymdstr = $moment->format('y-m-d');
// Good:
$currentDate = $moment->format('y-m-d');
```
## Use the same vocabulary for the same type of variable
```php
// Bad:
getUserInfo();
getUserData();
getUserRecord();
getUserProfile();
// Good:
getUser();
```
## Use searchable names
```php
// Bad:
$result = $serializer->serialize($data, 448);
// Good:
$json = $serializer->serialize($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
```
## Use explanatory variables
```php
// Bad:
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(.+?)\s*(\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);
// Good:
$address = 'One Infinite Loop, Cupertino 95014';
$cityZipCodeRegex = '/^[^,]+,\s*(?<city>.+?)\s*(?<zipCode>\d{5})$/';
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches['city'], $matches['zipCode']);
```
## Avoid nesting too deeply and return early
```php
// Bad:
function isShopOpen($day): bool
{
if ($day) {
if (is_string($day)) {
$day = strtolower($day);
if ($day === 'friday') {
return true;
} elseif ($day === 'saturday') {
return true;
} elseif ($day === 'sunday') {
return true;
}
return false;
}
return false;
}
return false;
}
// Good:
function isShopOpen(string $day): bool
{
if (empty($day)) {
return false;
}
$openingDays = ['friday', 'saturday', 'sunday'];
return in_array(strtolower($day), $openingDays, true);
}
```
## Avoid Mental Mapping
```php
// Bad:
$l = ['Austin', 'New York', 'San Francisco'];
for ($i = 0; $i < count($l); $i++) {
$li = $l[$i];
doStuff();
dispatch($li);
}
// Good:
$locations = ['Austin', 'New York', 'San Francisco'];
foreach ($locations as $location) {
doStuff();
dispatch($location);
}
```
## Don't add unneeded context
```php
// Bad:
class Car
{
public $carMake;
public $carModel;
public $carColor;
}
// Good:
class Car
{
public $make;
public $model;
public $color;
}
```
- path: "**/*.php"
instructions: |
# PHP Comparison - Clean Code Rules
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Use identical comparison
```php
// Bad:
$a = '42';
$b = 42;
if ($a != $b) {
// The expression will always pass
}
// Good:
$a = '42';
$b = 42;
if ($a !== $b) {
// The expression is verified
}
```
## Null coalescing operator
```php
// Bad:
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
// Good:
$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';
```
- path: "**/*.php"
instructions: |
# PHP Functions - Clean Code Rules (Part 1)
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Use default arguments instead of short circuiting or conditionals
```php
// Bad:
function createMicrobrewery($breweryName = 'Hipster Brew Co.'): void
{
// ...
}
// Good:
function createMicrobrewery(string $breweryName = 'Hipster Brew Co.'): void
{
// ...
}
```
## Function arguments (2 or fewer ideally)
```php
// Bad:
class Questionnaire
{
public function __construct(
string $firstname,
string $lastname,
string $patronymic,
string $region,
string $district,
string $city,
string $phone,
string $email
) {
// ...
}
}
// Good:
class Name
{
private $firstname;
private $lastname;
private $patronymic;
public function __construct(string $firstname, string $lastname, string $patronymic)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->patronymic = $patronymic;
}
}
class Questionnaire
{
public function __construct(Name $name, City $city, Contact $contact)
{
// ...
}
}
```
## Function names should say what they do
```php
// Bad:
class Email
{
public function handle(): void
{
mail($this->to, $this->subject, $this->body);
}
}
$message->handle();
// Good:
class Email
{
public function send(): void
{
mail($this->to, $this->subject, $this->body);
}
}
$message->send();
```
- path: "**/*.php"
instructions: |
# PHP Functions - Clean Code Rules (Part 2)
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Functions should only be one level of abstraction
```php
// Bad:
function parseBetterPHPAlternative(string $code): void
{
$regexes = [/* ... */];
$statements = explode(' ', $code);
$tokens = [];
foreach ($regexes as $regex) {
foreach ($statements as $statement) {
// ...
}
}
$ast = [];
foreach ($tokens as $token) {
// lex...
}
foreach ($ast as $node) {
// parse...
}
}
// Good:
class Tokenizer
{
public function tokenize(string $code): array
{
// ...
}
}
class BetterPHPAlternative
{
private $tokenizer;
private $lexer;
public function __construct(Tokenizer $tokenizer, Lexer $lexer)
{
$this->tokenizer = $tokenizer;
$this->lexer = $lexer;
}
public function parse(string $code): void
{
$tokens = $this->tokenizer->tokenize($code);
$ast = $this->lexer->lexify($tokens);
foreach ($ast as $node) {
// parse...
}
}
}
```
## Don't use flags as function parameters
```php
// Bad:
function createFile(string $name, bool $temp = false): void
{
if ($temp) {
touch('./temp/' . $name);
} else {
touch($name);
}
}
// Good:
function createFile(string $name): void
{
touch($name);
}
function createTempFile(string $name): void
{
touch('./temp/' . $name);
}
```
- path: "**/*.php"
instructions: |
# PHP Functions - Clean Code Rules (Part 3)
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Avoid Side Effects
```php
// Bad:
$name = 'Ryan McDermott';
function splitIntoFirstAndLastName(): void
{
global $name;
$name = explode(' ', $name);
}
splitIntoFirstAndLastName();
// Good:
function splitIntoFirstAndLastName(string $name): array
{
return explode(' ', $name);
}
$name = 'Ryan McDermott';
$newName = splitIntoFirstAndLastName($name);
```
## Don't write to global functions
```php
// Bad:
function config(): array
{
return ['foo' => 'bar'];
}
// Good:
class Configuration
{
private $configuration = [];
public function __construct(array $configuration)
{
$this->configuration = $configuration;
}
public function get(string $key): ?string
{
return $this->configuration[$key] ?? null;
}
}
```
## Don't use a Singleton pattern
```php
// Bad:
class DBConnection
{
private static $instance;
private function __construct(string $dsn) { /* ... */ }
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
$singleton = DBConnection::getInstance();
// Good:
class DBConnection
{
public function __construct(string $dsn) { /* ... */ }
}
$connection = new DBConnection($dsn);
```
- path: "**/*.php"
instructions: |
# PHP Functions - Clean Code Rules (Part 4)
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Encapsulate conditionals
```php
// Bad:
if ($article->state === 'published') {
// ...
}
// Good:
if ($article->isPublished()) {
// ...
}
```
## Avoid negative conditionals
```php
// Bad:
function isDOMNodeNotPresent(DOMNode $node): bool
{
// ...
}
if (! isDOMNodeNotPresent($node)) {
// ...
}
// Good:
function isDOMNodePresent(DOMNode $node): bool
{
// ...
}
if (isDOMNodePresent($node)) {
// ...
}
```
## Avoid conditionals
```php
// Bad:
class Airplane
{
public function getCruisingAltitude(): int
{
switch ($this->type) {
case '777':
return $this->getMaxAltitude() - $this->getPassengerCount();
case 'Air Force One':
return $this->getMaxAltitude();
case 'Cessna':
return $this->getMaxAltitude() - $this->getFuelExpenditure();
}
}
}
// Good:
interface Airplane
{
public function getCruisingAltitude(): int;
}
class Boeing777 implements Airplane
{
public function getCruisingAltitude(): int
{
return $this->getMaxAltitude() - $this->getPassengerCount();
}
}
```
## Avoid type-checking
```php
// Bad:
function travelToTexas($vehicle): void
{
if ($vehicle instanceof Bicycle) {
$vehicle->pedalTo(new Location('texas'));
} elseif ($vehicle instanceof Car) {
$vehicle->driveTo(new Location('texas'));
}
}
// Good:
function travelToTexas(Vehicle $vehicle): void
{
$vehicle->travelTo(new Location('texas'));
}
```
## Remove dead code
```php
// Bad:
function oldRequestModule(string $url): void { /* ... */ }
function newRequestModule(string $url): void { /* ... */ }
$request = newRequestModule($requestUrl);
// Good:
function requestModule(string $url): void { /* ... */ }
$request = requestModule($requestUrl);
```
- path: "**/*.php"
instructions: |
# PHP Objects and Data Structures - Clean Code Rules
Based on [piotrplenik/clean-code-php](https://github.com/piotrplenik/clean-code-php/):
## Use object encapsulation
```php
// Bad:
class BankAccount
{
public $balance = 1000;
}
$bankAccount = new BankAccount();
$bankAccount->balance -= 100;
// Good:
class BankAccount
{
private $balance;
public function __construct(int $balance = 1000)
{
$this->balance = $balance;
}
public function withdraw(int $amount): void
{
if ($amount > $this->balance) {
throw new \Exception('Amount greater than available balance.');
}
$this->balance -= $amount;
}
public function getBalance(): int
{
return $this->balance;
}
}
$bankAccount = new BankAccount();
$bankAccount->withdraw($shoesPrice);
```
## Make objects have private/protected members
```php
// Bad:
class Employee
{
public $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
echo 'Employee name: ' . $employee->name;
// Good:
class Employee
{
private $name;
public function __construct(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
echo 'Employee name: ' . $employee->getName();
```