In a standard Drupal 8 environment, the current working directory is override and becomes the document root of the site. This is a bit troublesome for Drupal Console command implementations that wants to know where the command is running (e.g. import command need that to resolve the given relative path of the target file).

For example:

namespace Drupal\foobar\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Core\Command\ContainerAwareCommand;

 * Class ImportCommand.
 * Drupal\Console\Annotations\DrupalCommand (
 *     extension="foobar",
 *     extensionType="module"
 * )
class ImportCommand extends ContainerAwareCommand {

   * {@inheritdoc}
  protected function configure() {
      ->setDescription($this->trans('Import something'))
      ->addArgument('file', InputArgument::REQUIRED, 'The file to import');

   * {@inheritdoc}
  protected function execute(InputInterface $input, OutputInterface $output) {

    // **** here ****
    $file = $input->getArgument('file');

    // ...
    // ...


Now, consider a user running this command:

drupal --root=/var/www/html foobar:import ./foobar.json

You can virtually run this command anywhere in your system.

The relative path provided to argument $file (i.e. ./foobar.json) is expected to be resolved relative to the runner's current working directory. Normal PHP script can get the information from getcwd(). But in a Drupal Console environment, the function getcwd() returns the document root of the site.

The normal function getcwd() obviously don't work. Is there a way?

  • I doubt Drupal would have anything specific, do standard PHP solutions like __DIR__ not work? If not you'll probably have to trawl through debug_backtrace to get that kind of info at runtime – Clive Jun 15 '20 at 14:39
  • The constant __DIR__ specifies where the script is in. Not the working directory of the script caller. – Koala Yeung Jun 16 '20 at 2:44
  • The Drupal environment overrides the standard working directory variables so getcwd() wouldn't work as normal. That's why I need a Drupal-specific way to recover the original getcwd() value (if it exists). – Koala Yeung Jun 16 '20 at 2:46
  • The $_SERVER superglobal usually contains env vars when executing PHP from the shell. – Shawn Conn Jun 16 '20 at 2:48
  • I've checked. The superglobal $_SERVER does not provide any variable for a Drupal Console command to retrieve the working directory of the command runner. – Koala Yeung Jun 16 '20 at 2:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.