Completed
Push — master ( 067f09...35db61 )
by Temitope
9s
created

EmojiController   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 249
Duplicated Lines 8.03 %

Coupling/Cohesion

Components 0
Dependencies 8

Importance

Changes 18
Bugs 6 Features 3
Metric Value
wmc 24
c 18
b 6
f 3
lcom 0
cbo 8
dl 20
loc 249
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A listAllEmoji() 0 12 2
A getSingleEmoji() 0 14 2
B createEmoji() 0 30 3
A updateEmojiByPutVerb() 0 22 3
A updateEmojiByPatchVerb() 0 19 3
A deleteEmoji() 0 15 2
A createEmojiKeywords() 18 18 3
A formatEmoji() 0 10 2
B getCurrentUserId() 0 25 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * @author   Temitope Olotin <[email protected]>
4
 * @license  <https://opensource.org/license/MIT> MIT
5
 */
6
namespace Laztopaz\EmojiRestfulAPI;
7
8
use Firebase\JWT\JWT;
9
use Psr\Http\Message\ResponseInterface as Response;
10
use Psr\Http\Message\ServerRequestInterface as Request;
11
12
class EmojiController
13
{
14
    private $auth;
15
16
    public function __construct(Oauth $auth)
17
    {
18
        $this->auth = $auth;
19
    }
20
21
    /**
22
     * This method list all emojis.
23
     *
24
     * @param $response
25
     *
26
     * @return json $emojis
27
     */
28
    public function listAllEmoji(Response $response)
29
    {
30
        $emojis = Emoji::with('keywords', 'category', 'created_by')->get();
31
        $emojis = $emojis->toArray();
32
33
        if (count($emojis) > 0) {
34
            return $response
35
            ->withJson($this->formatEmoji($emojis), 200);
36
        }
37
38
        return $response->withJson(['status'], 404);
39
    }
40
41
    /**
42
     * This method get a single emoji.
43
     *
44
     * @param $response
45
     * @param $args
46
     *
47
     * @return json $emoji
48
     */
49
    public function getSingleEmoji(Response $response, $args)
50
    {
51
        $id = $args['id'];
52
53
        $emoji = Emoji::where('id', '=', $id)->with('keywords', 'category', 'created_by')->get();
54
        $emoji = $emoji->toArray();
55
56
        if (count($emoji) > 0) {
57
            return $response
58
            ->withJson($this->formatEmoji($emoji), 200);
59
        }
60
61
        return $response->withStatus(404);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response->withStatus(404); (Psr\Http\Message\ResponseInterface) is incompatible with the return type documented by Laztopaz\EmojiRestfulAPI...troller::getSingleEmoji of type Laztopaz\EmojiRestfulAPI\json.

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...
62
    }
63
64
    /**
65
     * This method creates a new emoji.
66
     *
67
     * @param $args
68
     *
69
     * @return json $response;
70
     */
71
    public function createEmoji(Request $request, Response $response)
72
    {
73
        $requestParams = $request->getParsedBody();
74
75
        $emojiKeyword = $requestParams['keywords'];
76
77
        $userId = $this->getCurrentUserId($request, $response);
78
79
        if (is_array($requestParams)) {
80
            $created_at = date('Y-m-d h:i:s');
81
82
            $emoji = Emoji::create(
83
                [
84
                    'name'       => $requestParams['name'],
85
                    'char'       => $requestParams['char'],
86
                    'created_at' => $created_at,
87
                    'category'   => $requestParams['category'],
88
                    'created_by' => $userId,
89
                ]
90
            );
91
92
            if ($emoji->id) {
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Laztopaz\EmojiRestfulAPI\Emoji>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
93
                $createdKeyword = $this->createEmojiKeywords($emoji->id, $emojiKeyword);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Laztopaz\EmojiRestfulAPI\Emoji>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Unused Code introduced by
$createdKeyword is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
94
95
                return $response->withJson($emoji->toArray(), 201);
96
            }
97
98
            return $response->withStatus(204);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response->withStatus(204); (Psr\Http\Message\ResponseInterface) is incompatible with the return type documented by Laztopaz\EmojiRestfulAPI...Controller::createEmoji of type Laztopaz\EmojiRestfulAPI\json.

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...
99
        }
100
    }
101
102
    /**
103
     * This method updates an emoji.
104
     *
105
     * @param $request
106
     * @param $response
107
     *
108
     * @return json
109
     */
110
    public function updateEmojiByPutVerb(Request $request, Response $response, $args)
111
    {
112
        $upateParams = $request->getParsedBody();
113
114
        if (is_array($upateParams)) {
115
            $id = $args['id'];
116
117
            $emoji = Emoji::find($id);
118
119
            if ($emoji->id) {
120
                $emoji->name = $upateParams['name'];
121
                $emoji->char = $upateParams['char'];
122
                $emoji->category = $upateParams['category'];
123
                $emoji->updated_at = date('Y-m-d h:i:s');
124
                $emoji->save();
0 ignored issues
show
Bug introduced by
The method save does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloq...ase\Eloquent\Collection.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
125
126
                return $response->withJson(['status'], 201);
127
            }
128
129
            return $response->withJson(['status'], 404);
130
        }
131
    }
132
133
    /**
134
     * This method updates an emoji partially.
135
     *
136
     * @param $request
137
     * @param $response
138
     *
139
     * @return json
140
     */
141
    public function updateEmojiByPatchVerb(Request $request, Response $response, $args)
142
    {
143
        $upateParams = $request->getParsedBody();
144
145
        if (is_array($upateParams)) {
146
            $id = $args['id'];
147
148
            $emoji = Emoji::find($id);
149
            if ($emoji->id) {
150
                $emoji->name = $upateParams['name'];
151
                $emoji->updated_at = date('Y-m-d h:i:s');
152
                $emoji->save();
0 ignored issues
show
Bug introduced by
The method save does only exist in Illuminate\Database\Eloquent\Model, but not in Illuminate\Database\Eloq...ase\Eloquent\Collection.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
153
154
                return $response->withJson($emoji->toArray(), 201);
0 ignored issues
show
Bug introduced by
The method toArray does only exist in Illuminate\Database\Eloq...Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Builder.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
155
            }
156
157
            return $response->withStatus(404);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response->withStatus(404); (Psr\Http\Message\ResponseInterface) is incompatible with the return type documented by Laztopaz\EmojiRestfulAPI...:updateEmojiByPatchVerb of type Laztopaz\EmojiRestfulAPI\json.

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...
158
        }
159
    }
160
161
    /**
162
     * This method deletes an emoji.
163
     *
164
     * @param $request
165
     * @param $response
166
     * @param $args
167
     *
168
     * @return json
169
     */
170
    public function deleteEmoji(Request $request, Response $response, $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...
171
    {
172
        $id = $args['id'];
173
174
        $emoji = Emoji::find($id);
175
        if ($emoji->id) {
176
            $emoji->delete();
0 ignored issues
show
Bug introduced by
The method delete does only exist in Illuminate\Database\Eloq...Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Collection.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
177
            // Delete keywords assciated with the emoji
178
            Keyword::where('emoji_id', '=', $id)->delete();
179
180
            return $response->withJson(['status'], 204);
181
        }
182
183
        return $response->withStatus(404);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response->withStatus(404); (Psr\Http\Message\ResponseInterface) is incompatible with the return type documented by Laztopaz\EmojiRestfulAPI...Controller::deleteEmoji of type Laztopaz\EmojiRestfulAPI\json.

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...
184
    }
185
186
    /**
187
     * This method creates emoji keywords.
188
     *
189
     * @param $request
190
     * @param $response
191
     * @param $args
192
     *
193
     * @return $id
0 ignored issues
show
Documentation introduced by
The doc-type $id could not be parsed: Unknown type name "$id" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
194
     */
195 View Code Duplication
    public function createEmojiKeywords($emoji_id, $keywords)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
    {
197
        if ($keywords) {
198
            $splittedKeywords = explode(',', $keywords);
199
200
            $created_at = date('Y-m-d h:i:s');
201
202
            foreach ($splittedKeywords as $keyword) {
203
                $emojiKeyword = Keyword::create([
204
                        'emoji_id'     => $emoji_id,
205
                        'keyword_name' => $keyword,
206
                        'created_at'   => $created_at,
207
                ]);
208
            }
209
        }
210
211
        return $emojiKeyword->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Laztopaz\EmojiRestfulAPI\Keyword>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
The variable $emojiKeyword 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...
212
    }
213
214
    /**
215
     * This method format emoji result.
216
     *
217
     * @param $emojis
218
     *
219
     * @return array $emojis
220
     */
221
    public function formatEmoji(array $emojis)
222
    {
223
        foreach ($emojis as $key => &$value) {
224
            $value['created_by'] = $value['created_by']['firstname'].' '.$value['created_by']['lastname'];
225
            $value['category'] = $value['category']['category_name'];
226
            $value['keywords'] = array_map(function ($key) { return $key['keyword_name']; }, $value['keywords']);
227
        }
228
229
        return $emojis;
230
    }
231
232
    /**
233
     * This method authenticate and return user id.
234
     */
235
    public function getCurrentUserId($request, $response)
236
    {
237
        $loadEnv = DatabaseConnection::loadEnv();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $loadEnv is correct as \Laztopaz\EmojiRestfulAP...seConnection::loadEnv() (which targets Laztopaz\EmojiRestfulAPI...seConnection::loadEnv()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
$loadEnv is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
238
239
        $jwtoken = $request->getHeader('HTTP_AUTHORIZATION');
240
241
        try {
242
            if (isset($jwtoken)) {
243
                $secretKey = base64_decode(getenv('secret'));
244
245
                $jwt = json_decode($jwtoken[0], true);
246
247
                //decode the JWT using the key from config
248
                $decodedToken = JWT::decode($jwt['jwt'], $secretKey, ['HS512']);
249
250
                $tokenInfo = (array) $decodedToken;
251
252
                $userInfo = (array) $tokenInfo['dat'];
253
254
                return $userInfo['id'];
255
            }
256
        } catch (\Exception $e) {
257
            return $response->withJson(['status' => $e->getMessage()], 401);
258
        }
259
    }
260
}
261