Test Failed
Pull Request — master (#160)
by Maximo
05:32
created

ProcessOutputMapperTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 61
ccs 0
cts 30
cp 0
rs 10
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getMapperOptions() 0 9 2
A canUseMapper() 0 7 3
A processOutput() 0 20 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Contracts\Controllers;
6
7
use Canvas\Exception\ServerErrorHttpException;
8
use AutoMapperPlus\DataType;
9
use StdClass;
10
11
trait ProcessOutputMapperTrait
12
{
13
    protected $dto = null;
14
    protected $dtoMapper = null;
15
16
    /**
17
    * Format Controller Result base on a Mapper.
18
    *
19
    * @param mixed $results
20
    * @return void
21
    */
22
    protected function processOutput($results)
23
    {
24
        $this->canUseMapper();
25
26
        //if we have relationships we use StdClass to allow use to overwrite the array as we see fit in the Dto
27
        $mapperModel = !$this->request->hasQuery('relationships') ? get_class($this->model) : DataType::ARRAY;
28
        $this->dto = !$this->request->hasQuery('relationships') ? $this->dto : StdClass::class;
29
30
        $this->dtoConfig->registerMapping($mapperModel, $this->dto)
31
            ->useCustomMapper($this->dtoMapper);
32
33
        if (is_array($results) && isset($results['data'])) {
34
            $results['data'] = $this->mapper->mapMultiple($results['data'], $this->dto);
35
            return  $results;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $results returns the type array which is incompatible with the documented return type void.
Loading history...
36
        }
37
38
        //return $this->mapper->map($results, $this->dto, $this->getMapperOptions());
39
        return is_iterable($results) ?
40
            $this->mapper->mapMultiple($results, $this->dto)
41
            : $this->mapper->map($results, $this->dto);
42
    }
43
44
    /**
45
     * Can we use the mapper on this request?
46
     *
47
     * @return boolean
48
     */
49
    protected function canUseMapper(): bool
50
    {
51
        if (!is_object($this->model) || empty($this->dto)) {
52
            throw new ServerErrorHttpException('No Mapper configured on this controller ' . get_class($this));
53
        }
54
55
        return true;
56
    }
57
58
    /**
59
     * If we have relationships send them as addicontal context to the mapper.
60
     *
61
     * @return array
62
     */
63
    protected function getMapperOptions(): array
64
    {
65
        if ($this->request->hasQuery('relationships')) {
66
            return [
67
                'relationships' => explode(',', $this->request->getQuery('relationships'))
68
            ];
69
        }
70
71
        return [];
72
    }
73
}
74