| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Features\UserSettings\Factories; |
| 6 |
|
| 7 |
use Metricool\Features\UserSettings\Fields\Field; |
| 8 |
use Metricool\Features\UserSettings\Storage\AbstractStorage; |
| 9 |
|
| 10 |
class FieldFactory |
| 11 |
{ |
| 12 |
private const FIELDS_NAMESPACE = '\\Metricool\\Features\\UserSettings\\Fields\\'; |
| 13 |
|
| 14 |
/** |
| 15 |
* Creates a field from the user_settings configuration |
| 16 |
* @see config/user_settings.php |
| 17 |
*/ |
| 18 |
public static function createFromConfig(string $name, array $config, ?AbstractStorage $storage = null): Field |
| 19 |
{ |
| 20 |
$fieldClassName = ($config['field'] ?? 'Field'); |
| 21 |
$fieldClass = self::FIELDS_NAMESPACE . $fieldClassName; |
| 22 |
|
| 23 |
if (!class_exists($fieldClass)) { |
| 24 |
throw new \InvalidArgumentException('Field "' . esc_html($fieldClass) . '" not found'); |
| 25 |
} |
| 26 |
|
| 27 |
$field = new $fieldClass($name); |
| 28 |
$field->applyConfig($config); |
| 29 |
|
| 30 |
if ($storage !== null) { |
| 31 |
$field->setStorage($storage); |
| 32 |
} |
| 33 |
|
| 34 |
return $field; |
| 35 |
} |
| 36 |
} |
| 37 |
|