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

ArtistRepository::getOrCreateByNames()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4.0023

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 29
ccs 18
cts 19
cp 0.9474
rs 9.7
cc 4
nc 5
nop 2
crap 4.0023
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Model\Artist;
8
9
/**
10
 * @extends AbstractRepository<Artist>
11
 */
12
class ArtistRepository extends AbstractRepository
13
{
14
    /**
15
     * Get or create artists by their given names.
16
     *
17
     * @param string[] $names
18
     *
19
     * @return Artist[]
20
     */
21 10
    public function getOrCreateByNames(array $names, string $site): array
22
    {
23 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...
24
            return [];
25
        }
26
27
        // Dedup and trim whitespaces
28 10
        $names = array_unique(array_map(fn ($value) => trim($value), $names));
29
30 10
        $artists = $this->findBy([
31 10
            'name' => $names,
32 10
            'site' => $site,
33 10
        ]);
34
35 10
        $found = [];
36 10
        foreach ($artists as $artist) {
37 8
            $found[] = $artist->getName();
38
        }
39
40 10
        $notFound = array_diff($names, $found);
41 10
        foreach ($notFound as $name) {
42 10
            $artist = new Artist();
43 10
            $artist->setSite($site);
44 10
            $this->getEntityManager()->persist($artist);
45 10
            $artist->setName($name);
46 10
            $artists[] = $artist;
47
        }
48
49 10
        return $artists;
50
    }
51
}
52