Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpmnd Laravel Package

povils/phpmnd

PHPMND detects magic numbers in PHP code to improve readability and maintainability. Flags numeric literals that should be constants (0 and 1 ignored by default). Install via Composer and run vendor/bin/phpmnd locally or globally in CI and dev workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require --dev povils/phpmnd
    

    Add to composer.json under require-dev to ensure it runs only in dev environments.

  2. Basic Configuration Add to composer.json under "scripts":

    "scripts": {
        "test": [
            "@phpmnd",
            "@phpunit"
        ]
    }
    

    This ensures phpmnd runs before PHPUnit in your test suite.

  3. First Run Execute:

    composer test
    

    Review the output for detected magic numbers (e.g., hardcoded 2, 30, 0.5).


Where to Look First

  • Default Rules: Check vendor/povils/phpmnd/config/defaults.php for built-in patterns (e.g., /\b(\d+)\b/).
  • Custom Rules: Override defaults in phpmnd.json (auto-generated on first run) or create a custom config file.
  • Exclusions: Use phpmnd.json to exclude files/directories (e.g., vendor/, tests/).

First Use Case: Enforce Consistency

Run phpmnd in CI to fail builds with magic numbers, forcing developers to replace them with named constants (e.g., MAX_RETRIES = 3).


Implementation Patterns

Workflow Integration

  1. Pre-Commit Hook Add to .git/hooks/pre-commit (or use husky):

    ./vendor/bin/phpmnd
    

    Fail if magic numbers are detected.

  2. CI Pipeline Place phpmnd early in the pipeline (e.g., before linting):

    # .github/workflows/ci.yml
    - name: Check for magic numbers
      run: composer test
    
  3. IDE Integration Use PHPStorm’s "Run External Tool" to execute phpmnd on file save (via vendor/bin/phpmnd path/to/file.php).


Customization Patterns

  1. Extend Rules Override phpmnd.json to add custom patterns:

    {
        "rules": [
            {
                "pattern": "/\\b([1-9]\\d{0,2}(?:\\.\\d+)?)m\\b/",
                "message": "Hardcoded metric value found (e.g., '100m'). Use constants like `DISTANCE_KM`."
            }
        ]
    }
    
  2. Contextual Exclusions Exclude specific files or regex-matching paths:

    {
        "exclude": [
            "config/constants.php",
            "src/Helpers/.*\\.php"
        ]
    }
    
  3. Severity Levels Tag rules as error/warning in phpmnd.json to control CI behavior:

    {
        "rules": [
            {
                "pattern": "/\\b\\d+\\b/",
                "severity": "error"
            }
        ]
    }
    

Common Integration Tips

  • Pair with php-cs-fixer: Run phpmnd after php-cs-fixer to catch magic numbers introduced by auto-fixing.
  • Laravel-Specific: Exclude config/ and database/ from scans (they often contain hardcoded values intentionally).
  • Monorepos: Use --path to scope scans to specific directories (e.g., composer test -- --path=src/App).

Gotchas and Tips

Pitfalls

  1. False Positives

    • Issue: phpmnd may flag version numbers (e.g., 2.1.0) or timestamps.
    • Fix: Exclude paths or refine patterns (e.g., /\b(\d+\.\d+\.\d+)\b/ → ignore).
  2. Performance

    • Issue: Scanning large codebases (e.g., 10K+ files) can be slow.
    • Fix: Use --parallel (if supported) or exclude non-critical directories.
  3. Overzealous Rules

    • Issue: Default rules may break legacy code with intentional magic numbers (e.g., 0 as a flag).
    • Fix: Whitelist files or adjust patterns (e.g., /\b0\b(?!\s*=>)/ to exclude 0 =>).
  4. Configuration Overrides

    • Issue: Local phpmnd.json may conflict with team defaults.
    • Fix: Use --config to explicitly pass a config file:
      composer test -- --config=phpmnd.team.json
      

Debugging Tips

  1. Dry Run Use --dry-run to preview changes without failing:

    composer test -- --dry-run
    
  2. Verbose Output Enable debug mode for detailed rule matching:

    composer test -- --verbose
    
  3. Test Custom Rules Validate rules with a test file:

    echo "<?php \$x = 42;" > test_magic.php
    ./vendor/bin/phpmnd test_magic.php
    

Extension Points

  1. Custom Exit Codes Override exit codes in a script wrapper (e.g., phpmnd.sh):

    #!/bin/bash
    ./vendor/bin/phpmnd || exit 1
    
  2. Plugin System Extend via Povils\Phpmnd\Rule\RuleInterface to create reusable rule sets (e.g., Laravel-specific constants).

  3. GitHub Action Use the povils/phpmnd-action for GitHub Actions:

    - uses: povils/phpmnd-action@v1
      with:
        config: phpmnd.json
    

Laravel-Specific Quirks

  1. Config Files Exclude config/ unless you’re enforcing magic numbers in config values (rare):

    {
        "exclude": ["config/"]
    }
    
  2. Migrations Exclude database/migrations/ if using timestamps or IDs as magic numbers:

    {
        "exclude": ["database/migrations/"]
    }
    
  3. Service Providers Watch for hardcoded array keys (e.g., ['status' => 1]). Replace with constants:

    // Before
    $user->status = 1;
    
    // After
    $user->status = User::STATUS_ACTIVE;
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky