|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the "elao/api-resources-metadata" package. |
|
5
|
|
|
* |
|
6
|
|
|
* Copyright (C) 2016 Elao |
|
7
|
|
|
* |
|
8
|
|
|
* @author Elao <[email protected]> |
|
9
|
|
|
*/ |
|
10
|
|
|
|
|
11
|
|
|
namespace Elao\ApiResourcesMetadata\Resource\Loader; |
|
12
|
|
|
|
|
13
|
|
|
use Elao\ApiResourcesMetadata\Attribute\ResourceAttributeMetadata; |
|
14
|
|
|
use Elao\ApiResourcesMetadata\Resource\ResourceMetadata; |
|
15
|
|
|
use Symfony\Component\Yaml\Parser; |
|
16
|
|
|
|
|
17
|
|
|
class YamlFileLoader implements LoaderInterface |
|
18
|
|
|
{ |
|
19
|
|
|
/** @var string */ |
|
20
|
|
|
private $path; |
|
21
|
|
|
|
|
22
|
|
|
/** @var Parser */ |
|
23
|
|
|
private $parser; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct(string $path) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->path = $path; |
|
28
|
|
|
$this->parser = new Parser(); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function loadResourceMetadata(ResourceMetadata $resourceMetadata): bool |
|
32
|
|
|
{ |
|
33
|
|
|
list($shortName, $resource) = $this->findResourceData($resourceMetadata); |
|
34
|
|
|
|
|
35
|
|
|
if (null === $resource) { |
|
36
|
|
|
return false; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
$resourceMetadata->setShortName($shortName); |
|
40
|
|
|
|
|
41
|
|
|
if (isset($resource['description'])) { |
|
42
|
|
|
$resourceMetadata->setDescription($resource['description'] ?? ''); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
foreach ($resource['attributes'] ?? [] as $name => $attribute) { |
|
46
|
|
|
$attributeMetadata = $resourceMetadata->getAttribute($name) ?? new ResourceAttributeMetadata($name); |
|
47
|
|
|
|
|
48
|
|
|
!isset($attribute['description']) ?: $attributeMetadata->setDescription($attribute['description']); |
|
49
|
|
|
!isset($attribute['required']) ?: $attributeMetadata->setRequired($attribute['required']); |
|
50
|
|
|
!isset($attribute['type']) ?: $attributeMetadata->setType($attribute['type']); |
|
51
|
|
|
!isset($attribute['originalType']) ?: $attributeMetadata->setOriginalType($attribute['originalType']); |
|
52
|
|
|
|
|
53
|
|
|
$resourceMetadata->addAttribute($attributeMetadata); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return true; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
private function findResourceData(ResourceMetadata $resourceMetadata) |
|
60
|
|
|
{ |
|
61
|
|
|
$parsed = $this->parser->parse(file_get_contents($this->path)); |
|
62
|
|
|
$resources = $parsed['resources'] ?? []; |
|
63
|
|
|
|
|
64
|
|
|
foreach ($resources as $shortName => $resource) { |
|
65
|
|
|
if (is_string($resource)) { |
|
66
|
|
|
$resource = ['class' => $resource]; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
if ($resourceMetadata->getClass() === $resource['class']) { |
|
70
|
|
|
return [$shortName, $resource]; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return null; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|