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() {
$this
->setName('foobar:import')
->setDescription($this->trans('Import something'))
->addArgument('file', InputArgument::REQUIRED, 'The file to import');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$this->getIo()->info('execute');
// **** 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?
__DIR__
not work? If not you'll probably have to trawl throughdebug_backtrace
to get that kind of info at runtime__DIR__
specifies where the script is in. Not the working directory of the script caller.getcwd()
wouldn't work as normal. That's why I need a Drupal-specific way to recover the originalgetcwd()
value (if it exists).$_SERVER
superglobal usually contains env vars when executing PHP from the shell.$_SERVER
does not provide any variable for a Drupal Console command to retrieve the working directory of the command runner.