| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\Core; |
| 6 |
|
| 7 |
use InvalidArgumentException; |
| 8 |
use function is_string; |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
class AlgorithmManagerFactory |
| 14 |
{ |
| 15 |
private array $algorithms = []; |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
public function __construct(iterable $algorithms = []) |
| 21 |
{ |
| 22 |
foreach ($algorithms as $algorithm) { |
| 23 |
$this->add($algorithm->name(), $algorithm); |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public function add(string $alias, Algorithm $algorithm): void |
| 34 |
{ |
| 35 |
$this->algorithms[$alias] = $algorithm; |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
public function aliases(): array |
| 44 |
{ |
| 45 |
return array_keys($this->algorithms); |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
public function all(): array |
| 55 |
{ |
| 56 |
return $this->algorithms; |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public function create(array $aliases): AlgorithmManager |
| 65 |
{ |
| 66 |
$algorithms = []; |
| 67 |
foreach ($aliases as $alias) { |
| 68 |
if (! is_string($alias)) { |
| 69 |
throw new InvalidArgumentException('Invalid alias'); |
| 70 |
} |
| 71 |
if (! isset($this->algorithms[$alias])) { |
| 72 |
throw new InvalidArgumentException(sprintf( |
| 73 |
'The algorithm with the alias "%s" is not supported.', |
| 74 |
$alias |
| 75 |
)); |
| 76 |
} |
| 77 |
$algorithms[] = $this->algorithms[$alias]; |
| 78 |
} |
| 79 |
|
| 80 |
return new AlgorithmManager($algorithms); |
| 81 |
} |
| 82 |
} |