AppAdapter   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 48
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getNotFound() 0 8 2
A __construct() 0 5 1
A get() 0 18 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Exception\ResourceNotFoundException;
8
use Override;
9
use Ray\Di\Exception\Unbound;
10
use Ray\Di\InjectorInterface;
11
use Throwable;
12
13
use function assert;
14
use function sprintf;
15
use function str_contains;
16
use function str_ends_with;
17
use function str_replace;
18
use function ucwords;
19
20
final class AppAdapter implements AdapterInterface
21
{
22
    /**
23
     * @param InjectorInterface $injector  Application dependency injector
24
     * @param string            $namespace Resource adapter namespace
25
     */
26
    public function __construct(
27
        private readonly InjectorInterface $injector,
28
        /** Resource adapter namespace */
29
        private readonly string $namespace,
30
    ) {
31
    }
32
33
    /**
34
     * {@inheritDoc}
35
     *
36
     * @throws ResourceNotFoundException
37
     * @throws Unbound
38
     */
39
    #[Override]
40
    public function get(AbstractUri $uri): ResourceObject
41
    {
42
        if (str_ends_with($uri->path, '/')) {
43
            $uri->path .= 'index';
44
        }
45
46
        $path = str_replace('-', '', ucwords($uri->path, '/-'));
47
        /** @var ''|class-string $class */
48
        $class = sprintf('%s\Resource\%s', $this->namespace, str_replace('/', '\\', ucwords($uri->scheme) . $path));
49
        try {
50
            $instance = $this->injector->getInstance($class);
51
            assert($instance instanceof ResourceObject);
52
        } catch (Unbound $e) {
53
            throw $this->getNotFound($uri, $e, $class);
54
        }
55
56
        return $instance;
57
    }
58
59
    /** @return ResourceNotFoundException|Unbound */
60
    private function getNotFound(AbstractUri $uri, Unbound $e, string $class): Throwable
61
    {
62
        $unboundClass = $e->getMessage();
63
        if (str_contains($unboundClass, "{$class}-")) {
64
            return new ResourceNotFoundException((string) $uri, 404, $e);
65
        }
66
67
        return $e;
68
    }
69
}
70