public function visitArray($data, Type $type, Context $context) { if (!is_array($data)) { throw new RuntimeException(sprintf('Expected array, but got %s: %s', gettype($data), json_encode($data))); } // If no further parameters were given, keys/values are just passed as is. if (!$type->hasParam(0)) { $this->setData($data); return $data; } switch ($type->countParams()) { case 1: // Array is a list. $listType = $type->getParam(0); $result = []; foreach ($data as $v) { $result[] = $context->accept($v, $listType); } $this->setData($result); return $result; case 2: // Array is a map. $keyType = $type->getParam(0); $entryType = $type->getParam(1); $result = []; foreach ($data as $k => $v) { $result[$context->accept($k, $keyType)] = $context->accept($v, $entryType); } $this->setData($result); return $result; default: throw new RuntimeException(sprintf('Array type cannot have more than 2 parameters, but got %s.', json_encode($type->getParams()))); } }
public function visitArray($data, Type $type, Context $context) { $currentMetadata = $context->getMetadataStack()->getCurrent(); $entryName = null !== $currentMetadata && $currentMetadata->xmlEntryName ? $currentMetadata->xmlEntryName : 'entry'; $namespace = null !== $currentMetadata && $currentMetadata->xmlEntryNamespace ? $currentMetadata->xmlEntryNamespace : null; $result = []; $nodes = null !== $namespace ? $data->children($namespace)->{$entryName} : $data->{$entryName}; switch ($type->countParams()) { case 0: throw new RuntimeException(sprintf('The array type must be specified either as "array<T>", or "array<K,V>".')); case 1: foreach ($nodes as $v) { if ($this->isNullNode($v)) { $result[] = $this->visitNull(null, Type::null(), $context); } else { $result[] = $context->accept($v, $type->getParam(0)); } } break; case 2: if (null === $currentMetadata) { throw new RuntimeException('Maps are not supported on top-level without metadata.'); } $keyType = $type->getParam(0); $entryType = $type->getParam(1); foreach ($nodes as $v) { $attrs = $v->attributes(); if (!isset($attrs[$currentMetadata->xmlKeyAttribute])) { throw new RuntimeException(sprintf('The key attribute "%s" must be set for each entry of the map.', $currentMetadata->xmlKeyAttribute)); } $k = $context->accept($attrs[$currentMetadata->xmlKeyAttribute], $keyType); if ($this->isNullNode($v)) { $result[$k] = $this->visitNull(null, Type::null(), $context); } else { $result[$k] = $context->accept($v, $entryType); } } break; default: throw new LogicException(sprintf('The array type does not support more than 2 parameters, but got %s.', json_encode($type['params']))); } $this->setData($result); return $result; }
/** * @return string * @param Type $type */ private function getFormat(Type $type) { return $type->hasParam(0) ? $type->getParam(0) : $this->defaultFormat; }