ArtistRepository   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 94.74%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 18
c 1
b 0
f 0
dl 0
loc 44
ccs 18
cts 19
cp 0.9474
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A getOrCreateByNames() 0 35 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Enum\Site;
8
use Application\Model\Artist;
9
10
/**
11
 * @extends AbstractRepository<Artist>
12
 */
13
class ArtistRepository extends AbstractRepository
14
{
15
    /**
16
     * Get or create artists by their given names.
17
     *
18
     * @param string[] $names
19
     *
20
     * @return Artist[]
21
     */
22 10
    public function getOrCreateByNames(array $names, Site $site): array
23
    {
24 10
        if (!$names) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $names of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
25
            return [];
26
        }
27
28
        // Dedup and trim whitespaces
29 10
        $names = array_unique(array_map(fn ($value) => trim($value), $names));
30
31 10
        $artists = $this->findBy([
32 10
            'name' => $names,
33 10
            'site' => $site->value,
34 10
        ]);
35
36 10
        $found = [];
37 10
        foreach ($artists as $artist) {
38
            // Names are not trimmed when saved from thesaurus interface, so we
39
            // have names with trailing whitespace in the database.
40
            // With the collation we use, MariaDB trims whitespaces when doing
41
            // comparison (affecting UNIQUE constraint and SELECT queries).
42
            // So we must be sure to handle whitespaces in the same way as
43
            // MariaDB when doing comparisons.
44 8
            $found[] = trim($artist->getName());
45
        }
46
47 10
        $notFound = array_diff($names, $found);
48 10
        foreach ($notFound as $name) {
49 10
            $artist = new Artist();
50 10
            $artist->setSite($site);
51 10
            $this->getEntityManager()->persist($artist);
52 10
            $artist->setName($name);
53 10
            $artists[] = $artist;
54
        }
55
56 10
        return $artists;
57
    }
58
}
59