PropertyContainerMetadata.php 2.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<?php

/**
 * @file
 * Contains \Drupal\Core\TypedData\Validation\PropertyContainerMetadata.
 */

namespace Drupal\Core\TypedData\Validation;

use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\ListInterface;
use Symfony\Component\Validator\PropertyMetadataContainerInterface;
use Symfony\Component\Validator\ValidationVisitorInterface;

/**
 * Typed data implementation of the validator MetadataInterface.
 */
class PropertyContainerMetadata extends Metadata implements PropertyMetadataContainerInterface {

  /**
   * Overrides Metadata::accept().
   */
  public function accept(ValidationVisitorInterface $visitor, $typed_data, $group, $propertyPath) {
    // To let all constraints properly handle empty structures, pass on NULL
    // if the data structure is empty. That way existing NotNull or NotBlank
    // constraints work as expected.
    if ($typed_data->isEmpty()) {
      $typed_data = NULL;
    }
    $visitor->visit($this, $typed_data, $group, $propertyPath);
    $pathPrefix = empty($propertyPath) ? '' : $propertyPath . '.';

    if ($typed_data) {
      foreach ($typed_data as $name => $data) {
        $metadata = $this->factory->getMetadataFor($data, $name);
        $metadata->accept($visitor, $data, $group, $pathPrefix . $name);
      }
    }
  }

41 42 43 44 45 46 47 48 49 50 51 52 53
  /**
   * Implements PropertyMetadataContainerInterface::hasPropertyMetadata().
   */
  public function hasPropertyMetadata($property_name) {
    try {
      $exists = (bool)$this->getPropertyMetadata($property_name);
    }
    catch (\LogicException $e) {
      $exists = FALSE;
    }
    return $exists;
  }

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /**
   * Implements PropertyMetadataContainerInterface::getPropertyMetadata().
   */
  public function getPropertyMetadata($property_name) {
    if ($this->typedData instanceof ListInterface) {
      return array(new Metadata($this->typedData[$property_name], $property_name));
    }
    elseif ($this->typedData instanceof ComplexDataInterface) {
      return array(new Metadata($this->typedData->get($property_name), $property_name));
    }
    else {
      throw new \LogicException("There are no known properties.");
    }
  }
}