GithubHelp home page GithubHelp logo

wp-cli / eval-command Goto Github PK

View Code? Open in Web Editor NEW
8.0 9.0 15.0 8.23 MB

Executes arbitrary PHP code or files.

License: MIT License

PHP 38.61% Gherkin 61.39%
wp-cli wp-cli-package wordpress cli eval hacktoberfest

eval-command's Introduction

wp-cli/eval-command

Executes arbitrary PHP code or files.

Testing

Quick links: Using | Installing | Contributing | Support

Using

This package implements the following commands:

wp eval

Executes arbitrary PHP code.

wp eval <php-code> [--skip-wordpress]

Note: because code is executed within a method, global variables need to be explicitly globalized.

OPTIONS

<php-code>
	The code to execute, as a string.

[--skip-wordpress]
	Execute code without loading WordPress.

EXAMPLES

# Display WordPress content directory.
$ wp eval 'echo WP_CONTENT_DIR;'
/var/www/wordpress/wp-content

# Generate a random number.
$ wp eval 'echo rand();' --skip-wordpress
479620423

wp eval-file

Loads and executes a PHP file.

wp eval-file <file> [<arg>...] [--skip-wordpress] [--use-include]

Note: because code is executed within a method, global variables need to be explicitly globalized.

OPTIONS

<file>
	The path to the PHP file to execute.  Use '-' to run code from STDIN.

[<arg>...]
	One or more positional arguments to pass to the file. They are placed in the $args variable.

[--skip-wordpress]
	Load and execute file without loading WordPress.

[--use-include]
	Process the provided file via include instead of evaluating its contents.

Installing

This package is included with WP-CLI itself, no additional installation necessary.

To install the latest version of this package over what's included in WP-CLI, run:

wp package install [email protected]:wp-cli/eval-command.git

Contributing

We appreciate you taking the initiative to contribute to this project.

Contributing isn’t limited to just code. We encourage you to contribute in the way that best fits your abilities, by writing tutorials, giving a demo at your local meetup, helping other users with their support questions, or revising our documentation.

For a more thorough introduction, check out WP-CLI's guide to contributing. This package follows those policy and guidelines.

Reporting a bug

Think you’ve found a bug? We’d love for you to help us get it fixed.

Before you create a new issue, you should search existing issues to see if there’s an existing resolution to it, or if it’s already been fixed in a newer version.

Once you’ve done a bit of searching and discovered there isn’t an open or fixed issue for your bug, please create a new issue. Include as much detail as you can, and clear steps to reproduce if possible. For more guidance, review our bug report documentation.

Creating a pull request

Want to contribute a new feature? Please first open a new issue to discuss whether the feature is a good fit for the project.

Once you've decided to commit the time to seeing your pull request through, please follow our guidelines for creating a pull request to make sure it's a pleasant experience. See "Setting up" for details specific to working on this package locally.

Support

GitHub issues aren't for general support questions, but there are other venues you can try: https://wp-cli.org/#support

This README.md is generated dynamically from the project's codebase using wp scaffold package-readme (doc). To suggest changes, please submit a pull request against the corresponding part of the codebase.

eval-command's People

Contributors

aaemnnosttv avatar clemens-tolboom avatar conatus avatar danielbachhuber avatar ernilambar avatar francescolaffi avatar gilbitron avatar github-actions[bot] avatar gitlost avatar hideokamoto avatar janw-me avatar japh avatar jmslbam avatar johnbillion avatar jrfnl avatar lkwdwrd avatar miya0001 avatar mpeshev avatar mweimerskirch avatar mwilliamson avatar natewr avatar nyordanov avatar pjeby avatar schlessera avatar scribu avatar swissspidy avatar szepeviktor avatar wesm87 avatar wojsmol avatar yivi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eval-command's Issues

Fatal error when calling PHP-FFMpeg

Bug Report

Describe the current, buggy behavior

I am using the PHP-FFMpeg package, installed via composer. When I call the function that uses it with wp eval, the execution stops with error:

Fatal error: Uncaught TypeError: Argument 1 passed to Symfony\Component\Process\Process::__construct() must be of the type array, null given, called in phar:///usr/local/bin/wp/vendor/symfony/process/ProcessBuilder.php on line 275 and defined in wp-content/plugins/generate-hls/vendor/symfony/process/Process.php:140
Stack trace:
#0 phar:///usr/local/bin/wp/vendor/symfony/process/ProcessBuilder.php(275): Symfony\Component\Process\Process->__construct()
#1 wp-content/plugins/generate-hls/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/ProcessBuilderFactory.php(172): Symfony\Component\Process\ProcessBuilder->getProcess()
#2 wp-content/plugins/generate-hls/vendor/alchemy/binary-driver/src/Alchemy/BinaryDriver/AbstractBinary.php(136): Alchemy\BinaryDriver\ProcessBuilderFactory->create()
#3 wp-c in wp-content/plugins/generate-hls/vendor/symfony/process/Process.php on line 140

If I launch it from web interface, it works without problems.

Describe how other contributors can replicate this bug

  • install PHP-FFMpeg: composer require php-ffmpeg/php-ffmpeg
  • create a simple function to use PHP-FFMpeg for example:
function test_ffmpeg() {
	$args = array(
	  'post_type'      => 'attachment',
	  'post_mime_type' => 'video',
	  'posts_per_page' => -1,
	  'post_status'    => 'inherit',
	  'suppress_filters' => true
	);

	require_once(__DIR__ . '/vendor/autoload.php');

	$attachements = new WP_Query($args);
	foreach($attachements->posts as $attachment) {
	  $source_file = get_attached_file( $attachment->ID);
    	if(!file_exists($source_file)) return false;
    	$ffprobe = FFMpeg\FFProbe::create();
    	$metadata = $ffprobe->streams($source_file);
    	var_dump($metadata->audios()->count());
	}
}
  • call this function via wp cli eval "test_ffmpeg();"

Describe what you would expect as the correct outcome

Get the correct information from ffmpeg.

Let us know what environment you are running this on

OS:     Linux 3.10.0-1127.10.1.el7.x86_64 #1 SMP Wed Jun 3 14:28:03 UTC 2020 x86_64Shell:  /bin/bash
PHP binary:     /usr/bin/phpPHP version:    7.4.5
php.ini used:   /etc/php.ini
WP-CLI root dir:        phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir:      phar://wp-cli.phar/vendor
WP_CLI phar path:       /home/generate/web/generate.staging.effata.it/public_html/wp-content/plugins/generate-hls
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.4.0

Add --use-include flag in order to overcome eval() limitations

Feature Request

Describe your use case and the problem you are facing

eval-file uses eval() to execute code in provided script. Unfortunately, this has some limitations:

  • declare(strict_types=1) in the script file throws a fatal error in eval()
  • evale'd code cannot be debugged using XDebug.

Describe the solution you'd like

I propose to add --use-require flag to eval-file to indicate that the script should be executed using require().

If the proposal is accepted I'm willing to implement it.

eval-file seems to require `global $wpdb;` for some reason

Take this example file:

<?php

echo $wpdb;

This causes the following error:

$ wp --debug eval-file example.php
# ...
PHP Notice:  Undefined variable: wpdb in example.php on line 3
PHP Stack trace:
PHP   1. {main}() /usr/local/Cellar/wp-cli/1.3.0/php/boot-fs.php:0
PHP   2. include_once() /usr/local/Cellar/wp-cli/1.3.0/php/boot-fs.php:17
PHP   3. WP_CLI\bootstrap() /usr/local/Cellar/wp-cli/1.3.0/php/wp-cli.php:23
PHP   4. WP_CLI\Bootstrap\LaunchRunner->process() /usr/local/Cellar/wp-cli/1.3.0/php/bootstrap.php:75
PHP   5. WP_CLI\Runner->start() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Bootstrap/LaunchRunner.php:23
PHP   6. WP_CLI\Runner->do_early_invoke() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Runner.php:923
PHP   7. WP_CLI\Runner->_run_command() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Runner.php:63
PHP   8. WP_CLI\Runner->run_command() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Runner.php:330
PHP   9. WP_CLI\Dispatcher\Subcommand->invoke() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Runner.php:323
PHP  10. call_user_func:{/usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/Subcommand.php:401}() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/Subcommand.php:401
PHP  11. WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher\{closure}() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/Subcommand.php:401
PHP  12. call_user_func:{/usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/CommandFactory.php:81}() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/CommandFactory.php:81
PHP  13. EvalFile_Command->__invoke() /usr/local/Cellar/wp-cli/1.3.0/php/WP_CLI/Dispatcher/CommandFactory.php:81
PHP  14. EvalFile_Command::_eval() /usr/local/Cellar/wp-cli/1.3.0/vendor/wp-cli/eval-command/src/EvalFile_Command.php:36
PHP  15. include() /usr/local/Cellar/wp-cli/1.3.0/vendor/wp-cli/eval-command/src/EvalFile_Command.php:40

However, if I change the example file so that it looks like this:

<?php

global $wpdb;
var_export( $wpdb );

Then I get the expected output:

$ wp --debug eval-file example.php
# ...
wpdb::__set_state(array(
   'show_errors' => true,
   'suppress_errors' => false,
   'last_error' => '',
   'num_queries' => 8,
   'num_rows' => 0,
   'rows_affected' => 1,
   'insert_id' => 0,
# ...

My question is: why is the line global $wpdb; required here? Since the code is not within a function, shouldn't the global be accessible directly without requiring the line global $wpdb;?

Eval she-bang handling breaks `__FILE__` constant

The PR in #35 added she-bang handling to eval-file so that you can have cheap "binaries" that are based on WP-CLI.

In doing so, it turned an include into an eval(). This in turn breaks how __FILE__ resolves: https://www.php.net/manual/en/function.eval.php#87296

We already hit that issue in a test for the wp-dli/doctor-command: https://travis-ci.org/wp-cli/doctor-command/jobs/516451087#L670

A possible solution would be to manually parse the $file_contents and replace __FILE__ with the value of $file.

Note: __DIR__ is likely affected too and needs to be checked as well.

Error using Requests library w/ eval-file

I was using eval-file to write some quick-and-dirty tests of a client wrapper around some API calls using Requests. However, I struggled for a while because every time I ran it, I got this Exception raised:

[02-Aug-2017 02:26:28 UTC] PHP Fatal error:  Uncaught Requests_Exception: cURL error 77: error setting certificate verify locations:
  CAfile: phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests/Transport/cacert.pem
  CApath: /etc/ssl/certs in phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests/Transport/cURL.php:422
Stack trace:
#0 phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests/Transport/cURL.php(177): Requests_Transport_cURL->process_response('', Array)
#1 phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests.php(379): Requests_Transport_cURL->request('https://api.git...', Array, Array, Array)
#2 phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests.php(706): Requests::request('https://api.git...', Array, Array, 'GET', Array)
#3 phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests.php(383): Requests::parse_response(Array, 'http://api.gith...', Array, Array, Array)
#4 phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests/Session.php(205): Requests::request('http://api.gith...', Array, Array, 'GET', Array)
 in phar:///usr/bin/wp/vendor/rmccue/requests/library/Requests/Transport/cURL.php on line 422

It cannot find a certificate required for making the SSL'd HTTP requests, but I didn't have this problem making requests from within WordPress (I stuck the same code on a dummy page and loaded it up and it ran fine). After some digging, I found in WordPress itself this line:

Requests::set_certificate_path( ABSPATH . WPINC . '/certificates/ca-bundle.crt' );

which sets the location of WP's certificate path. I'm not sure why this wasn't set correctly when running from WP-CLI, but adding that to the top of my script resolved the issue.

I haven't dug deeper into what's going on yet, but Requests is bundled w/ WP-CLI and appears to be loading that version before the WP version, so I suspect it's related to that. I also don't know if this is just a problem with eval-file or if other commands could have this problem.

I am running the latest version:

WP-CLI 1.2.1

PHP Parse error / unexpected end of file

I just tried to use wp-cli to eval a pretty simple script and I keep running into the same error:

PHP Parse error:  syntax error, unexpected end of file in phar:///var/www/sites/test/wp-cli.phar/vendor/wp-cli/eval-command/src/Eval_Command.php(37) : eval()'d code on line 1
Parse error: syntax error, unexpected end of file in phar:///var/www/sites/test/wp-cli.phar/vendor/wp-cli/eval-command/src/Eval_Command.php(37) : eval()'d code on line 1

This happens no matter what I put into the script, so I figure the problem isn't my script? The smallest test case I have is:

<?php
global $wpdb;
var_dump($wpdb);

which I call through:

php wp-cli.phar eval test.php

--info gives me:

PHP binary:	/usr/bin/php7.1
PHP version:	7.1.11-1+ubuntu17.04.1+deb.sury.org+1
php.ini used:	/etc/php/7.1/cli/php.ini
WP-CLI root dir:	phar://wp-cli.phar
WP-CLI vendor dir:	phar://wp-cli.phar/vendor
WP_CLI phar path:	/var/www/sites/test
WP-CLI packages dir:	
WP-CLI global config:	
WP-CLI project config:	
WP-CLI version:	1.4.1

I'll happily try to write a test/fix if someone points me into the right direction but at the moment I'm a bit lost.

`wp eval-file` and the `--use-include` parameter

The README file says this package is included in WP-CLI.

That is true but I haven't been able to use the --use-include parameter of eval-file without explicitely installing the package manually. I just tried on a fresh install of WP CLI 2.7.1.

Am I missing something? Do I really have to install it manually each time?

cli eval-file not read hooks...

Hi,
i did it :docker-compose run --rm cli eval-file /var/www/html/wp-content/themes/twentytwentyone-child/acf_fields.php
to import ACF filed into my site.
it on hook:add_action( 'init',
but it not work

Maybe I need to activate HOOK in a different way?

Move command over to new v2 structure

The following changes need to be made to move the command over to the v2 structure:

  • Make sure the correct framework is required:
    composer require wp-cli/wp-cli:^2
    
  • Require the testing framework as a dev dependency:
    composer require --dev wp-cli/wp-cli-tests:^0
    
  • Use the .travis.yml file from wp-cli/wp-cli:
    wget https://raw.githubusercontent.com/wp-cli/wp-cli/master/.travis.yml
    
  • Add the default script configuration to Composer file:
      "scripts": {
          "lint": "run-linter-tests",
          "phpcs": "run-phpcs-tests",
          "phpunit": "run-php-unit-tests",
          "behat": "run-behat-tests",
          "prepare-tests": "install-package-tests",
          "test": [
              "@lint",
              "@phpcs",
              "@phpunit",
              "@behat"
          ]
      },
    
  • Remove scaffolded binary files:
    git rm bin/install-package-tests.sh
    git rm bin/test.sh
    
  • Remove scaffolded Behat setup:
    git rm features/bootstrap/*
    git rm features/extra/*
    git rm features/steps/*
    
  • Remove scaffolded Behat tags util script:
    git rm utils/behat-tags.php
    
  • Add command packages that are needed for Behat tests as --dev dependencies.
    The following commands are already available, anything else needs to be explicitly required:
    • cli *
    • config *
    • core *
    • eval
    • eval-file
    • help
  • Update all dependencies:
    composer update
    
  • Optional - Add PHPCS rule set to enable CS & compatibility sniffing:
    wget https://raw.githubusercontent.com/wp-cli/wp-cli/master/phpcs.xml.dist
    
  • Run and adapt tests to make sure they all pass:
    composer test
    

Allow input from stdin

It's not possible to pipe a string of PHP directly into wp eval. This doesn't work:

echo 'echo phpversion();' | wp eval

You need to use xargs which means working with quote marks is difficult.

echo 'echo phpversion();' | xargs -I {}  wp eval {}

It would be great if wp eval accepted input from stdin.

Automatically rerun failed scenarios

The following changes need to be made:

  1. In the .travis.yml file, the - composer behat line in the script: section needs to be changed into the following:
- composer behat || composer behat-rerun
  1. In the composer-json file, the requirement on wp-cli/wp-cli-tests needs to be adapted to require at least v2.0.7:
"wp-cli/wp-cli-tests": "^2.0.7"
  1. In the composer-json file, the "scripts" section needs to be extended. Immediately after the line "behat": "run-behat-tests",, the following line needs to be inserted:
"behat-rerun": "rerun-behat-tests",

Here's an example of how this should look like:

Adopt and enforce new `WP_CLI_CS` standard

We have a new PHPCS standard for WP-CLI called WPCliCS (props @jrfnl). It is part of the wp-cli/wp-cli-tests package starting with version v2.1.0.

To adopt & enforce this new standard, the following actions need to be taken for this repository:

  • Create a PR that adds a custom ruleset phpcs.xml.dist to the repository

    • Add phpcs.xml.dist file
    • Adapt .distignore to ignore phpcs.xml.dist & phpunit.xml.dist
    • Adapt .gitignore to ignore phpunit.xml, phpcs.xml & .phpcs.xml
    • Require version ^2.1 of the wp-cli/wp-cli-tests as a dev dependency
  • Make any required changes to the code that fail the checks from the above ruleset in separate PRs

  • Merge thre ruleset once all required changes have been processed and merged

A sample PR for a simple repository can be seen here: https://github.com/wp-cli/maintenance-mode-command/pull/3/files

Related wp-cli/wp-cli#5179

eval-file with '--url' doesn't set the current blog ID

Summary

When using wp eval-file script.php --url=http://example.com/sub-site

I would expect the current blog ID (and subsequent globals like $wpdb->posts) to be set to the sub-site as set in --url, but this isn't the case.

Tested on wp-cli 1.5.1


Steps to reproduce:

  1. Create script.php with the following:
<?php
global $wpdb;

var_dump( get_current_blog_id() );
var_dump( $wpdb->posts );
  1. Create a multisite install and create a sub-site. For this example, the sub-site is located at http://example.com/sub-site

  2. Run the command wp eval-file script.php --url=http://example.com/sub-site

  3. Output in the cli is:

int(1)
string(8) "wp_posts"
  1. Expected output is:
int(2)
string(10) "wp_2_posts"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.