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

getSingleSpacecraftScannerResults()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 69
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 58
nc 1
nop 3
dl 0
loc 69
ccs 23
cts 23
cp 1
crap 2
rs 8.9163
c 0
b 0
f 0

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\Anomaly\Type\AnomalyTypeEnum;
11
use Stu\Component\Spacecraft\SpacecraftStateEnum;
12
use Stu\Component\Spacecraft\SpacecraftTypeEnum;
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\Module\Ship\Lib\TShipItem;
18
use Stu\Module\Spacecraft\Lib\ShipRumpSpecialAbilityEnum;
0 ignored issues
show
Bug introduced by
The type Stu\Module\Spacecraft\Li...pRumpSpecialAbilityEnum 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...
19
use Stu\Orm\Entity\Anomaly;
20
use Stu\Orm\Entity\SpacecraftBuildplan;
21
use Stu\Orm\Entity\CrewAssignment;
22
use Stu\Orm\Entity\MapInterface;
23
use Stu\Orm\Entity\ShipRumpSpecial;
24
use Stu\Orm\Entity\Spacecraft;
25
use Stu\Orm\Entity\SpacecraftInterface;
26
use Stu\Orm\Entity\SpacecraftSystem;
27
use Stu\Orm\Entity\StarSystemMapInterface;
28
use Stu\Orm\Entity\User;
29
use Stu\Orm\Entity\UserInterface;
30
31
/**
32
 * @extends EntityRepository<Spacecraft>
33
 */
34
final class SpacecraftRepository extends EntityRepository implements SpacecraftRepositoryInterface
35
{
36
    #[Override]
37
    public function save(SpacecraftInterface $spacecraft): void
38
    {
39
        $em = $this->getEntityManager();
40
41
        $em->persist($spacecraft);
42
    }
43
44
    #[Override]
45
    public function delete(SpacecraftInterface $spacecraft): void
46
    {
47
        $em = $this->getEntityManager();
48
49
        $em->remove($spacecraft);
50
    }
51
52
    #[Override]
53
    public function getAmountByUserAndSpecialAbility(
54
        int $userId,
55
        int $specialAbilityId
56
    ): int {
57
        return (int) $this->getEntityManager()->createQuery(
58
            sprintf(
59
                'SELECT COUNT(s)
60
                FROM %s s
61
                JOIN %s bp
62
                WITH s.plan_id = bp.id
63
                WHERE s.user_id = :userId AND s.rump_id IN (
64
                    SELECT rs.rump_id FROM %s rs WHERE rs.special = :specialAbilityId
65
                )
66
                %s',
67
                Spacecraft::class,
68
                SpacecraftBuildplan::class,
69
                ShipRumpSpecial::class,
70
                $specialAbilityId === ShipRumpSpecialAbilityEnum::COLONIZE ? 'AND bp.crew = 0' : ''
71
            )
72
        )->setParameters([
73
            'userId' => $userId,
74
            'specialAbilityId' => $specialAbilityId,
75
        ])->getSingleScalarResult();
76
    }
77
78
    #[Override]
79
    public function getAmountByUserAndRump(int $userId, int $rumpId): int
80
    {
81
        return $this->count([
82
            'user_id' => $userId,
83
            'rump_id' => $rumpId,
84
        ]);
85
    }
86
87
    #[Override]
88
    public function getByUser(UserInterface $user): array
89
    {
90
        return $this->findBy([
91
            'user_id' => $user,
92
        ]);
93
    }
94
95
    #[Override]
96
    public function getSuitableForShieldRegeneration(int $regenerationThreshold): array
97
    {
98
        return $this->getEntityManager()->createQuery(
99
            sprintf(
100
                'SELECT s FROM %s s
101
                JOIN %s ss
102
                WITH s.id = ss.spacecraft_id
103
                JOIN %s bp
104
                WITH s.plan_id = bp.id
105
                WHERE ss.system_type = :shieldType
106
                AND ss.mode < :modeOn
107
                AND s.schilde<s.max_schilde
108
                AND s.shield_regeneration_timer <= :regenerationThreshold
109
                AND (SELECT count(sc.id) FROM %s sc WHERE s.id = sc.spacecraft_id) >= bp.crew
110
                AND NOT EXISTS (SELECT a FROM %s a
111
                                WHERE a.location_id = s.location_id
112
                                AND a.anomaly_type_id = :anomalyType
113
                                AND a.remaining_ticks > 0)',
114
                Spacecraft::class,
115
                SpacecraftSystem::class,
116
                SpacecraftBuildplan::class,
117
                CrewAssignment::class,
118
                Anomaly::class
119
            )
120
        )->setParameters([
121
            'shieldType' => SpacecraftSystemTypeEnum::SHIELDS->value,
122
            'modeOn' => SpacecraftSystemModeEnum::MODE_ON->value,
123
            'regenerationThreshold' => $regenerationThreshold,
124
            'anomalyType' => AnomalyTypeEnum::SUBSPACE_ELLIPSE
125
        ])->getResult();
126
    }
127
128
    #[Override]
129
    public function getPlayerSpacecraftsForTick(): iterable
130
    {
131
        return $this->getEntityManager()->createQuery(
132
            sprintf(
133
                'SELECT s
134
                FROM %s s
135
                JOIN %s p
136
                WITH s.plan_id = p.id
137
                JOIN %s u
138
                WITH s.user_id = u.id
139
                WHERE s.user_id > :firstUserId
140
                AND (   ((SELECT count(sc.id)
141
                        FROM %s sc
142
                        WHERE sc.spacecraft_id = s.id) > 0)
143
                    OR
144
                        (s.state IN (:scrapping, :underConstruction))
145
                    OR
146
                        (p.crew = 0))
147
                AND (u.vac_active = :false OR u.vac_request_date > :vacationThreshold)',
148
                Spacecraft::class,
149
                SpacecraftBuildplan::class,
150
                User::class,
151
                CrewAssignment::class
152
            )
153
        )->setParameters([
154
            'underConstruction' => SpacecraftStateEnum::SHIP_STATE_UNDER_CONSTRUCTION,
155
            'scrapping' => SpacecraftStateEnum::SHIP_STATE_UNDER_SCRAPPING,
156
            'vacationThreshold' => time() - UserEnum::VACATION_DELAY_IN_SECONDS,
157
            'firstUserId' => UserEnum::USER_FIRST_ID,
158
            'false' => false
159
        ])->toIterable();
160
    }
161
162
    #[Override]
163
    public function getNpcSpacecraftsForTick(): array
164
    {
165
        return $this->getEntityManager()->createQuery(
166
            sprintf(
167
                'SELECT s FROM %s s WHERE s.user_id BETWEEN 2 AND (:firstUserId - 1)',
168
                Spacecraft::class
169
            )
170
        )->setParameter('firstUserId', UserEnum::USER_FIRST_ID)->getResult();
171
    }
172
173
    #[Override]
174
    public function isCloakedSpacecraftAtLocation(
175
        SpacecraftInterface $spacecraft
176
    ): bool {
177
178
        $result = $this->getEntityManager()->createQuery(
179
            sprintf(
180
                'SELECT COUNT(s.id) FROM %s s
181
                    WHERE s.location = :location
182
                    AND EXISTS (SELECT ss.id
183
                            FROM %s ss
184
                            WHERE s = ss.spacecraft
185
                            AND ss.system_type = %d
186
                            AND ss.mode > 1)
187
                    AND s.user != :ignoreUser',
188
                Spacecraft::class,
189
                SpacecraftSystem::class,
190
                SpacecraftSystemTypeEnum::CLOAK->value
191
            )
192
        )->setParameters([
193
            'location' => $spacecraft->getLocation(),
194
            'ignoreUser' => $spacecraft->getUser()
195
        ])->getSingleScalarResult();
196
197
        return $result > 0;
198
    }
199
200 1
    #[Override]
201
    public function getSingleSpacecraftScannerResults(
202
        SpacecraftInterface $spacecraft,
203
        bool $showCloaked = false,
204
        MapInterface|StarSystemMapInterface|null $field = null
205
    ): array {
206
207 1
        $rsm = new ResultSetMapping();
208 1
        $rsm->addEntityResult(TShipItem::class, 's');
209 1
        TFleetShipItem::addTSpacecraftItemFields($rsm);
210
211 1
        $location = $field ?? $spacecraft->getLocation();
212
213 1
        $query = $this->getEntityManager()->createNativeQuery(
214 1
            sprintf(
215 1
                'SELECT sp.id as shipid, s.fleet_id as fleetid, sp.rump_id as rumpid , ss.mode as warpstate,
216
                    twd.mode as tractorwarpstate, COALESCE(ss2.mode,0) as cloakstate, ss3.mode as shieldstate, COALESCE(ss4.status,0) as uplinkstate,
217
                    sp.type as spacecrafttype, sp.name as shipname, sp.huelle as hull, sp.max_huelle as maxhull,
218
                    sp.schilde as shield, sp.holding_web_id as webid, tw.finished_time as webfinishtime, u.id as userid, u.username,
219
                    r.category_id as rumpcategoryid, r.name as rumpname, r.role_id as rumproleid,
220
                    (SELECT count(*) > 0 FROM stu_ship_log sl WHERE sl.spacecraft_id = sp.id AND sl.is_private = :false) as haslogbook,
221
                    (SELECT count(*) > 0 FROM stu_crew_assign ca WHERE ca.spacecraft_id = sp.id) as hascrew
222
                FROM stu_spacecraft sp
223
                LEFT JOIN stu_ship s
224
                ON s.id = sp.id
225
                LEFT JOIN stu_spacecraft_system ss
226
                ON sp.id = ss.spacecraft_id
227
                AND ss.system_type = :warpdriveType
228
                LEFT JOIN stu_spacecraft tractor
229
                ON tractor.tractored_ship_id = s.id
230
                LEFT JOIN stu_spacecraft_system twd
231
                ON tractor.id = twd.spacecraft_id
232
                AND twd.system_type = :warpdriveType
233
                LEFT JOIN stu_spacecraft_system ss2
234
                ON sp.id = ss2.spacecraft_id
235
                AND ss2.system_type = :cloakType
236
                LEFT JOIN stu_spacecraft_system ss3
237
                ON sp.id = ss3.spacecraft_id
238
                AND ss3.system_type = :shieldType
239
                LEFT JOIN stu_spacecraft_system ss4
240
                ON sp.id = ss4.spacecraft_id
241
                AND ss4.system_type = :uplinkType
242
                JOIN stu_rump r
243
                ON sp.rump_id = r.id
244
                LEFT OUTER JOIN stu_tholian_web tw
245
                ON sp.holding_web_id = tw.id
246
                JOIN stu_user u
247
                ON sp.user_id = u.id
248
                WHERE sp.location_id = :locationId
249
                AND sp.id != :ignoreId
250
                AND s.fleet_id IS NULL
251
                AND sp.type != :stationType
252
                %s
253 1
                ORDER BY r.category_id ASC, r.role_id ASC, r.id ASC, sp.name ASC',
254 1
                $showCloaked ? '' : sprintf(' AND (sp.user_id = %d OR COALESCE(ss2.mode,0) < %d) ', $spacecraft->getUser()->getId(), SpacecraftSystemModeEnum::MODE_ON->value)
255 1
            ),
256 1
            $rsm
257 1
        )->setParameters([
258 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

258
            '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...
259 1
            'ignoreId' => $spacecraft->getId(),
260 1
            'cloakType' => SpacecraftSystemTypeEnum::CLOAK->value,
261 1
            'warpdriveType' => SpacecraftSystemTypeEnum::WARPDRIVE->value,
262 1
            'shieldType' => SpacecraftSystemTypeEnum::SHIELDS->value,
263 1
            'uplinkType' => SpacecraftSystemTypeEnum::UPLINK->value,
264 1
            'false' => false,
265 1
            'stationType' => SpacecraftTypeEnum::STATION->value
266 1
        ]);
267
268 1
        return $query->getResult();
269
    }
270
271
    #[Override]
272
    public function getRandomSpacecraftIdWithCrewByUser(int $userId): ?int
273
    {
274
        $rsm = new ResultSetMapping();
275
        $rsm->addScalarResult('id', 'id', 'integer');
276
277
        $result = $this->getEntityManager()
278
            ->createNativeQuery(
279
                'SELECT s.id as id FROM stu_spacecraft s
280
                WHERE s.user_id = :userId
281
                AND EXISTS (SELECT sc.id
282
                            FROM stu_crew_assign sc
283
                            WHERE s.id = sc.spacecraft_id)
284
                ORDER BY RANDOM()
285
                LIMIT 1',
286
                $rsm
287
            )
288
            ->setParameters([
289
                'userId' => $userId
290
            ])
291
            ->getOneOrNullResult();
292
293
        return $result != null ? $result['id'] : null;
294
    }
295
296
    #[Override]
297
    public function getAllTractoringSpacecrafts(): array
298
    {
299
        return $this->getEntityManager()->createQuery(
300
            sprintf(
301
                'SELECT s FROM %s s
302
                WHERE s.tractored_ship_id IS NOT NULL',
303
                Spacecraft::class
304
            )
305
        )->getResult();
306
    }
307
308
    #[Override]
309
    public function truncateAllSpacecrafts(): void
310
    {
311
        $this->getEntityManager()->createQuery(
312
            sprintf(
313
                'DELETE FROM %s s',
314
                Spacecraft::class
315
            )
316
        )->execute();
317
    }
318
}
319