Skip to content

Commit 781d9dc

Browse files
committed
add AbstractRegistry
1 parent ba573a2 commit 781d9dc

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

src/Commands/AbstractRegistry.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
3+
/**
4+
* @author Mohammed Moussaoui
5+
* @copyright Copyright (c) Mohammed Moussaoui. All rights reserved.
6+
* @license MIT License. For full license information see LICENSE file in the project root.
7+
* @link https://github.com/DevNet-Framework
8+
*/
9+
10+
namespace DevNet\Cli\Commands;
11+
12+
use DevNet\System\Collections\Enumerator;
13+
use DevNet\System\Collections\IEnumerable;
14+
use DevNet\System\Type;
15+
16+
abstract class AbstractRegistry implements IEnumerable
17+
{
18+
private Type $type;
19+
private array $classes = [];
20+
private array $objects = [];
21+
22+
abstract public static function getSingleton(): static;
23+
24+
public function __construct(string $type)
25+
{
26+
$this->type = new Type($type);
27+
}
28+
29+
/**
30+
* @param object|string $service object or class name of the injected service
31+
*/
32+
public function set(string $name, $service): void
33+
{
34+
if (is_string($service)) {
35+
$this->classes[$name] = $service;
36+
} else if (is_object($service)) {
37+
if ($this->type->isTypeOf($service)) {
38+
$this->objects[$name] = $service;
39+
}
40+
}
41+
}
42+
43+
public function get(string $name): ?object
44+
{
45+
$object = $this->objects[$name] ?? null;
46+
if ($object) {
47+
return $object;
48+
}
49+
50+
$class = $this->classes[$name] ?? '';
51+
if (class_exists($class)) {
52+
$object = new $class();
53+
if ($this->type->isTypeOf($object)) {
54+
$this->objects[$name] = $object;
55+
return $object;
56+
}
57+
}
58+
59+
return null;
60+
}
61+
62+
public function getIterator(): Enumerator
63+
{
64+
$names = array_keys($this->classes);
65+
foreach ($names as $name) {
66+
$this->get($name);
67+
}
68+
69+
return new Enumerator($this->objects);
70+
}
71+
72+
public static function register(string $name, string $class): void
73+
{
74+
static::getSingleton()->set($name, $class);
75+
}
76+
}

0 commit comments

Comments
 (0)