access_policy-1.0.x-dev/src/Plugin/access_policy/AccessRule/EntityFieldBoolean.php
src/Plugin/access_policy/AccessRule/EntityFieldBoolean.php
<?php namespace Drupal\access_policy\Plugin\access_policy\AccessRule; use Drupal\Core\Form\FormStateInterface; /** * Restrict content by comparing boolean fields on the entity. * * @AccessRule( * id = "entity_field_boolean", * handlers = { * "query_alter" = "\Drupal\access_policy\AccessRuleQueryHandler\EntityFieldBoolean" * } * ) */ class EntityFieldBoolean 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', ], ]; 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() { 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); } }