| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* The MIT License (MIT) |
| 7 |
* |
| 8 |
* Copyright (c) 2014-2020 Spomky-Labs |
| 9 |
* |
| 10 |
* This software may be modified and distributed under the terms |
| 11 |
* of the MIT license. See the LICENSE file for details. |
| 12 |
*/ |
| 13 |
|
| 14 |
namespace Jose\Component\Core; |
| 15 |
|
| 16 |
use InvalidArgumentException; |
| 17 |
use function is_string; |
| 18 |
|
| 19 |
class AlgorithmManagerFactory |
| 20 |
{ |
| 21 |
/** |
| 22 |
* @var array |
| 23 |
*/ |
| 24 |
private $algorithms = []; |
| 25 |
|
| 26 |
/** |
| 27 |
* Adds an algorithm. |
| 28 |
* |
| 29 |
* Each algorithm is identified by an alias hence it is allowed to have the same algorithm twice (or more). |
| 30 |
* This can be helpful when an algorithm have several configuration options. |
| 31 |
*/ |
| 32 |
public function add(string $alias, Algorithm $algorithm): void |
| 33 |
{ |
| 34 |
$this->algorithms[$alias] = $algorithm; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Returns the list of aliases. |
| 39 |
* |
| 40 |
* @return string[] |
| 41 |
*/ |
| 42 |
public function aliases(): array |
| 43 |
{ |
| 44 |
return array_keys($this->algorithms); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Returns all algorithms supported by this factory. |
| 49 |
* This is an associative array. Keys are the aliases of the algorithms. |
| 50 |
* |
| 51 |
* @return Algorithm[] |
| 52 |
*/ |
| 53 |
public function all(): array |
| 54 |
{ |
| 55 |
return $this->algorithms; |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Create an algorithm manager using the given aliases. |
| 60 |
* |
| 61 |
* @param string[] $aliases |
| 62 |
* |
| 63 |
* @throws InvalidArgumentException if the alias is invalid or is not supported |
| 64 |
*/ |
| 65 |
public function create(array $aliases): AlgorithmManager |
| 66 |
{ |
| 67 |
$algorithms = []; |
| 68 |
foreach ($aliases as $alias) { |
| 69 |
if (!is_string($alias)) { |
| 70 |
throw new InvalidArgumentException('Invalid alias'); |
| 71 |
} |
| 72 |
if (!isset($this->algorithms[$alias])) { |
| 73 |
throw new InvalidArgumentException(sprintf('The algorithm with the alias "%s" is not supported.', $alias)); |
| 74 |
} |
| 75 |
$algorithms[] = $this->algorithms[$alias]; |
| 76 |
} |
| 77 |
|
| 78 |
return new AlgorithmManager($algorithms); |
| 79 |
} |
| 80 |
} |
| 81 |
|