public function TypedDataManager::getConstraints

Gets configured constraints from a data definition.

Any constraints defined for the data type, i.e. below the 'constraint' key of the type's plugin definition, or constraints defined below the data definition's constraint' key are taken into account.

Constraints are defined via an array, having constraint plugin IDs as key and constraint options as values, e.g.

$constraints = array(
  'Range' => array(
    'min' => 5,
    'max' => 10,
  ),
  'NotBlank' => array(),
);

Options have to be specified using another array if the constraint has more than one or zero options. If it has exactly one option, the value should be specified without nesting it into another array:

$constraints = array(
  'EntityType' => 'node',
  'Bundle' => 'article',
);

Note that the specified constraints must be compatible with the data type, e.g. for data of type 'entity' the 'EntityType' and 'Bundle' constraints may be specified.

Parameters

array $definition: A data definition array.

Return value

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

See also

\Drupal\Core\Validation\ConstraintManager

File

drupal/core/lib/Drupal/Core/TypedData/TypedDataManager.php, line 344
Contains \Drupal\Core\TypedData\TypedDataManager.

Class

TypedDataManager
Manages data type plugins.

Namespace

Drupal\Core\TypedData

Code

public function getConstraints($definition) {
  $constraints = array();
  $validation_manager = $this
    ->getValidationConstraintManager();
  $type_definition = $this
    ->getDefinition($definition['type']);

  // Auto-generate a constraint for the primitive type if we have a mapping.
  if (isset($type_definition['primitive type'])) {
    $constraints[] = $validation_manager
      ->create('PrimitiveType', array(
      'type' => $type_definition['primitive type'],
    ));
  }

  // Add in constraints specified by the data type.
  if (isset($type_definition['constraints'])) {
    foreach ($type_definition['constraints'] as $name => $options) {
      $constraints[] = $validation_manager
        ->create($name, $options);
    }
  }

  // Add any constraints specified as part of the data definition.
  if (isset($definition['constraints'])) {
    foreach ($definition['constraints'] as $name => $options) {
      $constraints[] = $validation_manager
        ->create($name, $options);
    }
  }

  // Add the NotNull constraint for required data.
  if (!empty($definition['required']) && empty($definition['constraints']['NotNull'])) {
    $constraints[] = $validation_manager
      ->create('NotNull', array());
  }
  return $constraints;
}