access_policy-1.0.x-dev/src/Plugin/access_policy/SelectionRule/Boolean.php
src/Plugin/access_policy/SelectionRule/Boolean.php
<?php namespace Drupal\access_policy\Plugin\access_policy\SelectionRule; use Drupal\Core\Form\FormStateInterface; /** * Restrict content by comparing boolean fields on the entity. * * @selectionRule( * id = "boolean", * ) */ class Boolean extends EntityFieldBase { /** * {@inheritdoc} */ public function defaultSettings() { return [ "operator" => '=', ] + parent::defaultSettings(); } /** * {@inheritdoc} */ protected function valueForm(array &$form, FormStateInterface $form_state) { $form['value'] = [ '#type' => 'select', '#title' => $this->t('Value'), '#options' => [ 'true' => $this->t('True'), 'false' => $this->t('False'), ], '#default_value' => $this->settings['value'], ]; } /** * {@inheritdoc} */ public function operators() { $operators = [ '=' => [ 'title' => $this->t('Is equal to'), 'method' => 'validateSimple', ], '!=' => [ 'title' => $this->t('Is not equal to'), 'method' => 'validateSimple', ], 'is applicable' => [ 'title' => $this->t('Is applicable'), 'method' => 'validateIsApplicable', 'hide_value' => TRUE, 'values' => FALSE, ], ]; return $operators; } /** * Validate operators. * * @param mixed $expected * The expected value. * @param mixed $actual * The actual value. * * @return bool * TRUE if operator passes; FALSE otherwise. */ public function validateSimple($expected, $actual) { $op = $this->getOperator(); switch ($op) { case '=': return $this->equals($expected, $actual); case '!=': return $this->notEquals($expected, $actual); } return FALSE; } /** * {@inheritdoc} */ public function adminSummary() { if ($this->isValueHidden()) { return $this->getOperator(); } return $this->getOperator() . ' ' . $this->settings['value']; } /** * {@inheritdoc} */ public function getValue() { // This ensures that the value returned is always a boolean. $values = parent::getValue(); return array_map(function ($value) { return filter_var($value, FILTER_VALIDATE_BOOLEAN); }, $values); } }