DataEndpointController   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 11

Importance

Changes 0
Metric Value
dl 0
loc 252
rs 10
c 0
b 0
f 0
wmc 30
lcom 2
cbo 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSupplementalData() 0 9 1
C character() 0 35 8
A outfit() 0 17 4
B getCharacter() 0 40 6
B getOutfit() 0 42 6
B sendCensusQuery() 0 32 4
1
<?php
2
3
namespace Ps2alerts\Api\Controller\Endpoint\Data;
4
5
use Ps2alerts\Api\Controller\Endpoint\AbstractEndpointController;
6
use Ps2alerts\Api\Transformer\DataTransformer;
7
use Ps2alerts\Api\Transformer\Data\CharacterTransformer;
8
use Ps2alerts\Api\Transformer\Data\OutfitTransformer;
9
use Ps2alerts\Api\Contract\HttpClientAwareInterface;
10
use Ps2alerts\Api\Contract\HttpClientAwareTrait;
11
use Ps2alerts\Api\Exception\CensusErrorException;
12
use Ps2alerts\Api\Exception\CensusEmptyException;
13
use Ps2alerts\Api\Exception\RedisStoreException;
14
use Psr\Http\Message\ServerRequestInterface;
15
use Psr\Http\Message\ResponseInterface;
16
17
class DataEndpointController extends AbstractEndpointController implements
18
    HttpClientAwareInterface
19
{
20
    use HttpClientAwareTrait;
21
22
    /**
23
     * Construct
24
     *
25
     * @param DataTransformer $dataTransformer
26
     *
27
     */
28
    public function __construct(
29
        DataTransformer $dataTransformer
30
    ) {
31
        $this->transformer = $dataTransformer;
32
    }
33
34
    /**
35
     * Gets supplemental data
36
     *
37
     * @param  ServerRequestInterface  $request
38
     * @param  ResponseInterface $response
39
     * @param  array                                     $args
40
     *
41
     * @return ResponseInterface
42
     */
43
    public function getSupplementalData(ServerRequestInterface $request, ResponseInterface $response, array $args)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
    {
45
        // All data handling is done within the transformer.
46
        return $this->respond(
47
            'item',
48
            [],
49
            $this->transformer
50
        );
51
    }
52
53
    /**
54
     * Gets a player's info, either from redis or db cache
55
     *
56
     * @param  ServerRequestInterface $request
57
     * @param  ResponseInterface      $response
58
     * @param  array                  $args
59
     *
60
     * @return ResponseInterface
61
     */
62
    public function character(ServerRequestInterface $request, ResponseInterface $response, array $args)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
63
    {
64
        try {
65
            $character['data'] = $this->getCharacter($args['id']);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$character was never initialized. Although not strictly required by PHP, it is generally a good practice to add $character = 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...
66
        } catch (CensusErrorException $e) {
67
            $this->setStatusCode(500);
68
            return $this->respondWithError('Census returned garbage!', self::CODE_EXTERNAL_ERROR);
69
        } catch (CensusEmptyException $e) {
70
            $this->setStatusCode(404);
71
            return $this->respondWithError('Census returned no data!', self::CODE_EXTERNAL_ERROR);
72
        } catch (RedisStoreException $e) {
73
            $this->setStatusCode(500);
74
            return $this->respondWithError('Redis store failed!', self::CODE_INTERNAL_ERROR);
75
        }
76
77
        // Now return the character the outfit injected
78
        if (! empty($character['data']['outfit'])) {
79
            try {
80
                $outfit = $this->getOutfit($character['data']['outfit']);
81
            } catch (CensusErrorException $e) {
82
                $this->setStatusCode(500);
83
                return $this->respondWithError('Census returned garbage!', self::CODE_EXTERNAL_ERROR);
84
            } catch (CensusEmptyException $e) {
85
                $this->setStatusCode(404);
86
                return $this->respondWithError('Census returned no data!', self::CODE_EXTERNAL_ERROR);
87
            } catch (RedisStoreException $e) {
88
                $this->setStatusCode(500);
89
                return $this->respondWithError('Redis store failed!', self::CODE_INTERNAL_ERROR);
90
            }
91
92
            $character['data']['outfit'] = $outfit;
93
        }
94
95
        return $this->respondWithData($character);
96
    }
97
98
    /**
99
     * Gets an outfits's info, either from redis or db cache
100
     *
101
     * @param  ServerRequestInterface $request
102
     * @param  ResponseInterface      $response
103
     * @param  array                  $args
104
     *
105
     * @return ResponseInterface
106
     */
107
    public function outfit(ServerRequestInterface $request, ResponseInterface $response, array $args)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $response is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
108
    {
109
        try {
110
            $outfit['data'] = $this->getOutfit($args['id']);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$outfit was never initialized. Although not strictly required by PHP, it is generally a good practice to add $outfit = 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...
111
        } catch (CensusErrorException $e) {
112
            $this->setStatusCode(500);
113
            return $this->respondWithError('Census returned garbage!', self::CODE_EXTERNAL_ERROR);
114
        } catch (CensusEmptyException $e) {
115
            $this->setStatusCode(404);
116
            return $this->respondWithError('Census returned no data!', self::CODE_EXTERNAL_ERROR);
117
        } catch (RedisStoreException $e) {
118
            $this->setStatusCode(500);
119
            return $this->respondWithError('Redis store failed!', self::CODE_INTERNAL_ERROR);
120
        }
121
122
        return $this->respondWithData($outfit);
123
    }
124
125
    /**
126
     * Gets the character from Census with a supplied ID
127
     *
128
     * @param  string $id
129
     *
130
     * @throws CensusErrorException
131
     * @throws CensusEmptyException
132
     *
133
     * @return array|ResponseInterface
134
     */
135
    public function getCharacter($id)
136
    {
137
        // First, check if we have the character in Redis
138
        $redisCheck = $this->getRedisUtility()->checkRedis('cache', 'character', $id);
139
140
        if (! empty($redisCheck)) {
141
            return $redisCheck;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $redisCheck; (string|boolean) is incompatible with the return type documented by Ps2alerts\Api\Controller...ontroller::getCharacter of type array|Psr\Http\Message\ResponseInterface.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
142
        }
143
144
        // Since we don't have any data, let's grab it from Census.
145
        $endpoint = "character?character_id={$id}&c:resolve=outfit,world";
146
147
        try {
148
            $json = $this->sendCensusQuery($endpoint);
149
        } catch (\Exception $e) {
150
            throw new CensusErrorException();
151
        }
152
153
        // If the character is empty...
154
        // SCENARIOS: Character has been banned or deleted
155
        if ($json === null || empty($json->character_list)) {
156
            throw new CensusEmptyException();
157
        }
158
159
        $env = $json->environment;
160
        $json = $json->character_list[0];
161
        $json->environment = $env; // Re-inject the ENV to store
162
163
        $character = $this->getFractalUtility()->createItem($json, new CharacterTransformer);
164
165
        // First store the player without an outfit so we're not storing duplicated data
166
        try {
167
            $this->getRedisUtility()->storeInRedis('cache', 'character', $id, $character['data']);
168
        } catch (\Exception $e) {
169
            $this->setStatusCode(500);
170
            return $this->respondWithError('Redis store failed!', 'INTERNAL_ERROR');
171
        }
172
173
        return $character['data'];
174
    }
175
176
177
    /**
178
     * Gets an outfit from either Redis or Census
179
     *
180
     * @param  string $id
181
     *
182
     * @return array
183
     */
184
    public function getOutfit($id)
185
    {
186
        // First, check if we have the outfit in Redis
187
        $redisCheck = $this->getRedisUtility()->checkRedis('cache', 'outfit', $id);
188
189
        if (! empty($redisCheck)) {
190
            return $redisCheck;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $redisCheck; (string|boolean) is incompatible with the return type documented by Ps2alerts\Api\Controller...ntController::getOutfit of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
191
        }
192
193
        // Since we don't have any data, let's grab it from Census.
194
        $endpoint = "outfit?outfit_id={$id}&c:resolve=leader";
195
196
        try {
197
            $json = $this->sendCensusQuery($endpoint);
198
        } catch (\Exception $e) {
199
            throw new CensusErrorException('Census returned an error');
200
        }
201
202
        // If the outfit is empty...
203
        // SCENARIOS: Outfit has been deleted
204
        if ($json === null || empty($json->outfit_list)) {
205
            throw new CensusEmptyException('Census returned no data');
206
        }
207
208
        $env = $json->environment;
209
        $outfit = $json->outfit_list[0];
210
        $outfit->environment = $env; // Re-inject the ENV to store
211
212
        // Now to get the outfit's world, we need to get leader details
213
        $leader = $this->getCharacter($outfit->leader_character_id);
214
        $outfit->server = $leader['server'];
215
216
        $outfit = $this->getFractalUtility()->createItem($outfit, new OutfitTransformer);
217
218
        try {
219
            $this->getRedisUtility()->storeInRedis('cache', 'outfit', $id, $outfit['data'], 604800); // 1 week
220
        } catch (\Exception $e) {
221
            throw new RedisStoreException('Unable to store in Redis!');
222
        }
223
224
        return $outfit['data'];
225
    }
226
227
    /**
228
     * Allows the sending of queries to census, along with checking all environments
229
     *
230
     * @param  string $endpoint Endpoint string to get data from
231
     *
232
     * @throws \Exception
233
     *
234
     * @return string
235
     */
236
    public function sendCensusQuery($endpoint)
237
    {
238
        $config = $this->getConfig();
239
        $guzzle = $this->getHttpClientDriver();
240
241
        $environments = [
242
            'ps2:v2',
243
            'ps2ps4us',
244
            'ps2ps4eu'
245
        ];
246
247
        // Loop through each environment and get the first result
248
        foreach($environments as $env) {
249
            $url = "https://census.daybreakgames.com/s:{$config['census_service_id']}/get/{$env}/{$endpoint}";
250
251
            $req  = $guzzle->request('GET', $url);
252
            $body = $req->getBody();
253
            $json = json_decode($body);
254
255
            // Check for errors #BRINGJSONEXCEPTIONS!
256
            if (json_last_error() !== JSON_ERROR_NONE) {
257
                throw new \Exception();
258
            }
259
260
            // Append the environment so we can store it for later
261
            $json->environment = $env;
262
263
            if ($json->returned !== 0) {
264
                return $json;
265
            }
266
        }
267
    }
268
}
269