ConsignmentServiceCollection::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Loevgaard\DandomainConsignmentBundle\ConsignmentService;
6
7
use Loevgaard\DandomainConsignmentBundle\Exception\NonExistentConsignmentServiceException;
8
use Loevgaard\DandomainFoundation\Entity\Generated\ManufacturerInterface;
9
use Symfony\Component\DependencyInjection\Container;
10
11
class ConsignmentServiceCollection
12
{
13
    /**
14
     * @var ConsignmentServiceInterface[]
15
     */
16
    protected $consignmentServices;
17
18 3
    public function __construct()
19
    {
20 3
        $this->consignmentServices = [];
21 3
    }
22
23
    public function addConsignmentService(ConsignmentServiceInterface $consignmentService): void
24
    {
25
        $class = (new \ReflectionClass($consignmentService))->getShortName();
26
        $this->consignmentServices[$class] = $consignmentService;
27
    }
28
29
    /**
30
     * @param ManufacturerInterface $manufacturer
31
     *
32
     * @return ConsignmentServiceInterface
33
     *
34
     * @throws NonExistentConsignmentServiceException
35
     */
36
    public function findConsignmentService(ManufacturerInterface $manufacturer): ConsignmentServiceInterface
37
    {
38
        $name = preg_replace('/[^a-zA-Z0-9 ]+/i', ' ', $manufacturer->getName());
39
        $name = Container::camelize($name).'ConsignmentService';
40
41
        if (!isset($this->consignmentServices[$name])) {
42
            throw new NonExistentConsignmentServiceException('Consignment service `'.$name.'` not found. Did you mean any of these? '.join(', ', array_keys($this->consignmentServices)));
43
        }
44
45
        /** @var ConsignmentServiceInterface $service */
46
        $service = $this->consignmentServices[$name];
47
        $service->setManufacturer($manufacturer);
48
49
        return $service;
50
    }
51
}
52