PHP Code Review Expert
This skill provides comprehensive PHP code review capabilities, combining automated analysis with expert-level insights for PHP7 and PHP8 development.
Quick Start
- Automated Security Scan: Use
scripts/php-security-scanner.php for initial vulnerability detection
- Code Style Check: Apply configurations from
references/php-cs-fixer-config.md
- Manual Review: Follow the systematic review process outlined below
- Report Generation: Use the structured output format for consistent documentation
Available Resources
- Scripts:
php-security-scanner.php - Automated security vulnerability scanner
- References:
php-cs-fixer-config.md - Ready-to-use PHP CS Fixer configurations
- Examples:
before-after-refactor.md - Real-world refactoring examples
- Templates:
review-report-template.md - Comprehensive review report format
quick-checklist.md - 30-minute quick review checklist
Core Review Areas
1. Naming Conventions Check
Class Naming
- PSR-4 Compliance: Class names must match file names
- CamelCase: Use PascalCase for class names (e.g.,
UserController)
- Suffix Patterns:
- Controllers end with
Controller (e.g., UserController)
- Models end with
Model or use singular nouns (e.g., User)
- Services end with
Service (e.g., EmailService)
Method Naming
- camelCase: Methods use camelCase (e.g.,
getUserName())
- Verb-Noun Pattern: Start with action word (e.g.,
validateInput(), processOrder())
- Boolean Methods: Use is/has/can prefix (e.g.,
isValid(), hasPermission())
Variable Naming
- camelCase: Variables use camelCase (e.g.,
$userName)
- Descriptive: Use meaningful names (e.g.,
$customerEmail not $e)
- Constants: UPPER_SNAKE_CASE (e.g.,
MAX_RETRY_COUNT)
Database Naming
- Table Names: snake_case, plural (e.g.,
user_profiles)
- Column Names: snake_case (e.g.,
created_at)
- Foreign Keys:
{singular_table}_id (e.g., user_id)
2. Syntax Validation (PHP7 vs PHP8)
PHP8 Features to Embrace
- Union Types:
function process(int|float $value)
- Named Arguments:
createUser(name: 'John', email: 'john@example.com')
- Null safe Operator:
$user?->profile?->avatar
- Match Expression:
match($status) { 1 => 'active', 2 => 'inactive' }
- Constructor Property Promotion:
public function __construct(private string $name)
- Null Coalescing Assignment:
$user['name'] ??= 'Anonymous'
PHP7 Compatibility
- Typed Properties: Ensure PHP7.4+ if using typed properties
- Return Type Declarations: Check for PHP7.0+ compatibility
- Array Destructuring:
["id" => $userId, "name" => $userName] = $user;
Syntax Pitfalls to Avoid
- Missing Semicolons: Classic error in PHP
- Undefined Variables: Check for
$variable before use
- Array Access: Use
isset($array['key']) before accessing
- String Concatenation: Prefer
"{$variable}" over "$variable"
3. Logic Analysis
Control Flow Issues
- Deep Nesting: Maximum 3 levels, refactor with early returns
- Complex Conditions: Break down complex boolean expressions
- Switch Statements: Ensure all cases have breaks or returns
- Loop Performance: Use
foreach instead of for where possible
Error Handling
- Try-Catch Blocks: Always catch specific exceptions
- Error Suppression: Never use
@ operator
- Validation: Validate all inputs before processing
- Graceful Degradation: Handle edge cases properly
Security Logic
- Input Sanitization: Never trust user input
- SQL Injection: Use prepared statements exclusively
- XSS Prevention: Escape output with
htmlspecialchars()
- CSRF Protection: Implement tokens for state-changing operations
- File Upload: Validate file types and sizes strictly
4. Performance Optimization
Database Queries
- N+1 Problem: Use eager loading (e.g.,
with('comments'))
- Query Optimization: Add indexes on frequently queried columns
- Pagination: Always paginate large datasets
- Caching: Cache expensive queries with Redis/Memcached
Memory Management
- Large Arrays: Process in chunks for large datasets
- Unnecessary Variables: Unset large variables after use
- Generator Functions: Use
yield for memory-efficient iteration
- Object Caching: Reuse objects instead of recreating
Code Efficiency
- String Operations: Use
strpos() instead of preg_match() for simple searches
- Array Functions: Leverage built-in functions like
array_map(), array_filter()
- Early Returns: Reduce nesting and improve readability
- Lazy Loading: Load resources only when needed
5. Security Vulnerabilities
Critical Security Checks
- SQL Injection:
- ❌
SELECT * FROM users WHERE id = $_GET['id']
- ✅ Use PDO prepared statements
- XSS Attacks:
- ❌
echo $_POST['username']
- ✅
echo htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8')
- File Inclusion:
- ❌
include($_GET['file'])
- ✅ Whitelist allowed files, use absolute paths
- Command Injection:
- ❌
shell_exec($_GET['command'])
- ✅ Use
escapeshellarg() and validate inputs
Authentication & Authorization
- Password Security: Use
password_hash() and password_verify()
- Session Management: Regenerate session IDs, set secure session parameters
- Access Control: Implement role-based access control (RBAC)
- API Security: Validate API tokens on every request
6. Code Quality Metrics
Cyclomatic Complexity
- Target: Maximum 10 per method
- Refactoring: Break down complex methods
- Testing: Ensure each branch has test coverage
Code Reusability
- DRY Principle: Don't Repeat Yourself
- Single Responsibility: Each method/class has one purpose
- Composition over Inheritance: Favor composition for flexibility
Documentation
- PHPDoc: Document all public methods and classes
- Type Declarations: Use strong typing where possible
- Inline Comments: Explain complex business logic
- README: Keep project documentation updated
Review Process
Step 1: Automated Scanning (If the environment exists)
- Syntax Check:
php -l filename.php
- Code Standards: Run PHP_CodeSniffer with PSR-12
- Static Analysis: Use PHPStan or Psalm
- Security Scan: Run security checkers
Step 2: Manual Review
- Readability: Is the code easy to understand?
- Maintainability: Can future developers easily modify this?
- Performance: Are there obvious bottlenecks?
- Security: Are there potential vulnerabilities?
Step 3: Testing
- Unit Tests: Ensure adequate coverage (80%+)
- Integration Tests: Test component interactions
- Performance Tests: Benchmark critical paths
Common Code Smells
Red Flags
- Long Methods: > 50 lines
- Large Classes: > 500 lines
- Too Many Parameters: > 4 parameters
- Duplicate Code: Same logic in multiple places
- Dead Code: Unused variables, methods, or classes
- Magic Numbers: Hardcoded values without explanation
- Inconsistent Formatting: Mixing styles
Refactoring Patterns
- Extract Method: Break down complex methods
- Extract Class: Separate responsibilities
- Replace Magic Numbers: Use named constants
- Introduce Parameter Object: Group related parameters
- Encapsulate Collection: Control collection access
PHP7 vs PHP8 Compatibility Checklist
PHP8+ Features (Use When Available)
PHP7.4+ Features
Backward Compatibility
Best Practices Summary
Do
- ✓ Use meaningful variable and method names
- ✓ Write self-documenting code
- ✓ Keep methods small and focused
- ✓ Use type declarations
- ✓ Write tests for critical logic
- ✓ Handle errors gracefully
- ✓ Validate all inputs
- ✓ Use dependency injection
- ✓ Follow PSR standards
- ✓ Document complex business logic
Don't
- ✗ Use global variables
- ✗ Suppress errors with
@
- ✗ Trust user input without validation
- ✗ Mix business logic with presentation
- ✗ Create god classes that do everything
- ✗ Use magic methods excessively
- ✗ Ignore performance implications
- ✗ Skip error handling
- ✗ Hardcode configuration values
- ✗ Leave debug code in production
Review Output Format
When reviewing code, use the standardized templates:
For Comprehensive Reviews
Use templates/review-report-template.md which provides:
- Executive summary with key findings
- Categorized issues (Critical/Standards/Improvements)
- Security and performance assessments
- PHP compatibility analysis
- Actionable recommendations with timelines
For Quick Reviews
Use templates/quick-checklist.md for:
- 30-minute focused review process
- Essential security and quality checks
- Pull request reviews
- Pre-deployment validation
Custom Format
For specific needs, provide feedback in this structure:
## Code Review: [filename]
### Summary
[Overall assessment]
### Critical Issues (Must Fix)
- [ ] [Issue description and suggested fix]
### Standards Violations (Should Fix)
- [ ] [Issue and recommended solution]
### Improvements (Nice to Have)
- [ ] [Suggestion for better code quality]
### Performance Impact
- [Analysis of performance implications]
### Security Assessment
- [Security vulnerabilities found]
### PHP Compatibility
- [PHP version compatibility issues]
References
- See
references/php-cs-fixer-config.md for automated code style configuration
- See
examples/before-after-refactor.md for refactoring examples
- Use
scripts/php-security-scanner.php for automated security scanning
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: php-code-review3description: Comprehensive PHP code review with security analysis, performance optimization, and PSR-12 compliance checking for PHP7/PHP8 projects Use when this capability is needed.4---56# PHP Code Review Expert78This skill provides comprehensive PHP code review capabilities, combining automated analysis with expert-level insights for PHP7 and PHP8 development.910## Quick Start11121. **Automated Security Scan**: Use `scripts/php-security-scanner.php` for initial vulnerability detection132. **Code Style Check**: Apply configurations from `references/php-cs-fixer-config.md`143. **Manual Review**: Follow the systematic review process outlined below154. **Report Generation**: Use the structured output format for consistent documentation1617## Available Resources1819- **Scripts**: `php-security-scanner.php` - Automated security vulnerability scanner20- **References**: `php-cs-fixer-config.md` - Ready-to-use PHP CS Fixer configurations 21- **Examples**: `before-after-refactor.md` - Real-world refactoring examples22- **Templates**: 23 - `review-report-template.md` - Comprehensive review report format24 - `quick-checklist.md` - 30-minute quick review checklist2526## Core Review Areas2728### 1. Naming Conventions Check2930#### Class Naming31- **PSR-4 Compliance**: Class names must match file names32- **CamelCase**: Use PascalCase for class names (e.g., `UserController`)33- **Suffix Patterns**: 34 - Controllers end with `Controller` (e.g., `UserController`)35 - Models end with `Model` or use singular nouns (e.g., `User`)36 - Services end with `Service` (e.g., `EmailService`)3738#### Method Naming39- **camelCase**: Methods use camelCase (e.g., `getUserName()`)40- **Verb-Noun Pattern**: Start with action word (e.g., `validateInput()`, `processOrder()`)41- **Boolean Methods**: Use is/has/can prefix (e.g., `isValid()`, `hasPermission()`)4243#### Variable Naming44- **camelCase**: Variables use camelCase (e.g., `$userName`)45- **Descriptive**: Use meaningful names (e.g., `$customerEmail` not `$e`)46- **Constants**: UPPER_SNAKE_CASE (e.g., `MAX_RETRY_COUNT`)4748#### Database Naming49- **Table Names**: snake_case, plural (e.g., `user_profiles`)50- **Column Names**: snake_case (e.g., `created_at`)51- **Foreign Keys**: `{singular_table}_id` (e.g., `user_id`)5253### 2. Syntax Validation (PHP7 vs PHP8)5455#### PHP8 Features to Embrace56- **Union Types**: `function process(int|float $value)`57- **Named Arguments**: `createUser(name: 'John', email: 'john@example.com')`58- **Null safe Operator**: `$user?->profile?->avatar`59- **Match Expression**: `match($status) { 1 => 'active', 2 => 'inactive' }`60- **Constructor Property Promotion**: `public function __construct(private string $name)`61- **Null Coalescing Assignment**: `$user['name'] ??= 'Anonymous'`6263#### PHP7 Compatibility64- **Typed Properties**: Ensure PHP7.4+ if using typed properties65- **Return Type Declarations**: Check for PHP7.0+ compatibility66- **Array Destructuring**: `["id" => $userId, "name" => $userName] = $user;`6768#### Syntax Pitfalls to Avoid69- **Missing Semicolons**: Classic error in PHP70- **Undefined Variables**: Check for `$variable` before use71- **Array Access**: Use `isset($array['key'])` before accessing72- **String Concatenation**: Prefer `"{$variable}"` over `"$variable"`7374### 3. Logic Analysis7576#### Control Flow Issues77- **Deep Nesting**: Maximum 3 levels, refactor with early returns78- **Complex Conditions**: Break down complex boolean expressions79- **Switch Statements**: Ensure all cases have breaks or returns80- **Loop Performance**: Use `foreach` instead of `for` where possible8182#### Error Handling83- **Try-Catch Blocks**: Always catch specific exceptions84- **Error Suppression**: Never use `@` operator85- **Validation**: Validate all inputs before processing86- **Graceful Degradation**: Handle edge cases properly8788#### Security Logic89- **Input Sanitization**: Never trust user input90- **SQL Injection**: Use prepared statements exclusively91- **XSS Prevention**: Escape output with `htmlspecialchars()`92- **CSRF Protection**: Implement tokens for state-changing operations93- **File Upload**: Validate file types and sizes strictly9495### 4. Performance Optimization9697#### Database Queries98- **N+1 Problem**: Use eager loading (e.g., `with('comments')`)99- **Query Optimization**: Add indexes on frequently queried columns100- **Pagination**: Always paginate large datasets101- **Caching**: Cache expensive queries with Redis/Memcached102103#### Memory Management104- **Large Arrays**: Process in chunks for large datasets105- **Unnecessary Variables**: Unset large variables after use106- **Generator Functions**: Use `yield` for memory-efficient iteration107- **Object Caching**: Reuse objects instead of recreating108109#### Code Efficiency110- **String Operations**: Use `strpos()` instead of `preg_match()` for simple searches111- **Array Functions**: Leverage built-in functions like `array_map()`, `array_filter()`112- **Early Returns**: Reduce nesting and improve readability113- **Lazy Loading**: Load resources only when needed114115### 5. Security Vulnerabilities116117#### Critical Security Checks118- **SQL Injection**: 119 - ❌ `SELECT * FROM users WHERE id = $_GET['id']`120 - ✅ Use PDO prepared statements121- **XSS Attacks**:122 - ❌ `echo $_POST['username']`123 - ✅ `echo htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8')`124- **File Inclusion**:125 - ❌ `include($_GET['file'])`126 - ✅ Whitelist allowed files, use absolute paths127- **Command Injection**:128 - ❌ `shell_exec($_GET['command'])`129 - ✅ Use `escapeshellarg()` and validate inputs130131#### Authentication & Authorization132- **Password Security**: Use `password_hash()` and `password_verify()`133- **Session Management**: Regenerate session IDs, set secure session parameters134- **Access Control**: Implement role-based access control (RBAC)135- **API Security**: Validate API tokens on every request136137### 6. Code Quality Metrics138139#### Cyclomatic Complexity140- **Target**: Maximum 10 per method141- **Refactoring**: Break down complex methods142- **Testing**: Ensure each branch has test coverage143144#### Code Reusability145- **DRY Principle**: Don't Repeat Yourself146- **Single Responsibility**: Each method/class has one purpose147- **Composition over Inheritance**: Favor composition for flexibility148149#### Documentation150- **PHPDoc**: Document all public methods and classes151- **Type Declarations**: Use strong typing where possible152- **Inline Comments**: Explain complex business logic153- **README**: Keep project documentation updated154155## Review Process156157### Step 1: Automated Scanning (If the environment exists)1581. **Syntax Check**: `php -l filename.php`1592. **Code Standards**: Run PHP_CodeSniffer with PSR-121603. **Static Analysis**: Use PHPStan or Psalm1614. **Security Scan**: Run security checkers162163### Step 2: Manual Review1641. **Readability**: Is the code easy to understand?1652. **Maintainability**: Can future developers easily modify this?1663. **Performance**: Are there obvious bottlenecks?1674. **Security**: Are there potential vulnerabilities?168169### Step 3: Testing1701. **Unit Tests**: Ensure adequate coverage (80%+)1712. **Integration Tests**: Test component interactions1723. **Performance Tests**: Benchmark critical paths173174## Common Code Smells175176### Red Flags177- **Long Methods**: > 50 lines178- **Large Classes**: > 500 lines179- **Too Many Parameters**: > 4 parameters180- **Duplicate Code**: Same logic in multiple places181- **Dead Code**: Unused variables, methods, or classes182- **Magic Numbers**: Hardcoded values without explanation183- **Inconsistent Formatting**: Mixing styles184185### Refactoring Patterns186- **Extract Method**: Break down complex methods187- **Extract Class**: Separate responsibilities188- **Replace Magic Numbers**: Use named constants189- **Introduce Parameter Object**: Group related parameters190- **Encapsulate Collection**: Control collection access191192## PHP7 vs PHP8 Compatibility Checklist193194### PHP8+ Features (Use When Available)195- [ ] Union Types: `function foo(int|float $bar)`196- [ ] Named Arguments: `array_fill(start_index: 0, count: 100, value: 50)`197- [ ] Match Expression: More concise than switch198- [ ] Null safe Operator: `$country = $session?->user?->getAddress()?->country`199- [ ] Constructor Property Promotion: `public function __construct(private string $name)`200- [ ] Attributes: `#[Route('/users')]`, `#[ORM\Entity]`201202### PHP7.4+ Features203- [ ] Typed Properties: `private string $name;`204- [ ] Arrow Functions: `$ids = array_map(fn(Post $post) => $post->id, $posts)`205- [ ] Null Coalescing Assignment: `$array['key'] ??= 'default'`206- [ ] Spread Operator in Arrays: `$merged = [...$array1, ...$array2]`207208### Backward Compatibility209- [ ] Check PHP version requirements210- [ ] Avoid features not in target PHP version211- [ ] Use polyfills for newer functions if needed212- [ ] Test on minimum supported PHP version213214## Best Practices Summary215216### Do217- ✓ Use meaningful variable and method names218- ✓ Write self-documenting code219- ✓ Keep methods small and focused220- ✓ Use type declarations221- ✓ Write tests for critical logic222- ✓ Handle errors gracefully223- ✓ Validate all inputs224- ✓ Use dependency injection225- ✓ Follow PSR standards226- ✓ Document complex business logic227228### Don't229- ✗ Use global variables230- ✗ Suppress errors with `@`231- ✗ Trust user input without validation232- ✗ Mix business logic with presentation233- ✗ Create god classes that do everything234- ✗ Use magic methods excessively235- ✗ Ignore performance implications236- ✗ Skip error handling237- ✗ Hardcode configuration values238- ✗ Leave debug code in production239240## Review Output Format241242When reviewing code, use the standardized templates:243244### For Comprehensive Reviews245Use `templates/review-report-template.md` which provides:246- Executive summary with key findings247- Categorized issues (Critical/Standards/Improvements)248- Security and performance assessments249- PHP compatibility analysis250- Actionable recommendations with timelines251252### For Quick Reviews253Use `templates/quick-checklist.md` for:254- 30-minute focused review process255- Essential security and quality checks256- Pull request reviews257- Pre-deployment validation258259### Custom Format260For specific needs, provide feedback in this structure:261262```markdown263## Code Review: [filename]264265### Summary266[Overall assessment]267268### Critical Issues (Must Fix)269- [ ] [Issue description and suggested fix]270271### Standards Violations (Should Fix)272- [ ] [Issue and recommended solution]273274### Improvements (Nice to Have)275- [ ] [Suggestion for better code quality]276277### Performance Impact278- [Analysis of performance implications]279280### Security Assessment281- [Security vulnerabilities found]282283### PHP Compatibility284- [PHP version compatibility issues]285```286287## References288289- See `references/php-cs-fixer-config.md` for automated code style configuration290- See `examples/before-after-refactor.md` for refactoring examples291- Use `scripts/php-security-scanner.php` for automated security scanning292293---294> Converted and distributed by [TomeVault](https://tomevault.io/claim/jeeinn) — claim your Tome and manage your conversions.295<!-- tomevault:4.0:skill_md:2026-04-11 -->