Failed Conditions
Pull Request — master (#10)
by Maximo
03:05
created

library/Traits/FractalTrait.php (1 issue)

1
<?php
0 ignored issues
show
End of line character is invalid; expected "\n" but found "\r\n"
Loading history...
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Traits;
6
7
use League\Fractal\Manager;
8
use League\Fractal\Serializer\JsonApiSerializer;
9
use function Gewaer\Core\envValue;
10
use function sprintf;
11
use function ucfirst;
12
13
/**
14
 * Trait FractalTrait
15
 *
16
 * @package Gewaer\Traits
17
 */
18
trait FractalTrait
19
{
20
    /**
21
     * Format results based on a transformer
22
     *
23
     * @param string  $method
24
     * @param mixed   $results
25
     * @param string  $transformer
26
     * @param string  $resource
27
     * @param array   $relationships
28
     * @param array   $fields
29
     *
30
     * @return array
31
     */
32
    protected function format(
33
        string $method,
34
        $results,
35
        string $transformer,
36
        string $resource,
37
        array $relationships = [],
38
        array $fields = []
39
    ): array {
40
        $url = envValue('APP_URL', 'http://localhost');
41
        $manager = new Manager();
42
        $manager->setSerializer(new JsonApiSerializer($url));
43
44
        /**
45
         * Process relationships
46
         */
47
        if (count($relationships) > 0) {
48
            $manager->parseIncludes($relationships);
49
        }
50
51
        $class = sprintf('League\Fractal\Resource\%s', ucfirst($method));
52
        $resource = new $class($results, new $transformer($fields, $resource), $resource);
53
        $results = $manager->createData($resource)->toArray();
54
55
        return $results;
56
    }
57
}
58