1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HansOtt\Lastify; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use HansOtt\Lastify\TrackInfo\Artist; |
7
|
|
|
|
8
|
|
|
final class TrackInfo |
9
|
|
|
{ |
10
|
|
|
private $name; |
11
|
|
|
|
12
|
|
|
private $artists; |
13
|
|
|
|
14
|
18 |
|
public function __construct($name, array $artists = []) |
15
|
|
|
{ |
16
|
18 |
|
$this->assertValidName($name); |
17
|
15 |
|
$this->assertThatTheseAreAllArtists($artists); |
18
|
12 |
|
$this->name = $name; |
19
|
12 |
|
$this->artists = $artists; |
20
|
12 |
|
} |
21
|
|
|
|
22
|
18 |
View Code Duplication |
private function assertValidName($name) |
|
|
|
|
23
|
|
|
{ |
24
|
18 |
|
if (!is_string($name)) { |
25
|
|
|
throw new InvalidArgumentException('The name should be a string, instead got:' . gettype($name)); |
26
|
|
|
} |
27
|
18 |
|
if (empty($name)) { |
28
|
3 |
|
throw new InvalidArgumentException('The name cannot be empty'); |
29
|
|
|
} |
30
|
15 |
|
} |
31
|
|
|
|
32
|
15 |
View Code Duplication |
private function assertThatTheseAreAllArtists(array $artists) |
|
|
|
|
33
|
|
|
{ |
34
|
15 |
|
if (empty($artists)) { |
35
|
3 |
|
throw new InvalidArgumentException('A track should always have an artist'); |
36
|
|
|
} |
37
|
|
|
|
38
|
12 |
|
foreach ($artists as $artist) { |
39
|
12 |
|
if (! ($artist instanceof Artist)) { |
40
|
|
|
throw new \InvalidArgumentException(sprintf( |
41
|
|
|
'Expected "%s", but instead got: "%s"', |
42
|
|
|
Artist::class, |
43
|
|
|
is_object($artist) ? get_class($artist) : gettype($artist) |
44
|
|
|
)); |
45
|
|
|
} |
46
|
12 |
|
} |
47
|
12 |
|
} |
48
|
|
|
|
49
|
|
|
public function getName() |
50
|
|
|
{ |
51
|
|
|
return $this->name; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getArtists() |
55
|
|
|
{ |
56
|
|
|
return $this->artists; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function toString() |
60
|
|
|
{ |
61
|
3 |
|
$artists = array_map(function (Artist $artist) { |
62
|
3 |
|
return $artist->getName(); |
63
|
3 |
|
}, $this->artists); |
64
|
|
|
|
65
|
3 |
|
return sprintf('%s - %s', $this->name, implode(', ', $artists)); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function __toString() |
69
|
|
|
{ |
70
|
|
|
return $this->toString(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.