You are here

public function Dimension::getConstraints in Dimension 2.0.x

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldType/Dimension.php \Drupal\dimension\Plugin\Field\FieldType\Dimension::getConstraints()
  2. 2.1.x src/Plugin/Field/FieldType/Dimension.php \Drupal\dimension\Plugin\Field\FieldType\Dimension::getConstraints()

Gets a list of validation constraints.

Return value

array Array of constraints, each being an instance of \Symfony\Component\Validator\Constraint.

Overrides DecimalItem::getConstraints

File

src/Plugin/Field/FieldType/Dimension.php, line 211

Class

Dimension

Namespace

Drupal\dimension\Plugin\Field\FieldType

Code

public function getConstraints() : array {
  $constraint_manager = Drupal::typedDataManager()
    ->getValidationConstraintManager();
  $constraints = [];
  foreach ($this->definition
    ->getConstraints() as $name => $options) {
    $constraints[] = $constraint_manager
      ->create($name, $options);
  }

  /** @noinspection StaticInvocationViaThisInspection */
  foreach ($this
    ->fields() as $key => $label) {
    $settings = $this
      ->getSetting($key);
    $constraints[] = $constraint_manager
      ->create('ComplexData', [
      $key => [
        'Regex' => [
          'pattern' => '/^[+-]?((\\d+(\\.\\d*)?)|(\\.\\d+))$/i',
        ],
      ],
    ]);
    if (!empty($settings['min'])) {
      $min = $settings['min'];
      $constraints[] = $constraint_manager
        ->create('ComplexData', [
        $key => [
          'Range' => [
            'min' => $min,
            'minMessage' => $this
              ->t('%name: the value may be no less than %min.', [
              '%name' => $label,
              '%min' => $min,
            ]),
          ],
        ],
      ]);
    }
    if (!empty($settings['max'])) {
      $max = $settings['max'];
      $constraints[] = $constraint_manager
        ->create('ComplexData', [
        $key => [
          'Range' => [
            'max' => $max,
            'maxMessage' => $this
              ->t('%name: the value may be no greater than %max.', [
              '%name' => $label,
              '%max' => $max,
            ]),
          ],
        ],
      ]);
    }
  }
  return $constraints;
}