Passed
Push — dev ( 231d4b...6ea563 )
by Janko
101:30 queued 71:11
created

getSingleSpacecraftScannerResults()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 67
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 56
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 67
ccs 22
cts 22
cp 1
crap 2
rs 8.9599

2 Methods

Rating   Name   Duplication   Size   Complexity  
A ShipRepository::getEscapePods() 0 15 1
A ShipRepository::getWithTradeLicensePayment() 0 21 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Orm\Repository;
6
7
use Doctrine\ORM\EntityRepository;
8
use Doctrine\ORM\Query\ResultSetMapping;
9
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Stu\Component\Game\TimeConstants;
0 ignored issues
show
Bug introduced by
The type Stu\Component\Game\TimeConstants was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Stu\Component\Spacecraft\SpacecraftRumpEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Component\Spacecraft\SpacecraftRumpEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Stu\Component\Spacecraft\SpacecraftStateEnum;
13
use Stu\Component\Spacecraft\System\SpacecraftSystemModeEnum;
14
use Stu\Component\Spacecraft\System\SpacecraftSystemTypeEnum;
15
use Stu\Module\PlayerSetting\Lib\UserEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Module\PlayerSetting\Lib\UserEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Stu\Module\Ship\Lib\TFleetShipItem;
17
use Stu\Orm\Entity\Location;
18
use Stu\Orm\Entity\LocationInterface;
19
use Stu\Orm\Entity\MapInterface;
20
use Stu\Orm\Entity\PirateWrath;
21
use Stu\Orm\Entity\Ship;
22
use Stu\Orm\Entity\CrewAssignment;
23
use Stu\Orm\Entity\ShipInterface;
24
use Stu\Orm\Entity\SpacecraftRump;
25
use Stu\Orm\Entity\SpacecraftRumpInterface;
26
use Stu\Orm\Entity\Spacecraft;
27
use Stu\Orm\Entity\SpacecraftInterface;
28
use Stu\Orm\Entity\StarSystemMapInterface;
29
use Stu\Orm\Entity\Storage;
30
use Stu\Orm\Entity\User;
31
use Stu\Orm\Entity\UserInterface;
32
33
/**
34
 * @extends EntityRepository<Ship>
35
 */
36
final class ShipRepository extends EntityRepository implements ShipRepositoryInterface
37
{
38
    #[Override]
39
    public function save(ShipInterface $post): void
40
    {
41
        $em = $this->getEntityManager();
42
43
        $em->persist($post);
44
    }
45
46
    #[Override]
47
    public function delete(ShipInterface $post): void
48
    {
49
        $em = $this->getEntityManager();
50
51
        $em->remove($post);
52
    }
53
54 2
    #[Override]
55
    public function getByUserAndFleet(int $userId, ?int $fleetId): array
56
    {
57 2
        return $this->findBy(
58 2
            [
59 2
                'user_id' => $userId,
60 2
                'fleet_id' => $fleetId
61 2
            ],
62 2
            ['id' => 'asc']
63 2
        );
64
    }
65
66 1
    #[Override]
67
    public function getByLocationAndUser(LocationInterface $location, UserInterface $user): array
68
    {
69 1
        return $this->findBy([
70 1
            'user' => $user,
71 1
            'location' => $location,
72 1
        ], [
73 1
            'fleet_id' => 'desc',
74 1
            'is_fleet_leader' => 'desc',
75 1
            'id' => 'desc'
76 1
        ]);
77
    }
78
79 1
    #[Override]
80
    public function getPossibleFleetMembers(ShipInterface $fleetLeader): iterable
81
    {
82 1
        return $this->getEntityManager()->createQuery(
83 1
            sprintf(
84 1
                'SELECT s FROM %s s
85
                JOIN %s sp
86
                WITH s.id = sp.id
87
                WHERE sp.location = :location
88
                AND s.fleet_id IS NULL
89
                AND sp.user = :user
90
                AND sp.state != :state
91 1
                ORDER BY sp.rump_id ASC, sp.name ASC',
92 1
                Ship::class,
93 1
                Spacecraft::class
94 1
            )
95 1
        )->setParameters([
96 1
            'location' => $fleetLeader->getLocation(),
97 1
            'state' => SpacecraftStateEnum::SHIP_STATE_RETROFIT,
98 1
            'user' => $fleetLeader->getUser()
99 1
        ])->getResult();
100
    }
101
102
    #[Override]
103
    public function getWithTradeLicensePayment(
104
        int $userId,
105
        int $tradePostShipId,
106
        int $commodityId,
107
        int $amount
108
    ): iterable {
109
        return $this->getEntityManager()->createQuery(
110
            sprintf(
111
                'SELECT s FROM %s s WHERE s.user_id = :userId AND s.docked_to_id = :tradePostShipId AND s.id IN (
112
                    SELECT st.spacecraft_id FROM %s st WHERE st.commodity_id = :commodityId AND st.count >= :amount
113
                )',
114
                Ship::class,
115
                Storage::class
116
            )
117
        )->setParameters([
118
            'userId' => $userId,
119
            'tradePostShipId' => $tradePostShipId,
120
            'commodityId' => $commodityId,
121
            'amount' => $amount,
122
        ])->getResult();
123
    }
124
125
    #[Override]
126
    public function getEscapePods(): array
127
    {
128
        return $this->getEntityManager()->createQuery(
129
            sprintf(
130
                'SELECT s FROM %s s
131
                LEFT JOIN %s sr
132
                WITH s.rump_id = sr.id
133
                WHERE sr.category_id = :categoryId',
134
                Ship::class,
135
                SpacecraftRump::class
136
            )
137
        )->setParameters([
138
            'categoryId' => SpacecraftRumpEnum::SHIP_CATEGORY_ESCAPE_PODS
139
        ])->getResult();
140
    }
141
142
    #[Override]
143
    public function getEscapePodsByCrewOwner(int $userId): array
144
    {
145
        return $this->getEntityManager()->createQuery(
146
            sprintf(
147
                'SELECT s FROM %s s
148
                LEFT JOIN %s sr
149
                WITH s.rump_id = sr.id
150
                LEFT JOIN %s sc
151
                WITH sc.spacecraft_id = s.id
152
                WHERE sr.category_id = :categoryId
153
                AND sc.user_id = :userId',
154
                Ship::class,
155
                SpacecraftRump::class,
156
                CrewAssignment::class
157
            )
158
        )->setParameters([
159
            'categoryId' => SpacecraftRumpEnum::SHIP_CATEGORY_ESCAPE_PODS,
160
            'userId' => $userId
161
        ])->getResult();
162
    }
163
164 1
    #[Override]
165
    public function getFleetShipsScannerResults(
166
        SpacecraftInterface $spacecraft,
167
        bool $showCloaked = false,
168
        MapInterface|StarSystemMapInterface|null $field = null
169
    ): array {
170
171 1
        $rsm = new ResultSetMapping();
172 1
        $rsm->addEntityResult(TFleetShipItem::class, 's');
173 1
        $rsm->addFieldResult('s', 'fleetname', 'fleet_name');
174 1
        $rsm->addFieldResult('s', 'isdefending', 'is_defending');
175 1
        $rsm->addFieldResult('s', 'isblocking', 'is_blocking');
176 1
        TFleetShipItem::addTSpacecraftItemFields($rsm);
177
178 1
        $location = $field ?? $spacecraft->getLocation();
179
180 1
        $query = $this->getEntityManager()->createNativeQuery(
181 1
            sprintf(
182 1
                'SELECT f.id as fleetid, f.name as fleetname, f.defended_colony_id is not null as isdefending,
183
                    f.blocked_colony_id is not null as isblocking, s.id as shipid, sp.rump_id as rumpid,
184
                    ss.mode as warpstate, twd.mode as tractorwarpstate, COALESCE(ss2.mode,0) as cloakstate, ss3.mode as shieldstate,
185
                    COALESCE(ss4.status,0) as uplinkstate, sp.type as spacecrafttype, sp.name as shipname,
186
                    sp.huelle as hull, sp.max_huelle as maxhull, sp.schilde as shield, sp.holding_web_id as webid, tw.finished_time as webfinishtime,
187
                    u.id as userid, u.username, r.category_id as rumpcategoryid, r.name as rumpname, r.role_id as rumproleid,
188
                    (SELECT count(*) > 0 FROM stu_ship_log sl WHERE sl.spacecraft_id = s.id AND sl.is_private = :false) as haslogbook,
189
                    (SELECT count(*) > 0 FROM stu_crew_assign ca WHERE ca.spacecraft_id = s.id) as hascrew
190
                FROM stu_ship s
191
                JOIN stu_spacecraft sp
192
                ON s.id = sp.id
193
                LEFT JOIN stu_spacecraft_system ss
194
                ON s.id = ss.spacecraft_id
195
                AND ss.system_type = :warpdriveType
196
                LEFT JOIN stu_spacecraft tractor
197
                ON tractor.tractored_ship_id = s.id
198
                LEFT JOIN stu_spacecraft_system twd
199
                ON tractor.id = twd.spacecraft_id
200
                AND twd.system_type = :warpdriveType
201
                LEFT JOIN stu_spacecraft_system ss2
202
                ON s.id = ss2.spacecraft_id
203
                AND ss2.system_type = :cloakType
204
                LEFT JOIN stu_spacecraft_system ss3
205
                ON s.id = ss3.spacecraft_id
206
                AND ss3.system_type = :shieldType
207
                LEFT JOIN stu_spacecraft_system ss4
208
                ON s.id = ss4.spacecraft_id
209
                AND ss4.system_type = :uplinkType
210
                JOIN stu_rump r
211
                ON sp.rump_id = r.id
212
                JOIN stu_fleets f
213
                ON s.fleet_id = f.id
214
                LEFT OUTER JOIN stu_tholian_web tw
215
                ON sp.holding_web_id = tw.id
216
                JOIN stu_user u
217
                ON sp.user_id = u.id
218
                WHERE sp.location_id = :locationId
219
                AND s.id != :ignoreId
220
                %s
221 1
                ORDER BY f.sort DESC, f.id DESC, (CASE WHEN s.is_fleet_leader THEN 0 ELSE 1 END), r.category_id ASC, r.role_id ASC, r.id ASC, sp.name ASC',
222 1
                $showCloaked ? '' : sprintf(' AND (sp.user_id = %d OR COALESCE(ss2.mode,0) < %d) ', $spacecraft->getUser()->getId(), SpacecraftSystemModeEnum::MODE_ON->value)
223 1
            ),
224 1
            $rsm
225 1
        )->setParameters([
226 1
            'locationId' => $location->getId(),
0 ignored issues
show
Bug introduced by
The method getId() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

226
            'locationId' => $location->/** @scrutinizer ignore-call */ getId(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
227 1
            'ignoreId' => $spacecraft->getId(),
228 1
            'cloakType' => SpacecraftSystemTypeEnum::CLOAK->value,
229 1
            'warpdriveType' => SpacecraftSystemTypeEnum::WARPDRIVE->value,
230 1
            'shieldType' => SpacecraftSystemTypeEnum::SHIELDS->value,
231 1
            'uplinkType' => SpacecraftSystemTypeEnum::UPLINK->value,
232 1
            'false' => false
233 1
        ]);
234
235 1
        return $query->getResult();
236
    }
237
238
    #[Override]
239
    public function getAllDockedShips(): array
240
    {
241
        return $this->getEntityManager()->createQuery(
242
            sprintf(
243
                'SELECT s FROM %s s
244
                WHERE s.docked_to_id IS NOT NULL',
245
                Ship::class
246
            )
247
        )->getResult();
248
    }
249
250
    #[Override]
251
    public function getPirateTargets(ShipInterface $ship): array
252
    {
253
        $layer = $ship->getLayer();
254
        if ($layer === null) {
255
            return [];
256
        }
257
258
        $location = $ship->getLocation();
259
        $range = $ship->getSensorRange() * 2;
260
261
        return $this->getEntityManager()->createQuery(
262
            sprintf(
263
                'SELECT s FROM %s s
264
                JOIN %s l
265
                WITH s.location = l.id
266
                JOIN %s u
267
                WITH s.user_id = u.id
268
                LEFT JOIN %s w
269
                WITH u.id = w.user_id
270
                WHERE l.layer_id = :layerId
271
                AND l.cx BETWEEN :minX AND :maxX
272
                AND l.cy BETWEEN :minY AND :maxY
273
                AND (s.fleet_id IS NULL OR s.is_fleet_leader = :true)
274
                AND u.id >= :firstUserId
275
                AND u.state >= :stateActive
276
                AND u.creation < :eightWeeksEarlier
277
                AND (u.vac_active = :false OR u.vac_request_date > :vacationThreshold)
278
                AND COALESCE(w.protection_timeout, 0) < :currentTime',
279
                Ship::class,
280
                Location::class,
281
                User::class,
282
                PirateWrath::class
283
            )
284
        )
285
            ->setParameters([
286
                'minX' => $location->getCx() - $range,
287
                'maxX' => $location->getCx() + $range,
288
                'minY' => $location->getCy() - $range,
289
                'maxY' => $location->getCy() + $range,
290
                'layerId' => $layer->getId(),
291
                'firstUserId' => UserEnum::USER_FIRST_ID,
292
                'stateActive' => UserEnum::USER_STATE_ACTIVE,
293
                'eightWeeksEarlier' => time() - TimeConstants::EIGHT_WEEKS_IN_SECONDS,
294
                'vacationThreshold' => time() - UserEnum::VACATION_DELAY_IN_SECONDS,
295
                'currentTime' => time(),
296
                'true' => true,
297
                'false' => false
298
            ])
299
            ->getResult();
300
    }
301
302
    #[Override]
303
    public function getPirateFriends(ShipInterface $ship): array
304
    {
305
        $layer = $ship->getLayer();
306
        if ($layer === null) {
307
            return [];
308
        }
309
310
        $location = $ship->getLocation();
311
        $range = $ship->getSensorRange() * 3;
312
313
        return $this->getEntityManager()->createQuery(
314
            sprintf(
315
                'SELECT s FROM %s s
316
                JOIN %s l
317
                WITH s.location_id = l.id
318
                WHERE l.layer_id = :layerId
319
                AND l.cx BETWEEN :minX AND :maxX
320
                AND l.cy BETWEEN :minY AND :maxY
321
                AND s.id != :shipId
322
                AND s.user_id = :kazonUserId',
323
                Ship::class,
324
                Location::class
325
            )
326
        )
327
            ->setParameters([
328
                'minX' => $location->getCx() - $range,
329
                'maxX' => $location->getCx() + $range,
330
                'minY' => $location->getCy() - $range,
331
                'maxY' => $location->getCy() + $range,
332
                'layerId' => $layer->getId(),
333
                'shipId' => $ship->getId(),
334
                'kazonUserId' => UserEnum::USER_NPC_KAZON
335
            ])
336
            ->getResult();
337
    }
338
339 1
    #[Override]
340
    public function getByUserAndRump(UserInterface $user, SpacecraftRumpInterface $rump): array
341
    {
342 1
        return $this->findBy([
343 1
            'user_id' => $user->getId(),
344 1
            'rump_id' => $rump->getId()
345 1
        ], [
346 1
            'location_id' => 'asc',
347 1
            'fleet_id' => 'asc',
348 1
            'is_fleet_leader' => 'desc'
349 1
        ]);
350
    }
351
}
352