class SystemTestController

Same name in other branches
  1. 9 core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php \Drupal\system_test\Controller\SystemTestController
  2. 10 core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php \Drupal\system_test\Controller\SystemTestController
  3. 11.x core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php \Drupal\system_test\Controller\SystemTestController

Controller routines for system_test routes.

Hierarchy

Expanded class hierarchy of SystemTestController

File

core/modules/system/tests/modules/system_test/src/Controller/SystemTestController.php, line 23

Namespace

Drupal\system_test\Controller
View source
class SystemTestController extends ControllerBase implements TrustedCallbackInterface {
    
    /**
     * The lock service.
     *
     * @var \Drupal\Core\Lock\LockBackendInterface
     */
    protected $lock;
    
    /**
     * The persistent lock service.
     *
     * @var \Drupal\Core\Lock\LockBackendInterface
     */
    protected $persistentLock;
    
    /**
     * The current user.
     *
     * @var \Drupal\Core\Session\AccountInterface
     */
    protected $currentUser;
    
    /**
     * The renderer.
     *
     * @var \Drupal\Core\Render\RendererInterface
     */
    protected $renderer;
    
    /**
     * The messenger service.
     *
     * @var \Drupal\Core\Messenger\MessengerInterface
     */
    protected $messenger;
    
    /**
     * Constructs the SystemTestController.
     *
     * @param \Drupal\Core\Lock\LockBackendInterface $lock
     *   The lock service.
     * @param \Drupal\Core\Lock\LockBackendInterface $persistent_lock
     *   The persistent lock service.
     * @param \Drupal\Core\Session\AccountInterface $current_user
     *   The current user.
     * @param \Drupal\Core\Render\RendererInterface $renderer
     *   The renderer.
     * @param \Drupal\Core\Messenger\MessengerInterface $messenger
     *   The messenger service.
     */
    public function __construct(LockBackendInterface $lock, LockBackendInterface $persistent_lock, AccountInterface $current_user, RendererInterface $renderer, MessengerInterface $messenger) {
        $this->lock = $lock;
        $this->persistentLock = $persistent_lock;
        $this->currentUser = $current_user;
        $this->renderer = $renderer;
        $this->messenger = $messenger;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('lock'), $container->get('lock.persistent'), $container->get('current_user'), $container->get('renderer'), $container->get('messenger'));
    }
    
    /**
     * Tests main content fallback.
     *
     * @return string
     *   The text to display.
     */
    public function mainContentFallback() {
        return [
            '#markup' => $this->t('Content to test main content fallback'),
        ];
    }
    
    /**
     * Tests setting messages and removing one before it is displayed.
     *
     * @return string
     *   Empty string, we just test the setting of messages.
     */
    public function messengerServiceTest() {
        // Set two messages.
        $this->messenger
            ->addStatus('First message (removed).');
        $this->messenger
            ->addStatus($this->t('Second message with <em>markup!</em> (not removed).'));
        $messages = $this->messenger
            ->deleteByType('status');
        // Remove the first.
        unset($messages[0]);
        foreach ($messages as $message) {
            $this->messenger
                ->addStatus($message);
        }
        // Duplicate message check.
        $this->messenger
            ->addStatus('Non Duplicated message');
        $this->messenger
            ->addStatus('Non Duplicated message');
        $this->messenger
            ->addStatus('Duplicated message', TRUE);
        $this->messenger
            ->addStatus('Duplicated message', TRUE);
        // Add a Markup message.
        $this->messenger
            ->addStatus(Markup::create('Markup with <em>markup!</em>'));
        // Test duplicate Markup messages.
        $this->messenger
            ->addStatus(Markup::create('Markup with <em>markup!</em>'));
        // Ensure that multiple Markup messages work.
        $this->messenger
            ->addStatus(Markup::create('Markup2 with <em>markup!</em>'));
        // Test mixing of types.
        $this->messenger
            ->addStatus(Markup::create('Non duplicate Markup / string.'));
        $this->messenger
            ->addStatus('Non duplicate Markup / string.');
        $this->messenger
            ->addStatus(Markup::create('Duplicate Markup / string.'), TRUE);
        $this->messenger
            ->addStatus('Duplicate Markup / string.', TRUE);
        // Test auto-escape of non safe strings.
        $this->messenger
            ->addStatus('<em>This<span>markup will be</span> escaped</em>.');
        return [];
    }
    
    /**
     * Controller to return $_GET['destination'] for testing.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The request.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *   The response.
     */
    public function getDestination(Request $request) {
        $response = new Response($request->query
            ->get('destination'));
        return $response;
    }
    
    /**
     * Controller to return $_REQUEST['destination'] for testing.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The request.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *   The response.
     */
    public function requestDestination(Request $request) {
        $response = new Response($request->request
            ->get('destination'));
        return $response;
    }
    
    /**
     * Try to acquire a named lock and report the outcome.
     */
    public function lockAcquire() {
        if ($this->lock
            ->acquire('system_test_lock_acquire')) {
            $this->lock
                ->release('system_test_lock_acquire');
            return [
                '#markup' => 'TRUE: Lock successfully acquired in \\Drupal\\system_test\\Controller\\SystemTestController::lockAcquire()',
            ];
        }
        else {
            return [
                '#markup' => 'FALSE: Lock not acquired in \\Drupal\\system_test\\Controller\\SystemTestController::lockAcquire()',
            ];
        }
    }
    
    /**
     * Try to acquire a specific lock, and then exit.
     */
    public function lockExit() {
        if ($this->lock
            ->acquire('system_test_lock_exit', 900)) {
            echo 'TRUE: Lock successfully acquired in \\Drupal\\system_test\\Controller\\SystemTestController::lockExit()';
            // The shut-down function should release the lock.
            exit;
        }
        else {
            return [
                '#markup' => 'FALSE: Lock not acquired in system_test_lock_exit()',
            ];
        }
    }
    
    /**
     * Creates a lock that will persist across requests.
     *
     * @param string $lock_name
     *   The name of the persistent lock to acquire.
     *
     * @return string
     *   The text to display.
     */
    public function lockPersist($lock_name) {
        if ($this->persistentLock
            ->acquire($lock_name)) {
            return [
                '#markup' => 'TRUE: Lock successfully acquired in SystemTestController::lockPersist()',
            ];
        }
        else {
            return [
                '#markup' => 'FALSE: Lock not acquired in SystemTestController::lockPersist()',
            ];
        }
    }
    
    /**
     * Set cache tag on on the returned render array.
     */
    public function system_test_cache_tags_page() {
        $build['main'] = [
            '#cache' => [
                'tags' => [
                    'system_test_cache_tags_page',
                ],
            ],
            '#pre_render' => [
                '\\Drupal\\system_test\\Controller\\SystemTestController::preRenderCacheTags',
            ],
            'message' => [
                '#markup' => 'Cache tags page example',
            ],
        ];
        return $build;
    }
    
    /**
     * Set cache max-age on the returned render array.
     */
    public function system_test_cache_maxage_page() {
        $build['main'] = [
            '#cache' => [
                'max-age' => 90,
            ],
            'message' => [
                '#markup' => 'Cache max-age page example',
            ],
        ];
        return $build;
    }
    
    /**
     * Sets a cache tag on an element to help test #pre_render and cache tags.
     */
    public static function preRenderCacheTags($elements) {
        $elements['#cache']['tags'][] = 'pre_render';
        return $elements;
    }
    
    /**
     * Initialize authorize.php during testing.
     *
     * @see system_authorized_init()
     */
    public function authorizeInit($page_title) {
        $authorize_url = Url::fromUri('base:core/authorize.php', [
            'absolute' => TRUE,
        ])->toString();
        system_authorized_init('system_test_authorize_run', __DIR__ . '/../../system_test.module', [], $page_title);
        return new RedirectResponse($authorize_url);
    }
    
    /**
     * Sets a header.
     */
    public function setHeader(Request $request) {
        $query = $request->query
            ->all();
        $response = new CacheableResponse();
        $response->headers
            ->set($query['name'], $query['value']);
        $response->getCacheableMetadata()
            ->addCacheContexts([
            'url.query_args:name',
            'url.query_args:value',
        ]);
        $response->setContent($this->t('The following header was set: %name: %value', [
            '%name' => $query['name'],
            '%value' => $query['value'],
        ]));
        return $response;
    }
    
    /**
     * A simple page callback that uses a plain Symfony response object.
     */
    public function respondWithResponse(Request $request) {
        return new Response('test');
    }
    
    /**
     * A plain Symfony response with Cache-Control: public, max-age=60.
     */
    public function respondWithPublicResponse() {
        return (new Response('test'))->setPublic()
            ->setMaxAge(60);
    }
    
    /**
     * A simple page callback that uses a CacheableResponse object.
     */
    public function respondWithCacheableResponse(Request $request) {
        return new CacheableResponse('test');
    }
    
    /**
     * A simple page callback which adds a register shutdown function.
     */
    public function shutdownFunctions($arg1, $arg2) {
        drupal_register_shutdown_function('_system_test_first_shutdown_function', $arg1, $arg2);
        // If using PHP-FPM then fastcgi_finish_request() will have been fired
        // preventing further output to the browser which means that the escaping of
        // the exception message can not be tested.
        // @see _drupal_shutdown_function()
        // @see \Drupal\system\Tests\System\ShutdownFunctionsTest
        if (function_exists('fastcgi_finish_request')) {
            return [
                '#markup' => 'The function fastcgi_finish_request exists when serving the request.',
            ];
        }
        return [];
    }
    
    /**
     * Returns the title for system_test.info.yml's configure route.
     *
     * @param string $foo
     *   Any string for the {foo} slug.
     *
     * @return string
     */
    public function configureTitle($foo) {
        return 'Bar.' . $foo;
    }
    
    /**
     * Simple argument echo.
     *
     * @param string $text
     *   Any string for the {text} slug.
     *
     * @return array
     *   A render array.
     */
    public function simpleEcho($text) {
        return [
            '#plain_text' => $text,
        ];
    }
    
    /**
     * Shows permission-dependent content.
     *
     * @return array
     *   A render array.
     */
    public function permissionDependentContent() {
        $build = [];
        // The content depends on the access result.
        $access = AccessResult::allowedIfHasPermission($this->currentUser, 'pet llamas');
        $this->renderer
            ->addCacheableDependency($build, $access);
        // Build the content.
        if ($access->isAllowed()) {
            $build['allowed'] = [
                '#markup' => 'Permission to pet llamas: yes!',
            ];
        }
        else {
            $build['forbidden'] = [
                '#markup' => 'Permission to pet llamas: no!',
            ];
        }
        return $build;
    }
    
    /**
     * Returns the current date.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *   A Response object containing the current date.
     */
    public function getCurrentDate() {
        // Uses specific time to test that the right timezone is used.
        $response = new Response(\Drupal::service('date.formatter')->format(1452702549));
        return $response;
    }
    
    /**
     * Returns a response with a test header set from the request.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *   A Response object containing the test header.
     */
    public function getTestHeader(Request $request) {
        $response = new Response();
        $response->headers
            ->set('Test-Header', $request->headers
            ->get('Test-Header'));
        return $response;
    }
    
    /**
     * Returns a cacheable response with a custom cache control.
     */
    public function getCacheableResponseWithCustomCacheControl() {
        return new CacheableResponse('Foo', 200, [
            'Cache-Control' => 'bar',
        ]);
    }
    
    /**
     * {@inheritdoc}
     */
    public static function trustedCallbacks() {
        return [
            'preRenderCacheTags',
        ];
    }
    
    /**
     * Use a plain Symfony response object to output the current install_profile.
     */
    public function getInstallProfile() {
        $install_profile = \Drupal::installProfile() ?: 'NONE';
        return new Response('install_profile: ' . $install_profile);
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service.
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SystemTestController::$currentUser protected property The current user. Overrides ControllerBase::$currentUser
SystemTestController::$lock protected property The lock service.
SystemTestController::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
SystemTestController::$persistentLock protected property The persistent lock service.
SystemTestController::$renderer protected property The renderer.
SystemTestController::authorizeInit public function Initialize authorize.php during testing.
SystemTestController::configureTitle public function Returns the title for system_test.info.yml&#039;s configure route.
SystemTestController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
SystemTestController::getCacheableResponseWithCustomCacheControl public function Returns a cacheable response with a custom cache control.
SystemTestController::getCurrentDate public function Returns the current date.
SystemTestController::getDestination public function Controller to return $_GET[&#039;destination&#039;] for testing.
SystemTestController::getInstallProfile public function Use a plain Symfony response object to output the current install_profile.
SystemTestController::getTestHeader public function Returns a response with a test header set from the request.
SystemTestController::lockAcquire public function Try to acquire a named lock and report the outcome.
SystemTestController::lockExit public function Try to acquire a specific lock, and then exit.
SystemTestController::lockPersist public function Creates a lock that will persist across requests.
SystemTestController::mainContentFallback public function Tests main content fallback.
SystemTestController::messengerServiceTest public function Tests setting messages and removing one before it is displayed.
SystemTestController::permissionDependentContent public function Shows permission-dependent content.
SystemTestController::preRenderCacheTags public static function Sets a cache tag on an element to help test #pre_render and cache tags.
SystemTestController::requestDestination public function Controller to return $_REQUEST[&#039;destination&#039;] for testing.
SystemTestController::respondWithCacheableResponse public function A simple page callback that uses a CacheableResponse object.
SystemTestController::respondWithPublicResponse public function A plain Symfony response with Cache-Control: public, max-age=60.
SystemTestController::respondWithResponse public function A simple page callback that uses a plain Symfony response object.
SystemTestController::setHeader public function Sets a header.
SystemTestController::shutdownFunctions public function A simple page callback which adds a register shutdown function.
SystemTestController::simpleEcho public function Simple argument echo.
SystemTestController::system_test_cache_maxage_page public function Set cache max-age on the returned render array.
SystemTestController::system_test_cache_tags_page public function Set cache tag on on the returned render array.
SystemTestController::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
SystemTestController::__construct public function Constructs the SystemTestController.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.