AbstractApiController::collection()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of Gitamin.
5
 *
6
 * Copyright (C) 2015-2016 The Gitamin Team
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Gitamin\Http\Controllers\Api;
13
14
use Illuminate\Contracts\Pagination\Paginator;
15
use Illuminate\Contracts\Support\Arrayable;
16
use Illuminate\Http\Request;
17
use Illuminate\Routing\Controller;
18
use Illuminate\Support\Collection;
19
use Illuminate\Support\Facades\Response;
20
use McCool\LaravelAutoPresenter\Facades\AutoPresenter;
21
22
abstract class AbstractApiController extends Controller
23
{
24
    /**
25
     * The HTTP response headers.
26
     *
27
     * @var array
28
     */
29
    protected $headers = [];
30
31
    /**
32
     * The HTTP response meta data.
33
     *
34
     * @var array
35
     */
36
    protected $meta = [];
37
38
    /**
39
     * The HTTP response data.
40
     *
41
     * @var mixed
42
     */
43
    protected $data = null;
44
45
    /**
46
     * The HTTP response status code.
47
     *
48
     * @var int
49
     */
50
    protected $statusCode = 200;
51
52
    /**
53
     * Set the response headers.
54
     *
55
     * @param array $headers
56
     *
57
     * @return $this
58
     */
59
    protected function setHeaders(array $headers)
60
    {
61
        $this->headers = $headers;
62
63
        return $this;
64
    }
65
66
    /**
67
     * Set the response meta data.
68
     *
69
     * @param array $meta
70
     *
71
     * @return $this
72
     */
73
    protected function setMetaData(array $meta)
74
    {
75
        $this->meta = $meta;
76
77
        return $this;
78
    }
79
80
    /**
81
     * Set the response meta data.
82
     *
83
     * @param array $data
84
     *
85
     * @return $this
86
     */
87
    protected function setData($data)
88
    {
89
        $this->data = $data;
90
91
        return $this;
92
    }
93
94
    /**
95
     * Set the response status code.
96
     *
97
     * @param int $statusCode
98
     *
99
     * @return $this
100
     */
101
    protected function setStatusCode($statusCode)
102
    {
103
        $this->statusCode = $statusCode;
104
105
        return $this;
106
    }
107
108
    /**
109
     * Respond with an item response.
110
     *
111
     * @param mixed
112
     *
113
     * @return \Illuminate\Http\JsonResponse
114
     */
115
    public function item($item)
116
    {
117
        return $this->setData(AutoPresenter::decorate($item))->respond();
118
    }
119
120
    /**
121
     * Respond with a collection response.
122
     *
123
     * @param \Illuminate\Support\Collection $collection
124
     *
125
     * @return \Illuminate\Http\JsonResponse
126
     */
127
    public function collection(Collection $collection)
128
    {
129
        return $this->setData(AutoPresenter::decorate($collection))->respond();
130
    }
131
132
    /**
133
     * Respond with a pagination response.
134
     *
135
     * @param \Illuminate\Pagination\Paginator $paginator
136
     * @param \Illuminate\Http\Request         $request
137
     *
138
     * @return \Illuminate\Http\JsonResponse
139
     */
140
    protected function paginator(Paginator $paginator, Request $request)
141
    {
142
        foreach ($request->query as $key => $value) {
143
            if ($key !== 'page') {
144
                $paginator->addQuery($key, $value);
145
            }
146
        }
147
148
        $pagination = [
149
            'pagination' => [
150
                'total' => (int) $paginator->total(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Pagination\Paginator as the method total() does only exist in the following implementations of said interface: Illuminate\Pagination\LengthAwarePaginator.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
151
                'count' => count($paginator->items()),
152
                'per_page' => (int) $paginator->perPage(),
153
                'current_page' => (int) $paginator->currentPage(),
154
                'total_pages' => (int) $paginator->lastPage(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Pagination\Paginator as the method lastPage() does only exist in the following implementations of said interface: Illuminate\Pagination\LengthAwarePaginator.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
155
                'links' => [
156
                    'next_page' => $paginator->nextPageUrl(),
157
                    'previous_page' => $paginator->previousPageUrl(),
158
                ],
159
            ],
160
        ];
161
162
        $items = $paginator->getCollection();
163
164
        if ($sortBy = $request->get('sort')) {
165
            $direction = $request->has('order') && $request->get('order') === 'desc';
166
167
            $items = $items->sortBy($sortBy, SORT_REGULAR, $direction);
168
        }
169
170
        return $this->setMetaData($pagination)->setData(AutoPresenter::decorate($items->values()))->respond();
171
    }
172
173
    /**
174
     * Respond with a no content response.
175
     *
176
     * @param string $message
0 ignored issues
show
Bug introduced by
There is no parameter named $message. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
177
     *
178
     * @return \Illuminate\Http\JsonResponse
179
     */
180
    protected function noContent()
181
    {
182
        return $this->setStatusCode(204)->respond();
183
    }
184
185
    /**
186
     * Build the response.
187
     *
188
     * @return \Illuminate\Http\Response
189
     */
190
    protected function respond()
191
    {
192
        if (! empty($this->meta)) {
193
            $response['meta'] = $this->meta;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
194
        }
195
196
        $response['data'] = $this->data;
0 ignored issues
show
Bug introduced by
The variable $response does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
197
198
        if ($this->data instanceof Arrayable) {
199
            $response['data'] = $this->data->toArray();
200
        }
201
202
        return Response::json($response, $this->statusCode, $this->headers);
203
    }
204
}
205