TradingCard::getModelPath()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 14

Duplication

Lines 14
Ratio 100 %

Importance

Changes 0
Metric Value
dl 14
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 4
nop 1
1
<?php
2
3
namespace PlaygroundGame\Service;
4
5
use Zend\Stdlib\ErrorHandler;
6
7
class TradingCard extends Game
8
{
9
    protected $tradingcardMapper;
10
    protected $tradingcardmodelMapper;
11
    protected $tradingcardcardMapper;
12
13 View Code Duplication
    public function getModelPath($model)
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...
14
    {
15
        $path = $this->getOptions()->getMediaPath().DIRECTORY_SEPARATOR;
16
        $path .= 'game'.$model->getGame()->getId().DIRECTORY_SEPARATOR;
17
        if (!is_dir($path)) {
18
            mkdir($path, 0777, true);
19
        }
20
        $path .= 'models'.DIRECTORY_SEPARATOR;
21
        if (!is_dir($path)) {
22
            mkdir($path, 0777, true);
23
        }
24
25
        return $path;
26
    }
27
28 View Code Duplication
    public function getModelMediaUrl($model)
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...
29
    {
30
        $media_url = $this->getOptions()->getMediaUrl().'/';
31
        $media_url .= 'game'.$model->getGame()->getId().'/models/';
32
33
        return $media_url;
34
    }
35
36
    /**
37
     * @param  array $data
38
     * @return \PlaygroundGame\Entity\Game
39
     */
40
    public function updateModel(array $data, $model)
41
    {
42
        $form        = $this->serviceLocator->get('playgroundgame_tradingcardmodel_form');
43
        $tradingcard = $this->getGameMapper()->findById($data['trading_card_id']);
44
        $model->setGame($tradingcard);
45
        $path      = $this->getModelPath($model);
46
        $media_url = $this->getModelMediaUrl($model);
47
48
        $form->bind($model);
49
        $form->setData($data);
50
51
        if (!$form->isValid()) {
52
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by PlaygroundGame\Service\TradingCard::updateModel of type PlaygroundGame\Entity\Game.

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...
53
        }
54 View Code Duplication
        if (!empty($data['upload_image']['tmp_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
55
            ErrorHandler::start();
56
            $data['upload_image']['name'] = $this->fileNewname(
57
                $path,
58
                $model->getId()."-".$data['upload_image']['name']
59
            );
60
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
61
            $model->setImage($media_url.$data['upload_image']['name']);
62
            ErrorHandler::stop(true);
63
        }
64
65
        $this->getTradingCardModelMapper()->update($model);
66
        $this->getEventManager()->trigger(
67
            __FUNCTION__ .'.post',
68
            $this,
69
            array('model' => $model, 'data' => $data)
70
        );
71
72
        return $model;
73
    }
74
75
    public function getBooster($game, $user, $entry)
76
    {
77
        // get booster config from $game
78
        $em      = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
79
        $nb      = $game->getBoosterCardNumber();
80
        $booster = [];
81
82
        $today = new \DateTime("now");
83
        $today = $today->format('Y-m-d H:i:s');
84
85
        $qb  = $em->createQueryBuilder();
86
        $and = $qb->expr()->andx();
87
        $and->add(
88
            $qb->expr()->orX(
89
                $qb->expr()->lte('g.availability', ':date'),
90
                $qb->expr()->isNull('g.availability')
91
            )
92
        );
93
94
        $qb->setParameter('date', $today);
95
        $qb->select('g')
96
           ->from('PlaygroundGame\Entity\TradingCardModel', 'g')
97
           ->where($and);
98
99
        $query  = $qb->getQuery();
100
        $models = $query->getResult();
101
102
        shuffle($models);
103
104
        $eventModels = $this->getEventManager()->trigger(
105
            __FUNCTION__ .'.pre',
106
            $this,
107
            array(
108
                'game'   => $game,
109
                'user'   => $user,
110
                'entry'  => $entry,
111
                'models' => $models,
112
            )
113
        )->last();
114
115
        if ($eventModels) {
116
            $models = $eventModels;
117
        }
118
119
        for ($i = 0; $i < $nb; $i++) {
120
            $model = $models[$i];
121
            $card  = new \PlaygroundGame\Entity\TradingCardCard();
122
            $card->setUser($user);
123
            $card->setModel($model);
124
            $card->setGame($game);
125
            $card->setEntry($entry);
126
            $card = $this->getTradingCardCardMapper()->insert($card);
127
128
            $booster[] = $card;
129
        }
130
131
        $eventBooster = $this->getEventManager()->trigger(
132
            __FUNCTION__ .'.post',
133
            $this,
134
            array(
135
                'game'    => $game,
136
                'user'    => $user,
137
                'entry'   => $entry,
138
                'booster' => $booster,
139
            )
140
        )->last();
141
142
        if ($eventBooster) {
143
            $booster = $eventBooster;
144
        }
145
146
        // sending a booster represents an entry. We close the entry after that
147
        $entry->setActive(0);
148
        $entry = $this->getEntryMapper()->update($entry);
0 ignored issues
show
Unused Code introduced by
$entry 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...
149
150
        return $booster;
151
    }
152
153
    public function getAlbum($game, $user)
154
    {
155
        // all the models of the album
156
        $models = $this->getTradingCardModelMapper()->findAll();
157
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
158
159
        if ($user) {
160
            $qb = $em->createQueryBuilder();
161
            $and = $qb->expr()->andx();
162
            $and->add($qb->expr()->eq('g.id', ':game'));
163
            $qb->setParameter('game', $game);
164
            $and->add($qb->expr()->eq('u.id', ':user'));
165
            $qb->setParameter('user', $user);
166
            $qb->select('c')
167
                ->from('PlaygroundGame\Entity\TradingCardCard', 'c')
168
                ->innerJoin('c.game', 'g')
169
                ->innerJoin('c.model', 'm')
170
                ->innerJoin('c.user', 'u')
171
                ->where($and)
172
                ->orderBy('m.id', 'ASC')
173
                ->groupBy('c.model');
174
            $query = $qb->getQuery();
175
        } elseif ($game->getAnonymousAllowed() && $this->getAnonymousIdentifier()) {
176
            $limitDate = $this->getLimitDate('always');
177
            $entries = $this->getEntryMapper()->findLastEntriesByAnonymousIdentifier(
178
                $game,
179
                $this->getAnonymousIdentifier(),
180
                $limitDate
181
            );
182
            $qb = $em->createQueryBuilder();
183
            $qb->andWhere('e.id IN (:entries)')->setParameter('entries', $entries);
184
            $qb->select('c')
185
                ->from('PlaygroundGame\Entity\TradingCardCard', 'c')
186
                ->innerJoin('c.model', 'm')
187
                ->innerJoin('c.game', 'g')
188
                ->innerJoin('c.entry', 'e')
189
                ->orderBy('m.id', 'ASC')
190
                ->groupBy('c.model');
191
            $query = $qb->getQuery();
192
        } elseif ($game->getAnonymousAllowed()) {
193
            $limitDate = $this->getLimitDate('always');
194
            $entries = $this->getEntryMapper()->findLastEntriesByIp(
195
                $game,
196
                $this->getIp(),
197
                $limitDate
198
            );
199
            $qb = $em->createQueryBuilder();
200
            $qb->andWhere('e.id IN (:entries)')->setParameter('entries', $entries);
201
            $qb->select('c')
202
                ->from('PlaygroundGame\Entity\TradingCardCard', 'c')
203
                ->innerJoin('c.model', 'm')
204
                ->innerJoin('c.game', 'g')
205
                ->innerJoin('c.entry', 'e')
206
                ->orderBy('m.id', 'ASC')
207
                ->groupBy('c.model');
208
            $query = $qb->getQuery();
209 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
210
            // If the game is supposed to be a regular user game or an anonymous identified game,
211
            // it means that the registration/login is at the end of the game
212
            if ((!$user &&  !$game->getAnonymousAllowed()) || ($game->getAnonymousAllowed() && $game->getAnonymousIdentifier())) {
213
                return 0;
214
            }
215
            return $this->getEntryMapper()->findLastEntriesByIp($game, $this->getIp(), $limitDate);
0 ignored issues
show
Bug introduced by
The variable $limitDate seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
216
        }
217
218
        
219
        // all the cards of the user
220
        $cards = $query->getResult();
221
        $cardsArray = [];
222
        foreach ($cards as $card) {
223
            $cardsArray[$card->getModel()->getId()] = $card;
224
        }
225
226
        $album = [];
227
228
        // I create the complete album including the cards of the user
229
        foreach ($models as $model) {
230
            $sticker['model'] = $model;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sticker was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sticker = 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...
231
            if (isset($cardsArray[$model->getId()])) {
232
                $sticker['card'] = $cardsArray[$model->getId()];
233
            } else {
234
                $sticker['card'] = null;
0 ignored issues
show
Bug introduced by
The variable $sticker 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...
235
            }
236
            $album[] = $sticker;
237
        }
238
239
        return $album;
240
    }
241
242
    public function getGameEntity()
243
    {
244
        return new \PlaygroundGame\Entity\TradingCard;
245
    }
246
247
    public function getTradingCardMapper()
248
    {
249
        if (null === $this->tradingcardMapper) {
250
            $this->tradingcardMapper = $this->serviceLocator->get('playgroundgame_tradingcard_mapper');
251
        }
252
253
        return $this->tradingcardMapper;
254
    }
255
256
    public function getTradingCardCardMapper()
257
    {
258
        if (null === $this->tradingcardcardMapper) {
259
            $this->tradingcardcardMapper = $this->serviceLocator->get('playgroundgame_tradingcard_card_mapper');
260
        }
261
262
        return $this->tradingcardcardMapper;
263
    }
264
265
    public function getTradingCardModelMapper()
266
    {
267
        if (null === $this->tradingcardmodelMapper) {
268
            $this->tradingcardmodelMapper = $this->serviceLocator->get('playgroundgame_tradingcard_model_mapper');
269
        }
270
271
        return $this->tradingcardmodelMapper;
272
    }
273
}
274