Passed
Push — dev ( 117aec...fd7324 )
by Janko
15:18
created

getRandomSpacecraftWithCrewByUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 19
nc 2
nop 1
dl 0
loc 25
rs 9.6333
c 0
b 0
f 0
ccs 0
cts 16
cp 0
crap 6
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\TShipItem;
17
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...
18
use Stu\Orm\Entity\Anomaly;
19
use Stu\Orm\Entity\SpacecraftBuildplan;
20
use Stu\Orm\Entity\CrewAssignment;
21
use Stu\Orm\Entity\MapInterface;
22
use Stu\Orm\Entity\ShipRumpSpecial;
23
use Stu\Orm\Entity\Spacecraft;
24
use Stu\Orm\Entity\SpacecraftCondition;
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(): array
97
    {
98
        return $this->getEntityManager()->createQuery(
99
            sprintf(
100
                'SELECT s FROM %s s
101
                JOIN %s sc
102
                WITH s = sc.spacecraft
103
                JOIN %s ss
104
                WITH s.id = ss.spacecraft_id
105
                JOIN %s bp
106
                WITH s.plan_id = bp.id
107
                WHERE ss.system_type = :shieldType
108
                AND ss.mode < :modeOn
109
                AND sc.shield < s.max_schilde
110
                AND (SELECT count(ca.crew) FROM %s ca WHERE s = ca.spacecraft) >= bp.crew
111
                AND NOT EXISTS (SELECT a FROM %s a
112
                                WHERE a.location_id = s.location_id
113
                                AND a.anomaly_type_id in (:anomalyTypes)
114
                                AND a.remaining_ticks > 0)',
115
                Spacecraft::class,
116
                SpacecraftCondition::class,
117
                SpacecraftSystem::class,
118
                SpacecraftBuildplan::class,
119
                CrewAssignment::class,
120
                Anomaly::class
121
            )
122
        )->setParameters([
123
            'shieldType' => SpacecraftSystemTypeEnum::SHIELDS->value,
124
            'modeOn' => SpacecraftSystemModeEnum::MODE_ON->value,
125
            'anomalyTypes' => [AnomalyTypeEnum::SUBSPACE_ELLIPSE, AnomalyTypeEnum::ION_STORM]
126
        ])->getResult();
127
    }
128
129
    #[Override]
130
    public function getPlayerSpacecraftsForTick(): iterable
131
    {
132
        return $this->getEntityManager()->createQuery(
133
            sprintf(
134
                'SELECT s
135
                FROM %s s
136
                JOIN %s sc
137
                WITH s = sc.spacecraft
138
                JOIN %s p
139
                WITH s.plan_id = p.id
140
                JOIN %s u
141
                WITH s.user_id = u.id
142
                WHERE s.user_id > :firstUserId
143
                AND (   ((SELECT count(ca.crew)
144
                        FROM %s ca
145
                        WHERE ca.spacecraft = s) > 0)
146
                    OR
147
                        (sc.state IN (:scrapping, :underConstruction))
148
                    OR
149
                        (p.crew = 0))
150
                AND (u.vac_active = :false OR u.vac_request_date > :vacationThreshold)',
151
                Spacecraft::class,
152
                SpacecraftCondition::class,
153
                SpacecraftBuildplan::class,
154
                User::class,
155
                CrewAssignment::class
156
            )
157
        )->setParameters([
158
            'underConstruction' => SpacecraftStateEnum::UNDER_CONSTRUCTION,
159
            'scrapping' => SpacecraftStateEnum::UNDER_SCRAPPING,
160
            'vacationThreshold' => time() - UserEnum::VACATION_DELAY_IN_SECONDS,
161
            'firstUserId' => UserEnum::USER_FIRST_ID,
162
            'false' => false
163
        ])->toIterable();
164
    }
165
166
    #[Override]
167
    public function getNpcSpacecraftsForTick(): array
168
    {
169
        return $this->getEntityManager()->createQuery(
170
            sprintf(
171
                'SELECT s FROM %s s WHERE s.user_id BETWEEN 2 AND (:firstUserId - 1)',
172
                Spacecraft::class
173
            )
174
        )->setParameter('firstUserId', UserEnum::USER_FIRST_ID)->getResult();
175
    }
176
177
    #[Override]
178
    public function isCloakedSpacecraftAtLocation(
179
        SpacecraftInterface $spacecraft
180
    ): bool {
181
182
        $result = $this->getEntityManager()->createQuery(
183
            sprintf(
184
                'SELECT COUNT(s.id) FROM %s s
185
                    WHERE s.location = :location
186
                    AND EXISTS (SELECT ss.id
187
                            FROM %s ss
188
                            WHERE s = ss.spacecraft
189
                            AND ss.system_type = %d
190
                            AND ss.mode > 1)
191
                    AND s.user != :ignoreUser',
192
                Spacecraft::class,
193
                SpacecraftSystem::class,
194
                SpacecraftSystemTypeEnum::CLOAK->value
195
            )
196
        )->setParameters([
197
            'location' => $spacecraft->getLocation(),
198
            'ignoreUser' => $spacecraft->getUser()
199
        ])->getSingleScalarResult();
200
201
        return $result > 0;
202
    }
203
204 1
    #[Override]
205
    public function getSingleSpacecraftScannerResults(
206
        SpacecraftInterface $spacecraft,
207
        bool $showCloaked = false,
208
        MapInterface|StarSystemMapInterface|null $field = null
209
    ): array {
210
211 1
        $rsm = new ResultSetMapping();
212 1
        $rsm->addEntityResult(TShipItem::class, 's');
213 1
        TShipItem::addTSpacecraftItemFields($rsm);
214
215 1
        $location = $field ?? $spacecraft->getLocation();
216
217 1
        $query = $this->getEntityManager()->createNativeQuery(
218 1
            sprintf(
219 1
                'SELECT sp.id as shipid, s.fleet_id as fleetid, sp.rump_id as rumpid , ss.mode as warpstate,
220
                    twd.mode as tractorwarpstate, COALESCE(ss2.mode,0) as cloakstate, ss3.mode as shieldstate, COALESCE(ss4.status,0) as uplinkstate,
221
                    sp.type as spacecrafttype, sp.name as shipname, sc.hull as hull, sp.max_huelle as maxhull,
222
                    sc.shield as shield, sp.holding_web_id as webid, tw.finished_time as webfinishtime, u.id as userid, u.username,
223
                    r.category_id as rumpcategoryid, r.name as rumpname, r.role_id as rumproleid,
224
                    (SELECT count(*) > 0 FROM stu_ship_log sl WHERE sl.spacecraft_id = sp.id AND sl.is_private = :false) as haslogbook,
225
                    (SELECT count(*) > 0 FROM stu_crew_assign ca WHERE ca.spacecraft_id = sp.id) as hascrew
226
                FROM stu_spacecraft sp
227
                JOIN stu_spacecraft_condition sc
228
                ON sp.id = sc.spacecraft_id
229
                LEFT JOIN stu_ship s
230
                ON s.id = sp.id
231
                LEFT JOIN stu_spacecraft_system ss
232
                ON sp.id = ss.spacecraft_id
233
                AND ss.system_type = :warpdriveType
234
                LEFT JOIN stu_spacecraft tractor
235
                ON tractor.tractored_ship_id = s.id
236
                LEFT JOIN stu_spacecraft_system twd
237
                ON tractor.id = twd.spacecraft_id
238
                AND twd.system_type = :warpdriveType
239
                LEFT JOIN stu_spacecraft_system ss2
240
                ON sp.id = ss2.spacecraft_id
241
                AND ss2.system_type = :cloakType
242
                LEFT JOIN stu_spacecraft_system ss3
243
                ON sp.id = ss3.spacecraft_id
244
                AND ss3.system_type = :shieldType
245
                LEFT JOIN stu_spacecraft_system ss4
246
                ON sp.id = ss4.spacecraft_id
247
                AND ss4.system_type = :uplinkType
248
                JOIN stu_rump r
249
                ON sp.rump_id = r.id
250
                LEFT OUTER JOIN stu_tholian_web tw
251
                ON sp.holding_web_id = tw.id
252
                JOIN stu_user u
253
                ON sp.user_id = u.id
254
                WHERE sp.location_id = :locationId
255
                AND sp.id != :ignoreId
256
                AND s.fleet_id IS NULL
257
                AND sp.type != :stationType
258
                %s
259 1
                ORDER BY r.category_id ASC, r.role_id ASC, r.id ASC, sp.name ASC',
260 1
                $showCloaked ? '' : sprintf(' AND (sp.user_id = %d OR COALESCE(ss2.mode,0) < %d) ', $spacecraft->getUser()->getId(), SpacecraftSystemModeEnum::MODE_ON->value)
261 1
            ),
262 1
            $rsm
263 1
        )->setParameters([
264 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

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