1: <?php
2:
3: namespace OpenSearch;
4:
5: use OpenSearch\Endpoints\AbstractEndpoint;
6: use OpenSearch\Serializers\SerializerInterface;
7: use ReflectionClass;
8:
9: /**
10: * A factory for creating endpoints.
11: */
12: class EndpointFactory implements EndpointFactoryInterface
13: {
14: /**
15: * @var array<string, AbstractEndpoint>
16: */
17: private array $endpoints = [];
18:
19: public function __construct(
20: protected SerializerInterface $serializer,
21: ) {
22: }
23:
24: /**
25: * {@inheritdoc}
26: */
27: public function getEndpoint(string $class): AbstractEndpoint
28: {
29: if (!isset($this->endpoints[$class])) {
30: $this->endpoints[$class] = $this->createEndpoint($class);
31: }
32:
33: return $this->endpoints[$class];
34: }
35:
36: /**
37: * Creates an endpoint.
38: *
39: * @phpstan-template T of AbstractEndpoint
40: * @phpstan-param class-string<T> $class
41: * @phpstan-return T
42: * @throws \ReflectionException
43: */
44: private function createEndpoint(string $class): AbstractEndpoint
45: {
46: $reflection = new ReflectionClass($class);
47: $constructor = $reflection->getConstructor();
48:
49: if ($constructor && $constructor->getParameters()) {
50: return new $class($this->serializer);
51: }
52: return new $class();
53: }
54:
55: }
56: