Failed Conditions
Push — master ( 27554e...857869 )
by Luca
09:08
created

CardRepository::getNextCodeAvailable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2.003

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 19
ccs 10
cts 11
cp 0.9091
rs 9.9332
cc 2
nc 2
nop 1
crap 2.003
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Model\Card;
8
use Application\Model\Collection;
9
use Application\Model\Export;
10
use Application\Model\User;
11
use Doctrine\ORM\Query\Expr\Join;
12
use Doctrine\ORM\QueryBuilder;
13
use Ecodev\Felix\Repository\LimitedAccessSubQuery;
14
15
/**
16
 * @extends AbstractRepository<Card>
17
 */
18
class CardRepository extends AbstractRepository implements LimitedAccessSubQuery
19
{
20
    public function getFindAllByCollections(array $collections = []): QueryBuilder
21
    {
22
        $qb = $this->createQueryBuilder('card');
23
24
        if (count($collections) > 0) {
25
            $qb->join('card.collections', 'collection');
26
            $qb->andWhere('collection.id IN (:collections)');
27
            $qb->setParameter('collections', $collections);
28
        } else {
29
            $qb->andWhere('card.collections IS EMPTY');
30
        }
31
32
        return $qb;
33
    }
34
35
    /**
36
     * Returns pure SQL to get ID of all cards that are accessible to given user.
37
     * A card is accessible if:
38
     * - card is public
39
     * - card is member and user is logged in
40
     * - card owner or creator is the user
41
     * - card's collection responsible is the user.
42
     */
43 33
    public function getAccessibleSubQuery(?\Ecodev\Felix\Model\User $user): string
44
    {
45 33
        if ($user && $user->getRole() === User::ROLE_ADMINISTRATOR) {
46 12
            return '';
47
        }
48
49 21
        $visibility = [Card::VISIBILITY_PUBLIC];
50 21
        if ($user) {
51 14
            $visibility[] = Card::VISIBILITY_MEMBER;
52
        }
53
54 21
        $qb = $this->getEntityManager()
55 21
            ->getConnection()
56 21
            ->createQueryBuilder()
57 21
            ->select('card.id')
58 21
            ->from('card')
59 21
            ->where('card.visibility IN (' . $this->quoteArray($visibility) . ')');
60
61 21
        if ($user) {
62 14
            $userId = $this->getEntityManager()->getConnection()->quote($user->getId());
63 14
            $qb->leftJoin('card', 'card_collection', 'card_collection', 'card_collection.card_id = card.id')
64 14
                ->leftJoin('card_collection', 'collection_user', 'collection_user', 'card_collection.collection_id = collection_user.collection_id')
65 14
                ->orWhere('card.owner_id = ' . $userId)
66 14
                ->orWhere('card.creator_id = ' . $userId)
67 14
                ->orWhere('collection_user.user_id = ' . $userId);
68
        }
69
70 21
        return $qb->getSQL();
71
    }
72
73
    /**
74
     * Returns all filename in DB and their id and sizes.
75
     *
76
     * @return string[][]
77
     */
78
    public function getFilenamesForDimensionUpdate(?string $site = null): array
79
    {
80
        $filenames = $this->getEntityManager()->getConnection()->createQueryBuilder()
81
            ->from('card')
82
            ->addSelect('id')
83
            ->addSelect('width')
84
            ->addSelect('height')
85
            ->addSelect('CONCAT("data/images/", filename) AS filename')
86
            ->where('filename != ""')
87
            ->orderBy('filename');
88
89
        if ($site) {
90
            $filenames
91
                ->where('site = "' . $site . '"');
92
        }
93
94
        return $filenames->execute()->fetchAllAssociative();
0 ignored issues
show
Deprecated Code introduced by
The function Doctrine\DBAL\Query\QueryBuilder::execute() has been deprecated: Use {@see executeQuery()} or {@see executeStatement()} instead. ( Ignorable by Annotation )

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

94
        return /** @scrutinizer ignore-deprecated */ $filenames->execute()->fetchAllAssociative();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
95
    }
96
97
    /**
98
     * Return the next available code.
99
     */
100 1
    public function getNextCodeAvailable(Collection $collection): string
101
    {
102 1
        static $nextId = null;
103
104 1
        if (!$nextId) {
105 1
            $connection = _em()->getConnection();
106 1
            $database = $connection->quote($connection->getDatabase());
107
108 1
            $sql = "SELECT `AUTO_INCREMENT`
109
                FROM INFORMATION_SCHEMA.TABLES
110 1
                WHERE TABLE_SCHEMA = $database
111 1
                AND TABLE_NAME = 'card'";
112
113 1
            $nextId = (int) $connection->fetchOne($sql);
114
        } else {
115
            ++$nextId;
116
        }
117
118 1
        return $collection->getName() . '-' . $nextId;
119
    }
120
121
    /**
122
     * Get a card from it's legacy id.
123
     */
124
    public function getOneByLegacyId(int $legacy_id): ?Card
125
    {
126
        return $this->getAclFilter()->runWithoutAcl(fn () => $this->findOneBy([
127
            'legacyId' => $legacy_id,
128
        ]));
129
    }
130
131
    /**
132
     * Returns **some** cards for the given export, starting at $firstResult.
133
     *
134
     * This method has to be called repeatedly with a different $firstResult in order
135
     * to iterate over **all** cards of a given export
136
     */
137 3
    public function getExportCards(Export $export, int $lastCard): array
138
    {
139 3
        $cardIds = $this->getEntityManager()->getConnection()->fetchFirstColumn(
140 3
            'SELECT card_id FROM export_card WHERE export_id = :export AND card_id > :lastCard ORDER BY card_id LIMIT 250',
141 3
            [
142 3
                'export' => $export->getId(),
143 3
                'lastCard' => $lastCard,
144 3
            ],
145 3
        );
146
147 3
        $qb = $this->createQueryBuilder('card');
148 3
        $qb->select('card, artist, country, documentType, domain, institution, period')
149 3
            ->leftJoin('card.artists', 'artist', Join::WITH)
150 3
            ->leftJoin('card.country', 'country', Join::WITH)
151 3
            ->leftJoin('card.documentType', 'documentType', Join::WITH)
152 3
            ->leftJoin('card.domains', 'domain', Join::WITH)
153 3
            ->leftJoin('card.institution', 'institution', Join::WITH)
154 3
            ->leftJoin('card.periods', 'period', Join::WITH)
155 3
            ->andWhere('card.id IN (:cards)')
156 3
            ->setParameter('cards', $cardIds)
157 3
            ->orderBy('card.id');
158
159 3
        return $this->getAclFilter()->runWithoutAcl(fn () => $qb->getQuery()->getResult());
160
    }
161
}
162