Example #1
0
 /**
  * @param mixed      $value
  * @param int        $level
  * @param array|null $config
  *
  * @return mixed
  */
 protected function normalizeValue($value, $level, $config = null)
 {
     if (is_array($value)) {
         $nextLevel = $level + 1;
         foreach ($value as &$val) {
             $val = $this->normalizeValue($val, $nextLevel, $config);
         }
     } elseif (is_object($value)) {
         $objectNormalizer = $this->getObjectNormalizer($value);
         if (null !== $objectNormalizer) {
             $value = $objectNormalizer->normalize($value);
         } elseif ($value instanceof \Traversable) {
             $result = [];
             $nextLevel = $level + 1;
             foreach ($value as $val) {
                 $result[] = $this->normalizeValue($val, $nextLevel, $config);
             }
             $value = $result;
         } elseif (!empty($config)) {
             $value = $this->normalizeObjectByConfig($value, $config, $level);
         } elseif ($this->doctrineHelper->isManageableEntity($value)) {
             if ($level <= static::MAX_NESTING_LEVEL) {
                 $value = $this->normalizeEntity($value, $level);
             } else {
                 $entityId = $this->doctrineHelper->getEntityIdentifier($value);
                 $count = count($entityId);
                 if ($count === 1) {
                     $value = reset($entityId);
                 } elseif ($count > 1) {
                     $value = $entityId;
                 } else {
                     throw new \RuntimeException(sprintf('The entity "%s" does not have an identifier.', ClassUtils::getClass($value)));
                 }
             }
         } else {
             if ($level <= static::MAX_NESTING_LEVEL) {
                 $value = $this->normalizePlainObject($value, $level);
             } elseif (method_exists($value, '__toString')) {
                 $value = (string) $value;
             } else {
                 throw new \RuntimeException(sprintf('Instance of "%s" cannot be normalized.', get_class($value)));
             }
         }
     }
     return $value;
 }