| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Features\UserSettings\Factories; |
| 6 |
|
| 7 |
use Metricool\Support\Helpers\Storage; |
| 8 |
use Metricool\Support\Helpers\Collection; |
| 9 |
use Metricool\Features\UserSettings\Exceptions\StorageNotFoundException; |
| 10 |
|
| 11 |
class FieldsFactory |
| 12 |
{ |
| 13 |
private Storage $userSettings; |
| 14 |
|
| 15 |
public function __construct(array $userSettings) |
| 16 |
{ |
| 17 |
$this->userSettings = new Storage($userSettings); |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* Method creates a Collection of Field classes with their respective |
| 22 |
* storage instances based on the configuration found in |
| 23 |
* config/user_settings.php. |
| 24 |
* |
| 25 |
* @throws StorageNotFoundException when a field's storage is not found |
| 26 |
* in the configuration. |
| 27 |
*/ |
| 28 |
public function createFromConfig(): Collection |
| 29 |
{ |
| 30 |
$hydratedStorages = $this->hydrateConfigurationStorages(); |
| 31 |
|
| 32 |
return $this->hydrateConfigurationFields( |
| 33 |
$hydratedStorages |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Method hydrates plain text configuration storages from |
| 39 |
* config/user_settings.php into {@see AbstractStorage} instances based on |
| 40 |
* the configured 'storage' value. |
| 41 |
*/ |
| 42 |
private function hydrateConfigurationStorages(): Collection |
| 43 |
{ |
| 44 |
$storages = []; |
| 45 |
foreach ($this->userSettings->get('storages', []) as $name => $config) { |
| 46 |
$storages[$name] = StorageFactory::createFromConfig($name, $config); |
| 47 |
} |
| 48 |
|
| 49 |
return new Collection($storages); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Method hydrates plain text configuration fields from |
| 54 |
* config/user_settings.php into {@see Field} instances and binds their |
| 55 |
* respective storage instance. |
| 56 |
* |
| 57 |
* @throws StorageNotFoundException when a field's storage is not found |
| 58 |
* in the configuration returned from {@see hydrateConfigurationStorages}. |
| 59 |
*/ |
| 60 |
private function hydrateConfigurationFields(Collection $convertedStorages): Collection |
| 61 |
{ |
| 62 |
$fields = []; |
| 63 |
foreach ($this->userSettings->get('fields', []) as $name => $config) { |
| 64 |
$field = FieldFactory::createFromConfig($name, $config); |
| 65 |
$storage = $convertedStorages->where('name', $field->getStorageName())->first(); |
| 66 |
|
| 67 |
// Abort when storage not present in config |
| 68 |
if ($storage == null) { |
| 69 |
throw new StorageNotFoundException('Storage "' . esc_html($field->getStorageName()) . '" not found for field: ' . esc_html($field->getName())); |
| 70 |
} |
| 71 |
|
| 72 |
// Set validated storage to the field |
| 73 |
$field->setStorage($storage); |
| 74 |
|
| 75 |
// Add the field to the list |
| 76 |
$fields[$name] = $field; |
| 77 |
} |
| 78 |
|
| 79 |
return new Collection($fields); |
| 80 |
} |
| 81 |
} |
| 82 |
|