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

Eval Command Laravel Package

wp-cli/eval-command

Adds WP-CLI commands to run arbitrary PHP code or execute PHP files from the command line. Supports running with or without loading WordPress, delaying execution until a specific hook, and passing args to scripts.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**: No additional installation required—bundled with WP-CLI (`wp --info` to verify).
2. **First Command**: Run inline PHP:
   ```bash
   wp eval 'echo "Hello, WordPress!";'
  1. First File Execution:
    wp eval-file /path/to/script.php
    

Where to Look First

  • CLI Reference: WP-CLI Handbook - Eval Command
  • Examples: Use --hook for lifecycle-aware execution (e.g., wp eval 'var_dump($wpdb)' --hook=init).
  • Debugging: Combine with wp db or wp plugin commands for context.

First Use Case

Debugging a Plugin Hook:

wp eval 'add_action("wp_loaded", function() { var_dump(current_user_can("administrator")); });' --hook=wp_loaded

Implementation Patterns

Core Workflows

  1. Inline Code Execution:

    • Use for one-liners (e.g., wp eval 'echo ABSPATH;' --skip-wordpress).
    • Pattern: Escape quotes with single quotes or JSON encoding:
      wp eval "$(jq -r '. | @sh' <<< '{"key": "value"}')"
      
  2. File-Based Scripting:

    • Store reusable logic in .php files (e.g., scripts/cleanup.php).
    • Pattern: Pass arguments via $args (accessible globally):
      wp eval-file scripts/cleanup.php --skip-wordpress arg1 arg2
      
      // scripts/cleanup.php
      global $args;
      echo "Args: " . implode(', ', $args);
      
  3. Hook-Aware Execution:

    • Test plugins/themes at specific WordPress stages:
      wp eval-file tests/plugin_hook_test.php --hook=wp_loaded
      
  4. Sandboxed Execution:

    • Use --skip-wordpress for isolated PHP (e.g., testing libraries):
      wp eval 'require_once "vendor/autoload.php"; $obj = new \Some\Library();' --skip-wordpress
      

Integration Tips

  • Laravel Compatibility:
    • Use wp eval to interact with WordPress from Laravel’s Artisan:
      php artisan tinker --execute='shell_exec("wp eval 'return get_option(\"home\");'")'
      
  • CI/CD Pipelines:
    • Automate pre-deployment checks:
      wp eval-file deploy/checks.php --hook=muplugins_loaded
      
  • IDE Shortcuts:
    • VS Code: Add a snippet for quick wp eval debugging:
      {
        "wp eval": {
          "prefix": "wpeval",
          "body": "wp eval '${1:code}' --hook=${2:wp_loaded}"
        }
      }
      

Gotchas and Tips

Pitfalls

  1. Global Scope Quirks:

    • Issue: Variables in eval are not global by default.
      wp eval '$x = 1; echo $x;'  # Fails (undefined $x)
      
    • Fix: Explicitly declare globals:
      wp eval 'global $x; $x = 1; echo $x;'
      
  2. File Paths in eval-file:

    • Issue: __FILE__/__DIR__ may resolve incorrectly in eval-file.
    • Fix: Use --use-include or preprocess paths:
      wp eval-file script.php --use-include
      
  3. Hook Timing:

    • Issue: --hook may not fire if WordPress isn’t loaded.
    • Fix: Always use --skip-wordpress with caution; test hooks with wp eval first.
  4. STDIN Limitations:

    • Issue: wp eval-file - reads from STDIN but may strip shebangs.
    • Fix: Pipe raw PHP (avoid #!/usr/bin/env php):
      cat script.php | wp eval-file -
      

Debugging Tips

  • Error Suppression:

    wp eval 'trigger_error("Test");' 2>&1 | grep -A5 "Test"
    
  • Log Output:

    wp eval 'error_log("Debug", 0);' --hook=shutdown
    

    Check wp-content/debug.log.

  • Inspect WordPress State:

    wp eval 'var_dump($GLOBALS["wp_filter"]);' --hook=all
    

Extension Points

  1. Custom Hooks:

  2. Pre/Post-Execution:

    • Use wp-cli/wp-cli-tests to mock eval in unit tests:
      $this->runCommand('eval', ['code' => 'return "test";']);
      
  3. Security:

    • Mitigation: Restrict --skip-wordpress to trusted users (e.g., via wp user permissions).
    • Audit: Log eval usage in wp-config.php:
      add_action('wp_loaded', function() {
        if (defined('WP_CLI') && WP_CLI) {
          error_log("Eval executed: " . $_SERVER['argv'][1] ?? '');
        }
      });
      

Config Quirks

  • PHP Version: Requires PHP 7.2.24+ (check with php -v).
  • WP-CLI Version: Tested with WP-CLI v2.13+ (update via wp cli update).
  • Windows Compatibility: Use --use-include for cross-platform file paths.

Pro Tips

  • Combine with wp shell:
    wp shell "eval('return get_site_option(\"siteurl\");')"
    
  • Template Scripts:
    wp eval-file --use-include <<< '<?php echo "Template: " . get_template();'
    
  • Benchmarking:
    wp eval 'echo "Time: " . microtime(true);' --hook=init
    

```markdown
## Laravel-Specific Adaptations
### Bridging WP-CLI and Laravel
1. **Artisan Integration**:
   - Create a custom Artisan command to proxy `wp eval`:
     ```php
     // app/Console/Commands/WpEval.php
     namespace App\Console\Commands;
     use Illuminate\Console\Command;
     class WpEval extends Command {
       protected $signature = 'wp:eval {code}';
       public function handle() {
         $output = shell_exec("wp eval '{$this->argument('code')}')");
         $this->info($output);
       }
     }
     ```
   - Run via:
     ```bash
     php artisan wp:eval 'echo ABSPATH;'
     ```

2. **Service Provider Hooks**:
   - Dynamically load WordPress in Laravel’s bootstrap:
     ```php
     // config/app.php
     'providers' => [
       App\Providers\WordPressServiceProvider::class,
     ],
     ```
     ```php
     // app/Providers/WordPressServiceProvider.php
     use Illuminate\Support\ServiceProvider;
     class WordPressServiceProvider extends ServiceProvider {
       public function boot() {
         if ($this->app->runningInConsole()) {
           $this->app->singleton('wp', function() {
             return shell_exec('wp eval \'return get_bloginfo();\'');
           });
         }
       }
     }
     ```

3. **Queue Workers**:
   - Offload `eval-file` to Laravel Queues:
     ```php
     // app/Console/Commands/ProcessWpQueue.php
     use Illuminate\Console\Command;
     use Illuminate\Support\Facades\Queue;
     class ProcessWpQueue extends Command {
       public function handle() {
         Queue::push(new EvalJob('wp eval-file /path/to/script.php'));
       }
     }
     ```

### Debugging Laravel + WordPress
- **Shared Storage**:
  - Use Laravel’s `storage/logs/laravel.log` and WordPress’s `debug.log` in tandem:
    ```bash
    wp eval 'error_log("Laravel Debug", 0);' --hook=shutdown
    ```
- **Xdebug**:
  - Configure `php.ini` for both stacks:
    ```ini
    xdebug.mode=debug
    xdebug.client_host=127.0.0.1
    xdebug.idekey=LARAVEL
    ```
  - Trigger via:
    ```bash
    wp eval 'xdebug_break();' --hook=init
    ```

### Performance Considerations
- **Avoid `eval` in Loops**:
  - Cache results in Laravel’s `cache()`:
    ```bash
    wp eval '
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