nilportugues / php-json-api

JSON API transformer outputting valid (PSR-7) API Responses.
http://nilportugues.com
MIT License
71 stars 35 forks source link

MappingFactory::fromArray() always seems to unbox the array #93

Closed fr0gs closed 6 years ago

fr0gs commented 7 years ago

I am constantly getting for this code:

    $mappings = array(OfferMapping::class); // Also tried with []

    $mapper = new Mapper($mappings);
    $transformer = new JsonApiTransformer($mapper);
    $serializer = new JsonApiSerializer($transformer);
        return response()->$serializer->serialize(Offer::all())
                     ->header('Access-Control-Allow-Origin', '*');

This error message:

1/1
FatalThrowableError in MappingFactory.php line 93:
Type error: Argument 1 passed to NilPortugues\Api\Mapping\MappingFactory::fromArray() must be of the type array, string given, called in /var/www/vendor/nilportugues/api-transformer/src/Mapping/Mapper.php on line 53
in MappingFactory.php line 93
at MappingFactory::fromArray('App\Api\Mappings\OfferMapping') in Mapper.php line 53
at Mapper->buildMapping('App\Api\Mappings\OfferMapping') in Mapper.php line 36
at Mapper->__construct(array('App\Api\Mappings\OfferMapping')) in OfferController.php line 35

I have tried passing

 $mapper = new Mapper([1]);
 $mapper = new Mapper(array(OfferMapping::class, $othermapping))

And other example values with no result. It seems to internally unbox the first one all the time.

I am using laravel 5.2 and using php-json-api 2.6.0.

fr0gs commented 7 years ago

I think I found the error.

    protected function buildMapping($mappedClass)
    {
        return (\is_string($mappedClass) && \class_exists($mappedClass, true)) ?
            MappingFactory::fromClass($mappedClass) :
            MappingFactory::fromArray($mappedClass);
    }

Which means that if you don't realize the class does not exist (was not properly imported) the function thinks it is an array. Would it be possible to throw a different error instead maybe to enhance debugging?