-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathAttributeFactory.php
More file actions
66 lines (55 loc) · 1.79 KB
/
AttributeFactory.php
File metadata and controls
66 lines (55 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
namespace SwaggerBake\Lib\Attribute;
use Reflector;
use SwaggerBake\Lib\Exception\SwaggerBakeRunTimeException;
final class AttributeFactory
{
/**
* @param \Reflector $reflection The reflection
* @param string $attributeClass Your Attribute class
*/
public function __construct(
private Reflector $reflection,
private string $attributeClass,
) {
}
/**
* Creates an instance of the attribute class, returns null if no attribute was found
*
* @return object|null
* @throws \ReflectionException
*/
public function createOneOrNull(): ?object
{
if (!method_exists($this->reflection, 'getAttributes')) {
throw new SwaggerBakeRunTimeException('Reflected instance does not have getAttributes method');
}
$attributes = $this->reflection->getAttributes($this->attributeClass);
if (empty($attributes)) {
return null;
}
/** @var \ReflectionAttribute $attr */
$attr = reset($attributes);
return $attr->newInstance();
}
/**
* Creates many instances of the attribute class and returns them in an array. This is useful when an Attribute
* has the IS_REPEATABLE flag set.
*
* @return array
* @throws \ReflectionException
* @throws \RuntimeException
*/
public function createMany(): array
{
if (!method_exists($this->reflection, 'getAttributes')) {
throw new SwaggerBakeRunTimeException('Reflected instance does not have getAttributes method');
}
$attributes = $this->reflection->getAttributes($this->attributeClass);
foreach ($attributes as $attr) {
$array[] = $attr->newInstance();
}
return $array ?? [];
}
}