From 70baaa7ec4d8b518710d65fec41b5bc14313ef55 Mon Sep 17 00:00:00 2001 From: Dmytro Dzubenko Date: Fri, 28 Jul 2017 12:09:46 +0300 Subject: [PATCH] Fix wrong first element exctracting --- src/ContainerAwareManager.php | 32 ++++++++++++++++++++++++++------ src/PaymaxiFractalBundle.php | 3 +++ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/ContainerAwareManager.php b/src/ContainerAwareManager.php index ec47905..b15fd15 100644 --- a/src/ContainerAwareManager.php +++ b/src/ContainerAwareManager.php @@ -28,8 +28,8 @@ class ContainerAwareManager extends Manager implements ContainerAwareInterface * Main method to kick this all off. Make a resource then pass it over, and use toArray() * * @param ResourceInterface $resource - * @param string $scopeIdentifier - * @param Scope $parentScopeInstance + * @param string $scopeIdentifier + * @param Scope $parentScopeInstance * * @return Scope */ @@ -66,13 +66,33 @@ private function resolveTransformer(ResourceInterface $resource) if ($resource instanceof Item) { $instance = ClassUtils::getRealClass(get_class($resource->getData())); } elseif ($resource instanceof Collection) { - $instance = ClassUtils::getRealClass(get_class($resource->getData()[0])); + $data = $resource->getData(); + + if (!is_array($data) && !($data instanceof \Traversable)) { + throw new \InvalidArgumentException( + sprintf('Expected array or array iterator. Given %s', gettype($data)) + ); + } + + $data = ($data instanceof \IteratorAggregate) ? $data->getIterator() : $data; + + $element = is_array($data) ? array_values($data)[0] : $data->current(); + + if (!is_object($element)) { + throw new \InvalidArgumentException( + sprintf('Element expected to be object. Given %s', gettype($element)) + ); + } + + $instance = ClassUtils::getRealClass(get_class($element)); } else { return; } - /** @var ResolverInterface $resolver */ - foreach ($serviceRegistry->all() as $resolver) { + /** @var ResolverInterface[] $resolvers */ + $resolvers = $serviceRegistry->all(); + + foreach ($resolvers as $resolver) { if ($resolver instanceof ContainerAwareInterface) { $resolver->setContainer($this->container); } @@ -84,4 +104,4 @@ private function resolveTransformer(ResourceInterface $resource) } } } -} +} \ No newline at end of file diff --git a/src/PaymaxiFractalBundle.php b/src/PaymaxiFractalBundle.php index 2b423f6..18177bb 100644 --- a/src/PaymaxiFractalBundle.php +++ b/src/PaymaxiFractalBundle.php @@ -13,6 +13,9 @@ */ class PaymaxiFractalBundle extends Bundle { + /** + * @param ContainerBuilder $container + */ public function build(ContainerBuilder $container) { $container->addCompilerPass(new PrioritizedRegistryPass('fractal.transformer.resolvers'));