johnatas-x/phpcpd
Laravel-friendly wrapper for PHP Copy/Paste Detector (PHPCPD) to spot duplicated code in your PHP projects. Run duplication checks from your tooling/CI and get actionable reports to reduce redundancy and improve maintainability.
Installation Add the package via Composer:
composer require --dev johnatas-x/phpcpd
Ensure phpcpd is listed under require-dev in composer.json.
Basic Usage
Run CPD on a directory (e.g., app/) via Artisan:
php artisan cpdetect:run app/
Output will show duplicate code blocks with file locations and line numbers.
First Use Case Integrate into your CI pipeline (e.g., GitHub Actions) to flag duplicates pre-merge:
- name: Run CPD
run: php artisan cpdetect:run app/ --min-tokens=50 --exclude=tests/
Pre-Commit Hook
Use phpcpd via a Git hook to block duplicates early:
composer require --dev php-cpd
echo 'php vendor/bin/phpcpd --min-tokens=50 app/' >> .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
Laravel Artisan Command Extend the package’s CLI with custom logic:
// app/Console/Commands/DetectDuplicates.php
use Illuminate\Console\Command;
use PhpCpd\Cpd;
class DetectDuplicates extends Command {
protected $signature = 'cpd:custom {path}';
public function handle() {
$cpd = new Cpd();
$report = $cpd->processDirectory($this->argument('path'));
$this->line($report->getReport());
}
}
Integration with PHPStan/Laravel-Pint Chain CPD with static analysis tools for comprehensive checks:
composer exec phpstan analyse --level=max && php artisan cpdetect:run app/
--min-tokens (default: 100) to balance sensitivity vs. noise.--exclude to skip vendor/ or generated files:
php artisan cpdetect:run app/ --exclude=vendor,storage
php artisan cpdetect:run app/ --format=html > reports/cpd.html
False Positives
--min-tokens or exclude specific files/directories.Performance
parallel-lint.Configuration Overrides
phpcpd.php).--config to specify a custom config file:
php artisan cpdetect:run app/ --config=phpcpd_custom.php
-v for detailed output:
php artisan cpdetect:run app/ -v
php artisan cpdetect:run app/ --dry-run
Custom Report Formatting
Extend the PhpCpd\Report class to add Slack/email alerts:
class SlackReport extends \PhpCpd\Report {
public function getReport() {
return "```" . parent::getReport() . "```";
}
}
Token Filtering
Override PhpCpd\Tokenizer\Tokenizer to ignore specific patterns (e.g., UUIDs):
class CustomTokenizer extends \PhpCpd\Tokenizer\Tokenizer {
protected function shouldIgnoreToken($token) {
return parent::shouldIgnoreToken($token) || str_contains($token, 'uuid-');
}
}
CI Integration Fail builds on duplicates:
- name: Enforce CPD
run: php artisan cpdetect:run app/ || exit 1
How can I help you explore Laravel packages today?