1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace TZachi\PhalconRepository; |
6
|
|
|
|
7
|
|
|
use Phalcon\Annotations\AdapterInterface as AnnotationsAdapterInterface; |
8
|
|
|
use RuntimeException; |
9
|
|
|
use TZachi\PhalconRepository\Resolver\Parameter as ParameterResolver; |
10
|
|
|
use TZachi\PhalconRepository\Resolver\QueryParameter as QueryParameterResolver; |
11
|
|
|
use function class_exists; |
12
|
|
|
|
13
|
|
|
class RepositoryFactory |
14
|
|
|
{ |
15
|
|
|
public const REPOSITORY_ANNOTATION_NAME = 'Repository'; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var AnnotationsAdapterInterface |
19
|
|
|
*/ |
20
|
|
|
protected $annotations; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var ParameterResolver |
24
|
|
|
*/ |
25
|
|
|
protected $parameterResolver; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var Repository[] |
29
|
|
|
*/ |
30
|
|
|
protected $repositories = []; |
31
|
|
|
|
32
|
7 |
|
public function __construct( |
33
|
|
|
AnnotationsAdapterInterface $annotations, |
34
|
|
|
?ParameterResolver $parameterResolver = null |
35
|
|
|
) { |
36
|
7 |
|
$this->annotations = $annotations; |
37
|
7 |
|
$this->parameterResolver = $parameterResolver ?? new QueryParameterResolver(); |
38
|
7 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Gets an instance of a model's repository. If one doesn't exist, create it. Instance is shared between multiple |
42
|
|
|
* calls |
43
|
|
|
*/ |
44
|
1 |
|
public function get(string $modelName): Repository |
45
|
|
|
{ |
46
|
1 |
|
if (isset($this->repositories[$modelName])) { |
47
|
1 |
|
return $this->repositories[$modelName]; |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
return $this->repositories[$modelName] = $this->create($modelName); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Creates a new repository related to a specific model |
55
|
|
|
* |
56
|
|
|
* @param string $modelName The class name of the phalcon model |
57
|
|
|
*/ |
58
|
6 |
|
public function create(string $modelName): Repository |
59
|
|
|
{ |
60
|
6 |
|
$repositoryClassName = Repository::class; |
61
|
|
|
|
62
|
6 |
|
$annotationsCollection = $this->annotations->get($modelName)->getClassAnnotations(); |
63
|
6 |
|
if ($annotationsCollection !== false && $annotationsCollection->has(self::REPOSITORY_ANNOTATION_NAME)) { |
64
|
3 |
|
$repositoryClassName = $annotationsCollection->get(self::REPOSITORY_ANNOTATION_NAME)->getArgument(0); |
65
|
3 |
|
if ($repositoryClassName === null || !class_exists($repositoryClassName)) { |
66
|
2 |
|
throw new RuntimeException("Repository class '" . $repositoryClassName . "' doesn't exists"); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
4 |
|
return new $repositoryClassName(new ModelWrapper($modelName), $this->parameterResolver); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|