-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIriTemplatesService.php
More file actions
83 lines (68 loc) · 2.59 KB
/
Copy pathIriTemplatesService.php
File metadata and controls
83 lines (68 loc) · 2.59 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Netgen\ApiPlatformExtras\Service;
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operations;
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouterInterface;
use function is_string;
use function preg_replace;
final class IriTemplatesService
{
public function __construct(
private ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
private ResourceNameCollectionFactoryInterface $resourceExtractor,
private RouterInterface $router,
) {}
/**
* @return array<string, string>
*/
public function getIriTemplatesData(): array
{
$resourceClasses = $this->resourceExtractor->create();
$routeCollection = $this->router->getRouteCollection();
$iriTemplates = [];
foreach ($resourceClasses as $class) {
try {
$resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($class);
} catch (ResourceClassNotFoundException) {
continue;
}
/** @var \ApiPlatform\Metadata\ApiResource $resourceMetadata */
foreach ($resourceMetadataCollection as $resourceMetadata) {
/** @var Operations<HttpOperation> $operations */
$operations = $resourceMetadata->getOperations();
foreach ($operations as $operation) {
if (!$operation instanceof Get) {
continue;
}
/** @var string $operationName */
$operationName = $operation->getName();
$route = $routeCollection->get($operationName);
$shortName = $resourceMetadata->getShortName();
if (
!$route instanceof Route
|| !is_string($shortName)
) {
continue;
}
$iriTemplates[$shortName] = $this->sanitizePath($route->getPath());
break;
}
}
}
return $iriTemplates;
}
private function sanitizePath(string $path): string
{
return preg_replace(
'/\.\{_format}$/',
'',
$path,
) ?? '';
}
}