Completed
Pull Request — master (#5)
by Dmitry
05:48
created

ServiceFactory::buildTransport()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.8449

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 6
cts 11
cp 0.5455
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 3
nop 2
crap 3.8449
1
<?php
2
/**
3
 * @author Dmitry Gladyshev <[email protected]>
4
 * @date 23/08/2016 13:42
5
 */
6
7
namespace Yandex\Direct;
8
9
use Yandex\Direct\Exception\InvalidArgumentException;
10
use Yandex\Direct\Exception\ServiceNotFoundException;
11
use Yandex\Direct\Transport\Json\Transport;
12
use Yandex\Direct\Transport\TransportInterface;
13
14
/**
15
 * Class ServiceFactory
16
 *
17
 * @package Yandex\Direct
18
 */
19
class ServiceFactory implements ServiceFactoryInterface
20
{
21
    /**
22
     * @var string
23
     */
24
    protected $serviceNamespace = __NAMESPACE__ . '\\' . 'Service';
25
26
    /**
27
     * @inheritdoc
28
     */
29 51
    public function createService($serviceName, array $serviceOptions = [])
30
    {
31 51
        if (empty($serviceOptions[self::OPTION_TRANSPORT])) {
32
            // Use default transport
33 34
            $serviceOptions[self::OPTION_TRANSPORT] = new Transport;
34 34
        }
35
36 51
        if (empty($serviceOptions[self::OPTION_CREDENTIALS])) {
37
            throw new InvalidArgumentException('Credentials is required.');
38
        }
39
40 51
        $className = $this->getServiceNamespace() . '\\' . ucfirst($serviceName);
41
42 51
        if (class_exists($className)) {
43 48
            $instance = new $className($serviceName);
44 48
            if (!$instance instanceof Service) {
45
                throw new ServiceNotFoundException(
46
                    "Service class `{$className}` is not instance of `" . Service::class . "`."
47
                );
48
            }
49 48
            $serviceOptions['name'] = $serviceName;
50 48
            $instance->setOptions($serviceOptions);
51 48
            return $instance;
52
        }
53
54 3
        throw new ServiceNotFoundException("Service class `{$className}` is not found.");
55
56
    }
57
58
    public function setServiceNamespace($namespace)
59
    {
60
        $this->serviceNamespace = $namespace;
61
    }
62
63 51
    protected function getServiceNamespace()
64
    {
65 51
        return $this->serviceNamespace;
66
    }
67
}
68