PageNotFoundRequest.php in Block In Page Not Found 8.3
File
src/Plugin/Condition/PageNotFoundRequest.php
View source
<?php
namespace Drupal\block_in_page_not_found\Plugin\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class PageNotFoundRequest extends ConditionPluginBase implements ContainerFactoryPluginInterface {
protected $requestStack;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($container
->get('request_stack'), $configuration, $plugin_id, $plugin_definition);
}
public function defaultConfiguration() {
return [
'page_not_found' => '',
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['prefix'] = [
'#markup' => '<h5>Page Not Found</h5>',
];
$form['page_not_found'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Show in page not found'),
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['page_not_found'] = $form_state
->getValue('page_not_found');
parent::submitConfigurationForm($form, $form_state);
}
public function __construct(RequestStack $request_stack, array $configuration, $plugin_id, array $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->requestStack = $request_stack;
}
public function evaluate() {
$page_not_found_checked = $this->configuration['page_not_found'];
if (!$page_not_found_checked || $page_not_found_checked == 0) {
return FALSE;
}
if ($page_not_found_checked == 1) {
$status = $this->requestStack
->getCurrentRequest()->attributes
->get('exception');
if ($status && $status
->getStatusCode() == 404) {
return TRUE;
}
else {
return FALSE;
}
}
}
public function summary() {
if (!empty($this->configuration['negate'])) {
return $this
->t('Do not return true on the following page not found.');
}
return $this
->t('Return true on the following page not found.');
}
public function getCacheContexts() {
$contexts = parent::getCacheContexts();
$contexts[] = 'url.path';
return $contexts;
}
}