| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\FormDesigns\Registrars; |
| 4 |
|
| 5 |
use Give\Framework\Exceptions\Primitives\InvalidArgumentException; |
| 6 |
use Give\Framework\FormDesigns\Exceptions\OverflowException; |
| 7 |
use Give\Framework\FormDesigns\FormDesign; |
| 8 |
use Give\Log\Log; |
| 9 |
|
| 10 |
/** |
| 11 |
* @since 3.0.0 |
| 12 |
*/ |
| 13 |
class FormDesignRegistrar |
| 14 |
{ |
| 15 |
/** |
| 16 |
* @var array |
| 17 |
*/ |
| 18 |
protected $designs = []; |
| 19 |
|
| 20 |
/** |
| 21 |
* @since 3.0.0 |
| 22 |
*/ |
| 23 |
public function getDesigns(): array |
| 24 |
{ |
| 25 |
return $this->designs; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* @since 3.0.0 |
| 30 |
* |
| 31 |
* @throws InvalidArgumentException |
| 32 |
*/ |
| 33 |
public function getDesign(string $id): FormDesign |
| 34 |
{ |
| 35 |
if (!$this->hasDesign($id)) { |
| 36 |
throw new InvalidArgumentException("No design exists with the ID {$id}"); |
| 37 |
} |
| 38 |
|
| 39 |
/** @var FormDesign $design */ |
| 40 |
$design = give($this->designs[$id]); |
| 41 |
|
| 42 |
return $design; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* @since 3.0.0 |
| 47 |
*/ |
| 48 |
public function hasDesign(string $id): bool |
| 49 |
{ |
| 50 |
return isset($this->designs[$id]); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* @since 3.0.0 |
| 55 |
*/ |
| 56 |
public function registerDesign(string $designClass) |
| 57 |
{ |
| 58 |
try { |
| 59 |
$this->register($designClass); |
| 60 |
} catch (InvalidArgumentException $invalidArgumentException) { |
| 61 |
Log::error('Form Design Registration', ['data' => $invalidArgumentException->getMessage()]); |
| 62 |
throw $invalidArgumentException; |
| 63 |
} catch (OverflowException $overflowException) { |
| 64 |
Log::error('Form Design Registration ', ['data' => $overflowException->getMessage()]); |
| 65 |
throw $overflowException; |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* @since 3.0.0 |
| 71 |
*/ |
| 72 |
public function unregisterDesign(string $designId) |
| 73 |
{ |
| 74 |
if ($this->hasDesign($designId)) { |
| 75 |
unset($this->designs[$designId]); |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
/** |
| 80 |
* @since 3.0.0 |
| 81 |
* |
| 82 |
* @return void |
| 83 |
* |
| 84 |
* @throws OverflowException|InvalidArgumentException |
| 85 |
*/ |
| 86 |
private function register(string $designClass) |
| 87 |
{ |
| 88 |
if (!is_subclass_of($designClass, FormDesign::class)) { |
| 89 |
throw new InvalidArgumentException( |
| 90 |
sprintf( |
| 91 |
'%1$s must extend %2$s', |
| 92 |
$designClass, |
| 93 |
FormDesign::class |
| 94 |
) |
| 95 |
); |
| 96 |
} |
| 97 |
|
| 98 |
$designId = $designClass::id(); |
| 99 |
|
| 100 |
if ($this->hasDesign($designId)) { |
| 101 |
throw new OverflowException("Cannot register a design with an id that already exists: $designId"); |
| 102 |
} |
| 103 |
|
| 104 |
$this->designs[$designId] = $designClass; |
| 105 |
|
| 106 |
give()->singleton($designClass); |
| 107 |
} |
| 108 |
} |
| 109 |
|