DescriptionFactory::createDescription()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Description;
6
7
use Psi\Component\Description\Schema\Schema;
8
9
/**
10
 * This class is the main point of entry for this component.
11
 *
12
 * It provides descriptions for objects. Descriptions are populated by
13
 * "enhancers" as given in the constructor. The order of the enhancers is important
14
 */
15
class DescriptionFactory
16
{
17
    /**
18
     * @var DescriptionEnhancerInterface[]
19
     */
20
    private $enhancers = [];
21
22
    /**
23
     * @var SubjectResolverInterface[]
24
     */
25
    private $resolvers = [];
26
27
    /**
28
     * @var Schema
29
     */
30
    private $schema;
31
32
    public function __construct(array $enhancers, Schema $schema = null, array $resolvers = [])
33
    {
34
        // type safety ...
35
        array_walk($enhancers, function (EnhancerInterface $enhancer) {
0 ignored issues
show
Unused Code introduced by
The parameter $enhancer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
36
        });
37
        array_walk($resolvers, function (SubjectResolverInterface $enhancer) {
0 ignored issues
show
Unused Code introduced by
The parameter $enhancer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
        });
39
40
        $this->enhancers = $enhancers;
41
        $this->resolvers = $resolvers;
42
        $this->schema = $schema;
43
    }
44
45
    /**
46
     * Return a description of the given subject.
47
     */
48
    public function describe(Subject $subject): DescriptionInterface
49
    {
50
        $description = $this->createDescription();
51
52
        foreach ($this->resolvers as $resolver) {
53
            $subject = $resolver->resolve($subject);
54
        }
55
56
        foreach ($this->enhancers as $enhancer) {
57
            if (false === $enhancer->supports($subject)) {
58
                continue;
59
            }
60
61
            $enhancer->enhanceFromClass($description, $subject->getClass());
62
63
            if ($subject->hasObject()) {
64
                $enhancer->enhanceFromObject($description, $subject);
65
            }
66
        }
67
68
        return $description;
69
    }
70
71
    private function createDescription(): DescriptionInterface
72
    {
73
        $description = new Description();
74
75
        if ($this->schema) {
76
            $description = new ValidatedDescription($description, $this->schema);
77
        }
78
79
        return $description;
80
    }
81
}
82