Completed
Push — master ( 5ef641...47b2a6 )
by Sebastian
04:50
created

ParseProperty::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 9.408
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Spatie\SchemaOrg\Generator\Parser\Tasks;
4
5
use Spatie\SchemaOrg\Generator\Property;
6
use Symfony\Component\DomCrawler\Crawler;
7
8
class ParseProperty extends Task
9
{
10
    public function __invoke(): ?Property
11
    {
12
        $node = new Crawler($this->definition);
13
14
        $property = new Property();
15
16
        $property->name = $this->getText($node, '[property="rdfs:label"]');
17
18
        if (empty($property->name)) {
19
            return null;
20
        }
21
22
        $property->description = $this->getText($node, '[property="rdfs:comment"]');
23
24
        $property->resource = $this->getAttribute($node, 'resource');
25
26
        $node
27
            ->filter('[property="http://schema.org/domainIncludes"]')
28
            ->each(function (Crawler $domain) use ($property) {
29
                $property->addType($this->getText($domain));
30
            });
31
32
        $node
33
            ->filter('[property="http://schema.org/rangeIncludes"]')
34
            ->each(function (Crawler $range) use ($property) {
35
                $property->addRanges(
36
                    $this->castRangesToTypes($this->getText($range))
37
                );
38
            });
39
40
        return $property;
41
    }
42
43
    private function castRangesToTypes(string $range): array
44
    {
45
        switch ($range) {
46
            case 'Boolean':
47
                return ['bool'];
48
            case 'False':
49
                return ['false'];
50
            case 'True':
51
                return ['true'];
52
            case 'Date':
53
            case 'Time':
54
            case 'DateTime':
55
                return ['\DateTimeInterface'];
56
            case 'Text':
57
            case 'URL':
58
                return ['string'];
59
            case 'Number':
60
                return ['float', 'int'];
61
            case 'Float':
62
                return ['float'];
63
            case 'Integer':
64
                return ['int'];
65
            default:
66
                return [$range];
67
        }
68
    }
69
}
70