Last active
December 29, 2018 23:23
-
-
Save mortenson/9408724b4406adb8c0ae426f298d37b2 to your computer and use it in GitHub Desktop.
A quick and dirty way to make Drupal requests over the command line. Useful with NodeJS.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Allows Node to make command line requests without a web server. | |
* | |
* Example use with Node to POST content: | |
* const { spawnSync } = require('child_process'); | |
* const input = JSON.stringify({ path: '/some/path', content: 'request content' }); | |
* spawnSync(drush, ['php:script', 'request.php', '--script-path=some/script/path'], { input: input }); | |
*/ | |
if (php_sapi_name() !== 'cli') { | |
die; | |
} | |
$input_data = file_get_contents('php://stdin'); | |
$input = json_decode($input_data, TRUE); | |
if (!is_array($input) || empty($input['path'])) { | |
throw new \Exception('Invalid input.'); | |
} | |
$admin = \Drupal\user\Entity\User::load(1); | |
if (!$admin) { | |
throw new \Exception('User 1 does not exit.'); | |
} | |
\Drupal::service('account_switcher')->switchTo($admin); | |
if (!empty($input['content'])) { | |
$request = \Symfony\Component\HttpFoundation\Request::create($input['path'], 'POST', [], [], [], [], $input['content']); | |
} | |
else { | |
$request = \Symfony\Component\HttpFoundation\Request::create($input['path'], 'GET'); | |
} | |
$response = \Drupal::service('http_kernel')->handle($request); | |
if (!$response->isOk()) { | |
throw new \Exception("Request to {$input['path']} failed."); | |
} | |
echo json_encode($response->getContent()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment