getApplicationOptions()   B
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 46
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 46
rs 8.5706
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\LaminasFactory;
6
7
use Laminas\ServiceManager\Exception\ServiceNotCreatedException;
8
use Laminas\ServiceManager\Exception\ServiceNotFoundException;
9
use Psr\Container\ContainerExceptionInterface;
10
use Psr\Container\ContainerInterface;
11
12
trait ApplicationOptionsProviderTrait
13
{
14
    protected string $applicationOptionsKey = 'arp';
15
16
    private string $applicationOptionsService = 'config';
17
18
    /**
19
     * @return array<mixed>
20
     *
21
     * @throws ServiceNotFoundException
22
     * @throws ServiceNotCreatedException
23
     * @throws ContainerExceptionInterface
24
     */
25
    public function getApplicationOptions(ContainerInterface $container, ?string $optionsKey = null): array
26
    {
27
        if (null !== $optionsKey) {
28
            $this->setApplicationOptionsKey($optionsKey);
29
        }
30
31
        if (!$container->has($this->applicationOptionsService)) {
32
            throw new ServiceNotFoundException(
33
                sprintf(
34
                    'The required application options service \'%s\' could not be found in \'%s\'.',
35
                    $this->applicationOptionsService,
36
                    __METHOD__
37
                )
38
            );
39
        }
40
41
        $options = $container->get($this->applicationOptionsService);
42
43
        if (!is_array($options) || !array_key_exists($this->applicationOptionsKey, $options)) {
44
            throw new ServiceNotCreatedException(
45
                sprintf(
46
                    'The application key \'%s\' could not be found within the application options service \'%s\'.',
47
                    $this->applicationOptionsKey,
48
                    $this->applicationOptionsService
49
                )
50
            );
51
        }
52
53
        $options = $options[$this->applicationOptionsKey];
54
55
        if ($options instanceof \Traversable) {
56
            $options = iterator_to_array($options);
57
        }
58
59
        if (!is_array($options)) {
60
            throw new ServiceNotCreatedException(
61
                sprintf(
62
                    'The application options must be an \'array\' or object of type \'%s\'; \'%s\' provided in \'%s\'.',
63
                    \Traversable::class,
64
                    gettype($options),
65
                    __METHOD__
66
                )
67
            );
68
        }
69
70
        return $options;
71
    }
72
73
    public function setApplicationOptionsKey(string $optionsKey): void
74
    {
75
        $this->applicationOptionsKey = $optionsKey;
76
    }
77
}
78