aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/JsonApiIntegration/FieldsetFilter.php
blob: a2be39a550cd7a7693ef3b4f438600e77055f254 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
namespace JsonApi\JsonApiIntegration;

class FieldsetFilter extends \Neomerx\JsonApi\Representation\FieldSetFilter
{
    /**
     * @param string   $type
     * @param iterable $fields
     *
     * @return iterable
     */
    protected function filterFields(string $type, iterable $fields): iterable
    {
        if ($this->hasFilter($type) === false) {
            foreach ($fields as $name => $value) {
                yield $name => $this->resolveValue($value);
            }

            return;
        }

        $allowedFields = $this->getAllowedFields($type);
        foreach ($fields as $name => $value) {
            if (isset($allowedFields[$name]) === true) {
                yield $name => $this->resolveValue($value);
            }
        }
    }

    /**
     * Resolves a given by either calling it if it's a callable. Otherwise
     * just return the value itself.
     *
     * @param mixed $value
     * @return mixed
     */
    private function resolveValue($value)
    {
        if ($value instanceof \Closure) {
            return $value();
        }

        return $value;
    }
}