Completed
Push — master ( d9360b...ee19ca )
by Rémi
02:52
created

GameResultHandler::getLanguage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace MiniGameMessageApp\Handler;
4
5
use League\Event\EventInterface;
6
use MessageApp\Finder\MessageFinder;
7
use MessageApp\Listener\MessageEventHandler;
8
use MessageApp\Message\DefaultMessage;
9
use MessageApp\Message\Sender\MessageSender;
10
use MessageApp\User\ApplicationUser;
11
use MessageApp\User\Finder\ContextUserFinder;
12
use MessageApp\User\UndefinedApplicationUser;
13
use MiniGame\Entity\PlayerId;
14
use MiniGame\GameResult;
15
use MiniGame\Result\AllPlayersResult;
16
use MiniGameMessageApp\Message\MiniGameMessageExtractor;
17
use MiniGameMessageApp\ReadModel\Finder\MiniGameUserFinder;
18
use Psr\Log\LoggerAwareInterface;
19
use Psr\Log\LoggerAwareTrait;
20
use Psr\Log\NullLogger;
21
use RemiSan\Context\Context;
22
23
class GameResultHandler implements MessageEventHandler, LoggerAwareInterface
24
{
25
    use LoggerAwareTrait;
26
27
    /**
28
     * @var MiniGameUserFinder
29
     */
30
    private $userFinder;
31
32
    /**
33
     * @var ContextUserFinder
34
     */
35
    private $contextUserFinder;
36
37
    /**
38
     * @var MessageFinder
39
     */
40
    private $messageFinder;
41
42
    /**
43
     * @var MessageSender
44
     */
45
    private $messageSender;
46
47
    /**
48
     * @var MiniGameMessageExtractor
49
     */
50
    private $extractor;
51
52
    /**
53
     * Constructor
54
     *
55
     * @param MiniGameUserFinder       $userFinder
56
     * @param ContextUserFinder        $contextUserFinder
57
     * @param MessageFinder            $messageFinder
58
     * @param MessageSender            $messageSender
59
     * @param MiniGameMessageExtractor $extractor
60 18
     */
61
    public function __construct(
62
        MiniGameUserFinder $userFinder,
63
        ContextUserFinder $contextUserFinder,
64
        MessageFinder $messageFinder,
65
        MessageSender $messageSender,
66
        MiniGameMessageExtractor $extractor
67 18
    ) {
68 18
        $this->userFinder = $userFinder;
69 18
        $this->contextUserFinder = $contextUserFinder;
70 18
        $this->messageFinder = $messageFinder;
71 18
        $this->messageSender = $messageSender;
72 18
        $this->extractor = $extractor;
73 18
        $this->logger = new NullLogger();
74
    }
75
76
    /**
77
     * Handle an event.
78
     *
79
     * @param EventInterface $event
80
     * @param Context        $context
81
     *
82
     * @return void
83 18
     */
84
    public function handle(EventInterface $event, Context $context = null)
85 18
    {
86 3
        if (! $event instanceof GameResult) {
87
            return;
88
        }
89 15
90
        $this->logger->info(sprintf('Send message after "%s"', $event->getName()));
91 15
        $messageContext = $this->getMessageContext($context);
92
93 15
        if ($event instanceof AllPlayersResult) {
94 3
            $users = $this->userFinder->getByGameId($event->getGameId());
95 3
        } else {
96 3
            $users = [ $this->getUser($event->getPlayerId(), $messageContext) ];
97 3
        }
98 2
99
        $this->sendMessage($event, $users, $messageContext);
0 ignored issues
show
Documentation introduced by
$users is of type array<integer,object<Mes...\ApplicationUser>|null>, but the function expects a array<integer,object<Mes...\User\ApplicationUser>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100 2
    }
101 2
102 2
    /**
103 12
     * @param  GameResult        $gameResult
104 9
     * @param  ApplicationUser[] $users
105 9
     * @param  mixed             $messageContext
106 6
     * @return void
107 9
     */
108 6
    private function sendMessage(GameResult $gameResult, array $users = array(), $messageContext = null)
109 6
    {
110
        $filteredUsers = self::filterUsers($users);
111 6
112
        if (count($filteredUsers) === 0) {
113 12
            return;
114
        }
115
116
        $message = new DefaultMessage(
117
            $filteredUsers,
0 ignored issues
show
Documentation introduced by
$filteredUsers is of type array<integer,object<Mes...\User\ApplicationUser>>, but the function expects a object<MessageApp\User\ApplicationUser>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
118
            $this->extractor->extractMessage(
119
                $gameResult,
120
                self::getLanguage($filteredUsers)
121 12
            )
122
        );
123 12
        $this->messageSender->send($message, $messageContext);
124 3
    }
125
126
    /**
127 9
     * @param  ApplicationUser[] $users
128 9
     * @return ApplicationUser[]
129 9
     */
130
    private static function filterUsers(array $users)
131
    {
132
        return array_unique(
133
            array_filter($users, function (ApplicationUser $user = null) {
134
                return $user !== null && !$user instanceof UndefinedApplicationUser;
135 15
            })
136
        );
137 15
    }
138 9
139
    /**
140
     * @param  ApplicationUser[] $users
141 6
     * @return string
142 6
     */
143
    private static function getLanguage(array $users)
144
    {
145
        return $users[0]->getPreferredLanguage(); // TODO add better language management
146
    }
147
148
    /**
149
     * @param  Context $context
150 12
     * @return mixed
151
     */
152
    private function getMessageContext(Context $context = null)
153 12
    {
154 12
        if (!$context) {
155 9
            return null;
156 9
        }
157 9
158 6
        $message = $this->messageFinder->findByReference($context->getValue());
159 3
        return ($message) ? $message->getSource() : null;
160 3
    }
161
162 3
    /**
163
     * @param  PlayerId $playerId
164 2
     * @param  mixed    $contextMessage
165
     * @return ApplicationUser
166 6
     */
167
    private function getUser(PlayerId $playerId = null, $contextMessage = null)
168
    {
169
        // Build message
170
        $user = $this->getUserByPlayerId($playerId);
171
        if (!$user) {
172
            $this->logger->debug('Try to get user by context message');
173 12
            $user = $this->getUserByContext($contextMessage);
174
            if (!$user) {
175 12
                if (!$playerId) {
176
                    $this->logger->debug('No user was found');
177
                    return null;
178
                }
179
                throw new \InvalidArgumentException('User not found!');
180
            }
181
        }
182 9
183
        return $user;
184 9
    }
185 3
186 3
    /**
187
     * @param  PlayerId $id
188
     * @return ApplicationUser
189 6
     */
190
    private function getUserByPlayerId(PlayerId $id = null)
191
    {
192
        return ($id) ? $this->userFinder->getByPlayerId($id) : null;
193
    }
194
195
    /**
196
     * @param  mixed $contextMessage
197
     * @return ApplicationUser
198
     */
199
    private function getUserByContext($contextMessage = null)
200
    {
201
        if (!$contextMessage) {
202
            $this->logger->debug('No context message to retrieve user from');
203
            return null;
204
        };
205
206
        return $this->contextUserFinder->getUserByContextMessage($contextMessage);
207
    }
208
}
209