Completed
Push — develop ( cd3b34...ba254b )
by greg
02:33
created

TradingCard::getModelMediaUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
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
    public function getModelPath($model)
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
    public function getModelMediaUrl($model)
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
            
56
            ErrorHandler::start();
57
            $data['upload_image']['name'] = $this->fileNewname(
58
                $path,
59
                $model->getId()."-".$data['upload_image']['name']
60
            );
61
            move_uploaded_file($data['upload_image']['tmp_name'], $path.$data['upload_image']['name']);
62
            $model->setImage($media_url.$data['upload_image']['name']);
63
            ErrorHandler::stop(true);
64
        }
65
66
        $this->getTradingCardModelMapper()->update($model);
67
        $this->getEventManager()->trigger(
68
            __FUNCTION__ .'.post',
69
            $this,
70
            array('model' => $model, 'data' => $data)
71
        );
72
73
        return $model;
74
    }
75
76
    public function getBooster($game, $user, $entry)
77
    {
78
        // get booster config from $game
79
        $em      = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
80
        $nb      = $game->getBoosterCardNumber();
81
        $booster = [];
82
83
        $today = new \DateTime("now");
84
        $today = $today->format('Y-m-d H:i:s');
85
86
        $qb  = $em->createQueryBuilder();
87
        $and = $qb->expr()->andx();
88
        $and->add(
89
            $qb->expr()->orX(
90
                $qb->expr()->lte('g.availability', ':date'),
91
                $qb->expr()->isNull('g.availability')
92
            )
93
        );
94
95
        $qb->setParameter('date', $today);
96
        $qb->select('g')
97
           ->from('PlaygroundGame\Entity\TradingCardModel', 'g')
98
           ->where($and);
99
100
        $query  = $qb->getQuery();
101
        $models = $query->getResult();
102
103
        shuffle($models);
104
105
        $eventModels = $this->getEventManager()->trigger(
106
            __FUNCTION__ .'.pre',
107
            $this,
108
            array(
109
                'game'   => $game,
110
                'user'   => $user,
111
                'entry'  => $entry,
112
                'models' => $models,
113
            )
114
        )->last();
115
116
        if ($eventModels) {
117
            $models = $eventModels;
118
        }
119
120
        for ($i = 0; $i < $nb; $i++) {
121
            $model = $models[$i];
122
            $card  = new \PlaygroundGame\Entity\TradingCardCard();
123
            $card->setUser($user);
124
            $card->setModel($model);
125
            $card->setGame($game);
126
            $card->setEntry($entry);
127
            $card = $this->getTradingCardCardMapper()->insert($card);
128
129
            $booster[] = $card;
130
        }
131
132
        $eventBooster = $this->getEventManager()->trigger(
133
            __FUNCTION__ .'.post',
134
            $this,
135
            array(
136
                'game'    => $game,
137
                'user'    => $user,
138
                'entry'   => $entry,
139
                'booster' => $booster,
140
            )
141
        )->last();
142
143
        if ($eventBooster) {
144
            $booster = $eventBooster;
145
        }
146
147
        // sending a booster represents an entry. We close the entry after that
148
        $entry->setActive(0);
149
        $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...
150
151
        return $booster;
152
    }
153
154
    public function getAlbum($game, $user)
155
    {
156
        // all the models of the album
157
        $models = $this->getTradingCardModelMapper()->findAll();
158
159
        $em = $this->serviceLocator->get('doctrine.entitymanager.orm_default');
160
        $qb = $em->createQueryBuilder();
161
        $and = $qb->expr()->andx();
162
        $and->add($qb->expr()->eq('g.id', ':game'));
163
        $and->add($qb->expr()->eq('u.id', ':user'));
164
        $qb->setParameter('game', $game);
165
        $qb->select('c')
166
            ->from('PlaygroundGame\Entity\TradingCardCard', 'c')
167
            ->innerJoin('c.game', 'g')
168
            ->innerJoin('c.model', 'm')
169
            ->leftJoin('c.user', 'u')
170
            ->where($and)
171
            ->orderBy('m.id', 'ASC')
172
            ->groupBy('c.model');
173
        if ($user) {
174
            $qb->setParameter('user', $user);
175
        } else {
176
            $qb->setParameter('user', null);
177
        }
178
        $query = $qb->getQuery();
179
180
        // all the cards of the user
181
        $cards = $query->getResult();
182
        $cardsArray = [];
183
        foreach ($cards as $card) {
184
            $cardsArray[$card->getModel()->getId()] = $card;
185
        }
186
187
        $album = [];
188
189
        // I create the complete album including the cards of the user
190
        foreach($models as $model) {
191
            $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...
192
            if(isset($cardsArray[$model->getId()])) {
193
                $sticker['card'] = $cardsArray[$model->getId()];
194
            } else {
195
                $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...
196
            }
197
            $album[] = $sticker;
198
        }
199
200
        return $album;
201
    }
202
203
    public function getAlbumOld($game, $user)
204
    {
205
        // get collection of cards from the user for this game
206
        $album      = $this->getTradingCardCardMapper()->findBy(
207
            array('game' => $game, 'user' => $user),
208
            array('createdAt' => 'ASC')
209
        );
210
        $eventAlbum = $this->getEventManager()->trigger(
211
            __FUNCTION__ .'.post',
212
            $this,
213
            array(
214
                'game'  => $game,
215
                'user'  => $user,
216
                'album' => $album,
217
            )
218
        )->last();
219
220
        if ($eventAlbum) {
221
            $album = $eventAlbum;
222
        }
223
224
        return $album;
225
    }
226
227
    public function getGameEntity()
228
    {
229
        return new \PlaygroundGame\Entity\TradingCard;
230
    }
231
232
    public function getTradingCardMapper()
233
    {
234
        if (null === $this->tradingcardMapper) {
235
            $this->tradingcardMapper = $this->serviceLocator->get('playgroundgame_tradingcard_mapper');
236
        }
237
238
        return $this->tradingcardMapper;
239
    }
240
241
    public function getTradingCardCardMapper()
242
    {
243
        if (null === $this->tradingcardcardMapper) {
244
            $this->tradingcardcardMapper = $this->serviceLocator->get('playgroundgame_tradingcard_card_mapper');
245
        }
246
247
        return $this->tradingcardcardMapper;
248
    }
249
250
    public function getTradingCardModelMapper()
251
    {
252
        if (null === $this->tradingcardmodelMapper) {
253
            $this->tradingcardmodelMapper = $this->serviceLocator->get('playgroundgame_tradingcard_model_mapper');
254
        }
255
256
        return $this->tradingcardmodelMapper;
257
    }
258
}
259