示例#1
0
 public function __construct($primitive)
 {
     // set class name and checks it exists
     parent::__construct($primitive);
     // extract string from String instance if needed
     $primitive = (string) $primitive;
     if (!AbstractPrimitive::isPrimitive($primitive)) {
         throw new Exception(sprintf('"%s" does not implements %s', $primitive, PrimitiveInterface::class), Exception::NORMALIZER_INCOMPATIBLE_CLASS);
     }
 }
示例#2
0
 /**
  * Set or retrieve collection type
  *
  * @param string $type      Type of the collection. If null, current type is returned
  *
  * @param bool   $normalize If false, no normalizer will be automatically added - only validator
  *
  * @return $this
  * @throws Exception
  */
 public function restrictTo($type, $normalize = true)
 {
     // unset type
     if (!$type || $type == self::MIXED) {
         return $this->clearRestrictions();
     }
     // set new type
     if (!$this->getValidators()->isEmpty() || !$this->getNormalizers()->isEmpty()) {
         throw new Exception('Class restriction can not be set if there is already Normalizer and/or Validator attached to the collection', Exception::COLLECTION_INVALID_TYPE);
     }
     // add normalizer (if type is a class - interfaces cannot be normalized
     if ($normalize && !interface_exists($type)) {
         switch (true) {
             case !class_exists($type):
                 throw new Exception(sprintf('Class "%s" does not exist', $type), Exception::COLLECTION_INVALID_TYPE);
             case AbstractPrimitive::isPrimitive($type):
                 $normalizer = new PrimitiveNormalizer($type);
                 break;
             default:
                 $normalizer = new ObjectNormalizer($type);
                 break;
         }
         $this->addNormalizer($normalizer);
     }
     $this->addValidator(new ObjectValidator($type));
     $this->type = (string) $type;
     return $this;
 }