TestSiteUserLoginCommand.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Drupal\TestSite\Commands;
  3. use Drupal\Core\DrupalKernel;
  4. use Drupal\Core\Site\Settings;
  5. use Symfony\Component\Console\Command\Command;
  6. use Symfony\Component\Console\Exception\InvalidArgumentException;
  7. use Symfony\Component\Console\Input\InputArgument;
  8. use Symfony\Component\Console\Input\InputInterface;
  9. use Symfony\Component\Console\Input\InputOption;
  10. use Symfony\Component\Console\Output\OutputInterface;
  11. use Symfony\Component\HttpFoundation\Request;
  12. /**
  13. * Command to generate a login link for the test site.
  14. *
  15. * @internal
  16. */
  17. class TestSiteUserLoginCommand extends Command {
  18. /**
  19. * The class loader to use for installation and initialization of setup.
  20. *
  21. * @var \Symfony\Component\Classloader\Classloader
  22. */
  23. protected $classLoader;
  24. /**
  25. * {@inheritdoc}
  26. */
  27. protected function configure() {
  28. $this->setName('user-login')
  29. ->setDescription('Generate a one time login link for an user.')
  30. ->addArgument('uid', InputArgument::REQUIRED, 'The ID of the user for whom the link will be generated')
  31. ->addOption('site-path', NULL, InputOption::VALUE_REQUIRED, 'The path for the test site.');
  32. }
  33. /**
  34. * {@inheritdoc}
  35. *
  36. * @throws \Symfony\Component\Console\Exception\InvalidArgumentException
  37. */
  38. protected function execute(InputInterface $input, OutputInterface $output) {
  39. $root = dirname(dirname(dirname(dirname(dirname(__DIR__)))));
  40. chdir($root);
  41. $this->classLoader = require 'autoload.php';
  42. $kernel = new DrupalKernel('prod', $this->classLoader, FALSE);
  43. $kernel::bootEnvironment();
  44. $kernel->setSitePath($input->getOption('site-path'));
  45. Settings::initialize($kernel->getAppRoot(), $kernel->getSitePath(), $this->classLoader);
  46. $request = Request::createFromGlobals();
  47. $kernel->boot();
  48. $kernel->preHandle($request);
  49. $container = $kernel->getContainer();
  50. $uid = $input->getArgument('uid');
  51. if (!is_numeric($uid)) {
  52. throw new InvalidArgumentException(sprintf('The "uid" argument needs to be an integer, but it is "%s".', $uid));
  53. }
  54. $userEntity = $container->get('entity_type.manager')
  55. ->getStorage('user')
  56. ->load($uid);
  57. $url = user_pass_reset_url($userEntity) . '/login';
  58. $output->writeln($url);
  59. return 0;
  60. }
  61. }