inline_image_saver-1.0.x-dev/tests/src/Traits/SetupBaseUrlTrait.php
tests/src/Traits/SetupBaseUrlTrait.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\inline_image_saver\Traits;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
/**
* Provides base URL setup for Kernel tests with SIMPLETEST_BASE_URL support.
*
* KernelTestBase creates a basic request context but without
* SIMPLETEST_BASE_URL configuration.
* This trait reinitializes the request with proper base URL setup.
*
* @see \Drupal\Core\Test\FunctionalTestSetupTrait::setupBaseUrl()
* @see \Drupal\Core\Test\FunctionalTestSetupTrait::prepareEnvironment()
*/
trait SetupBaseUrlTrait {
/**
* Reinitializes request with SIMPLETEST_BASE_URL configuration.
*
* Updates the existing request stack created by KernelTestBase with proper
* base URL setup from SIMPLETEST_BASE_URL environment variable.
*
* @throws \Exception
* Thrown when no SIMPLETEST_BASE_URL environment variable is provided or
* uses an invalid scheme.
*/
protected function setupBaseUrl(): void {
global $base_url;
// Get and set the domain of the environment we are running our test
// coverage against.
if (!$base_url = getenv('SIMPLETEST_BASE_URL')) {
throw new \Exception('You must provide a SIMPLETEST_BASE_URL environment variable to run this test.');
}
// Setup $_SERVER variable.
$parsed_url = parse_url($base_url);
$host = $parsed_url['host'] . (isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '');
$path = isset($parsed_url['path']) ? rtrim(rtrim($parsed_url['path']), '/') : '';
$port = $parsed_url['port'] ?? 80;
$valid_url_schemes = ['http', 'https'];
if (!in_array(strtolower($parsed_url['scheme']), $valid_url_schemes, TRUE)) {
throw new \Exception('You must provide valid scheme for the SIMPLETEST_BASE_URL environment variable. Valid schema are: http, https.');
}
// If the passed URL schema is 'https' then setup the $_SERVER variables
// properly so that testing will run under HTTPS.
if ($parsed_url['scheme'] === 'https') {
$_SERVER['HTTPS'] = 'on';
}
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_ADDR'] = '127.0.0.1';
$_SERVER['SERVER_PORT'] = $port;
$_SERVER['SERVER_SOFTWARE'] = NULL;
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['REQUEST_URI'] = $path . '/';
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['SCRIPT_NAME'] = $path . '/index.php';
$_SERVER['SCRIPT_FILENAME'] = $path . '/index.php';
$_SERVER['PHP_SELF'] = $path . '/index.php';
$_SERVER['HTTP_USER_AGENT'] = 'Drupal command line';
$request = Request::createFromGlobals();
$request->setSession(new Session(new MockArraySessionStorage()));
$request_stack = $this->container->get('request_stack');
$request_stack->pop();
$request_stack->push($request);
$this->container->get('router.request_context')->fromRequest($request);
}
}
