Увійти Реєстрація
Блог Серії
Кар'єра
Вакансії Компанії
Навчання
Співбесіди Тестування Відео
Екосистема
Пакети Ресурси Проєкти
Інше
Події Про нас
Новини 04 липня 2026
1

Детектор дублювання коду phpcpd-next для PHP 8.5+

phpcpd-next сканує PHP-код і виявляє блоки, які були скопійовані з одного місця в інше - той тип дублювання, який легко пропустити під час ревʼю коду, але складно підтримувати синхронізованим згодом.

Інструмент підтримується Luciano Federico Pereira як наступник архівованого phpcpd від Sebastian Bergmann і залишається повністю сумісною заміною з тією ж командою phpcpd.

Що нового: більше ніж точне копіювання

На відміну від попередньої версії, phpcpd-next виявляє не лише дослівні копії, а й дублікати, де рядки були переупорядковані або де між двома ідентичними блоками додали чи видалили один вираз:

  • Три алгоритми детекції - Rabin-Karp (точні збіги), TokenBag (виявлення переупорядкованих фрагментів) та опціональне суфіксне дерево (для клонів Type-3 з пропусками), плюс режим --fuzzy для нечутливості до перейменувань
  • Чотири формати виводу - консольний текст, PMD-CPD XML, JSON та SARIF 2.1.0 для GitHub Code Scanning
  • Headless API для виклику детекції всередині процесу, плюс PHPUnit-трейт, що перетворює перевірку дублювання на тестове твердження
  • Можливості для CI - значущі exit-коди, повне кешування результатів та інкрементальна індексація по файлах
  • Пресети для фреймворків, включно з Laravel, із CLI-прапорцями для перевизначення налаштувань пресетів
  • PHP 8.5+ без runtime-залежностей Composer та детерміністичні результати

Три алгоритми, що працюють разом

Більшість детекторів copy/paste знаходять лише точне дублювання. phpcpd-next за замовчуванням запускає Rabin-Karp (точні послідовні збіги) та TokenBag (overlap незалежно від порядку, тому переставлені вирази також реєструються) одночасно при кожному запуску. Алгоритм суфіксного дерева для клонів з пропусками - коли між ідентичними блоками вставили або видалили вираз - активується опціонально:

# За замовчуванням: точна + детекція переупорядкованих фрагментів
phpcpd src/

# Лише Rabin-Karp (швидше, без детекції переупорядкування)
phpcpd --rk src/

# Клони Type-3 з пропусками через суфіксне дерево
phpcpd --algorithm=suffixtree src/

Консольний вивід вказує на продубльовані діапазони та пропонує рефакторинг замість простого переліку номерів рядків:

Found 2 code clones with 21 duplicated lines in 2 files:
- app/Services/Billing.php:12-33 (21 lines)
  app/Services/Invoicing.php:40-61
→ Consider extracting the shared lines into a reusable method or constant.
37.50% duplicated lines out of 56 total lines of code.

Вивід SARIF для GitHub Code Scanning

Поряд із PMD-CPD XML та JSON, phpcpd-next генерує SARIF 2.1.0, тому клони відображаються у вкладці Security на GitHub. Неузгоджені (розбіжні) клони маркуються рівнем warning, точні клони - note:

- name: Detect duplicated code
  run: vendor/bin/phpcpd --log-sarif=phpcpd.sarif src/ || true

- name: Upload results
  uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: phpcpd.sarif

Headless API та PHPUnit-твердження

Окрім CLI, детекція виконується всередині процесу через статичний виклик detect() - без запуску shell-команд, без файлів звітів:

use LucianoPereira\PhpcpdNext\Phpcpd;

$clones = Phpcpd::detect(
    paths: 'app',
    minTokens: 60,
    algorithm: null,       // null = Rabin-Karp + TokenBag
    preset: 'laravel',
);

foreach ($clones as $clone) {
    echo $clone->numberOfLines(), " lines\n";
}

Вбудований трейт перетворює це на тест, тому дублювання стає регресійною перевіркою, що падає з локаціями клонів:

use LucianoPereira\PhpcpdNext\PHPUnit\AssertNoDuplication;
use PHPUnit\Framework\TestCase;

final class DuplicationTest extends TestCase
{
    use AssertNoDuplication;

    public function test_app_is_dry(): void
    {
        $this->assertNoDuplication(__DIR__ . '/../app', minTokens: 70);
    }
}

Інкрементальне кешування для CI

Для великих кодових баз --cache зберігає результати, ключовані відбитком конфігурації та хешем маніфесту файлів, відтворюючи кешований результат, коли нічого не змінилося. --incremental йде далі, повторно токенізуючи лише змінені файли та використовуючи решту з індексу по файлах (лише Rabin-Karp), друкуючи підсумок на зразок (incremental index: 412 reused, 3 scanned):

- uses: actions/cache@v4
  with:
    path: .phpcpd-cache
    key: phpcpd-${{ hashFiles('**/*.php') }}
    restore-keys: phpcpd-

- run: vendor/bin/phpcpd --incremental --cache-dir .phpcpd-cache src/

Встановлення та використання

Інструмент вимагає PHP 8.5+, ext-dom та ext-mbstring, і встановлюється як dev-залежність:

composer require --dev phpcpd-next/phpcpd
vendor/bin/phpcpd src/

Пресет Laravel сканує app, routes, database та config, виключаючи vendor-код, Blade-шаблони, міграції та файли IDE-helper:

vendor/bin/phpcpd --preset=laravel app/Services --min-tokens=60

Вихідний код та повну документацію можна знайти на GitHub.

Коментарі

Увійдіть, щоб залишити коментар

Будьте першим, хто залишить коментар!

Читайте також

Backpack CRUD RCE

Повідомлення про безпеку: неавтентифіковане ін'єктування команд у Backpack\CRUD

Команда Backpack for Laravel опублікувала повідомлення про безпеку: у телеметрії пакета Backpack\CRUD виявлено вразливість, що дозволяла віддалене виконання коду (RCE) без автентифікації. Дослідник безпеки Vishal Shukla (@therawdev) відповідально повідомив про проблему 16 травня 2026 року, і команда розробників випустила виправлення менш ніж за 24 години.

Що нового в PostgreSQL 19: графові запити, GROUP BY ALL і крок до "універсальної" бази даних.

Що нового в PostgreSQL 19: графові запити, GROUP BY ALL і крок до "універсальної" бази даних.

PostgreSQL 19 продовжує важливу тенденцію останніх років: класична реляційна база даних поступово перетворюється на універсальну платформу для роботи з різними типами даних - від JSON до графів і аналітики

Вакансії за темою

Full-time Сьогодні

Senior PHP Developer (Laravel/Symfony)

Improveit Solutions Віддалено За результатами співбесіди

We are looking for an experienced Senior PHP Developer to join our team and help build scalable, high-quality products. In this role, you will actively contribute to architectural decisions, drive technical initiatives, and collaborate closely with the team to deliver reliable and maintainable solutions. Requirements 5+ years of professional experience in software development. Expert-level knowledge of PHP 8.x and modern development practices. 5+ years of experience with Laravel or Symfony, including a deep understanding of framework internals. Strong experience with MySQL or MariaDB, including query optimization, schema design, and database normalization. Solid understanding of REST API design principles. Proficiency with Git, including branching strategies, code reviews, and release workflows. Experience with PHPUnit and defining testing strategies. Hands-on experience with Docker and containerized production environments. Strong knowledge of caching strategies and performance optimization techniques. Experience setting up and maintaining CI/CD pipelines (GitHub preferred). Solid understanding of Composer and dependency management. Comfortable working in Linux/CLI environments. Strong understanding of web application security best practices. Soft Skills Ability to independently design and architect solutions. Strong problem-solving mindset with a focus on maintainability and scalability. Confidence to challenge requirements and propose better alternatives. Ability to translate business needs into effective technical solutions. Experience leading technical initiatives or small teams. Strong written communication skills and experience working in asynchronous environments. Nice to Have Experience in the fintech or financial services domain. Frontend development experience with Vue.js or React. Experience with cloud platforms, preferably Azure. Previous experience conducting technical interviews or participating in hiring processes. What You'll Do Design and develop scalable, high-performance applications and APIs. Participate in architectural decisions and contribute to technical strategy. Collaborate with cross-functional teams to deliver business value. Drive best practices in code quality, testing, security, and performance. Mentor team members and contribute to continuous improvement initiatives. If you enjoy solving complex technical challenges, taking ownership of architecture and technical decisions, and building products that scale, we'd love to hear from you.

Full-time 4 дн. тому

Senior Backend Developer (PHP / Laravel)

VANTREXIS Віддалено За результатами співбесіди

VANTREXIS is an engineering agency that builds dedicated remote teams for high-growth SaaS companies in the US, UK, and EU. We are looking for a Senior Backend Engineer to develop new features in a complex, integration-heavy product environment. The Role You will join a team where AI-augmented development (** Cursor, Claude, Copilot**) is a daily standard, not a bonus. Your focus will be on delivering clean, typed code within established architectural patterns - and raising the quality bar as you go. Tech Stack Core: PHP 8.2 + Laravel 12. Database: MySQL 8 + Redis. ORM: Eloquent. Auth: Laravel Passport (OAuth 2.0), Spatie Permission (RBAC). Queue: Laravel Queue with multiple named workers. Cloud: AWS S3, SES, SNS. Payments: Mollie / Stripe. Real-time: Pusher, Firebase FCM. Testing: PHPUnit 11. What You'll Do Build & Architect: Deliver new API endpoints following the Controller → Service → Repository pattern. Ownership: Take full responsibility for features from analysis to production deployment. Quality First: Write feature tests alongside every new feature to raise current coverage. Integrate: Extend and maintain external integrations (Mollie, AWS, Firebase, healthcare APIs). Proactive Improvement: Identify architectural bottlenecks and edge cases before they become problems. Requirements Expert PHP/Laravel: Deep knowledge of Eloquent, Passport, Policies, Events, and Jobs. RBAC Patterns: Experience with complex authorization flows and company-scoped roles. Database Mastery: MySQL 8 optimization and writing safe, backwards-compatible migrations. Mindset: You think like an owner, not just a task-executor; you communicate risks early. AI-Tooling: Proficiency in using AI-powered tools to maximize engineering efficiency. Testing Culture: A "craftsmanship" approach where untested code is not considered "done". Nice to Have Experience with Mollie or equivalent payment lifecycles. Familiarity with AWS IVS (live streaming) or Pusher. Experience using PHPStan / Larastan for static analysis. An active GitHub profile or technical pet-projects. What We Offer Remote-first: Work from any safe location in Ukraine. Stability: VANTREXIS is an official Diia City resident. Benefits: Paid vacation, sick leaves, and corporate medical insurance. Culture: Flat structure, zero bureaucracy, and a strong engineering community. Growth: Access to Udemy and internal knowledge sharing. Hiring Process HR Screen: Intro call to discuss experience and expectations. Technical Interview: Deep dive into engineering skills and architectural thinking. Final Decision.

Full-time 8 дн. тому

Senior Full-stack Developer

SharpMinds Chernivtsi / Віддалено $4,000 - $5,000

We are looking for a Senior Full-stack Developer to join our software development team in Chernivtsi or remotely. About the client: Our client is a Dutch healthcare organization that provides care and support services to people who cannot live independently. The company has developed its own healthcare platform designed to reduce administrative workload for care workers through AI-powered features, such as report summarization, intelligent question generation, and workflow automation. The platform is already live and actively used, but the team is looking to expand development capacity to accelerate feature delivery, improve platform quality, and further develop AI-driven functionality. The platform integrates with multiple third-party healthcare systems through APIs and utilizes Azure and Amazon Bedrock services. Responsibilities: Develop and maintain an AI-powered healthcare platform Design, build, and improve backend and frontend functionality Integrate and maintain connections with third-party healthcare applications Ensure end-to-end platform quality across the entire application Participate in architectural discussions and technical decision-making Write maintainable, scalable, and well-tested code Support deployments and release processes through GitHub workflows Collaborate closely with the Product Owner and internal stakeholders Research and propose technical improvements and innovative solutions Occasionally support other technical initiatives, such as migration scripts or process automation Nice to have: 5+ years of experience with PHP and one of the modern PHP frameworks Symfony (preferred), Laravel; Experience with React or Next.js; Solid understanding of PostgreSQL; Experience working with REST APIs and third-party integrations; Understanding of software architecture and system design principles; Experience with testing and code quality practices; Strong communication skills and ability to work independently; Experience with AI-powered applications or LLM integrations Experience with Azure services Experience with Amazon Bedrock Healthcare domain experience DevOps exposure and cloud infrastructure knowledge Experience working in small product teams Curiosity and willingness to explore new technologies Upper-Intermediate level of English (candidate should have the ability to communicate with customers). We offer: Full-time position; Challenging and interesting projects from European companies; Competitive salary & bonus system; Flexible work schedule; Free English classes; Knowledge-sharing events, e.g. DevTalks; Unforgettable and interesting corporate events; Team-buildings. If you’re a proactive developer looking to work on meaningful software with a collaborative team, we’d love to hear from you! Відгукнутись на вакансію

Пакети за темою

Bagisto

bagisto/bagisto

Bagisto — це платформа для електронної комерції, побудована на Laravel. Вона надає готове рішення для створення та управління інтернет-магазинами з підтримкою каталогу товарів, замовлень, платежів та клієнтів.

27,502 v2.4.7 12 12

Lang

laravel-lang/lang

Список 126 мов для Laravel Framework, Laravel Jetstream, Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova, Laravel Spark та Laravel UI.

7,778 15.31.4 6