| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Services\FormBuilder; |
| 4 |
|
| 5 |
use FluentForm\Framework\Helpers\ArrayHelper; |
| 6 |
|
| 7 |
class DateConfigPolicy |
| 8 |
{ |
| 9 |
public static function preserveStored($fields, $storedFields = []) |
| 10 |
{ |
| 11 |
$stored = []; |
| 12 |
self::walk($storedFields, function ($field) use (&$stored) { |
| 13 |
$key = (string) ArrayHelper::get($field, 'uniqElKey'); |
| 14 |
if ('input_date' === ArrayHelper::get($field, 'element') && '' !== $key) { |
| 15 |
$stored[$key] = (string) ArrayHelper::get($field, 'settings.date_config'); |
| 16 |
} |
| 17 |
|
| 18 |
return $field; |
| 19 |
}); |
| 20 |
|
| 21 |
return self::walk($fields, function ($field) use ($stored) { |
| 22 |
if ('input_date' !== ArrayHelper::get($field, 'element')) { |
| 23 |
return $field; |
| 24 |
} |
| 25 |
$key = (string) ArrayHelper::get($field, 'uniqElKey'); |
| 26 |
$field['settings']['date_config'] = $stored[$key] ?? ''; |
| 27 |
|
| 28 |
return $field; |
| 29 |
}); |
| 30 |
} |
| 31 |
|
| 32 |
public static function dropExecutableConfigs($fields, &$dropped = 0) |
| 33 |
{ |
| 34 |
return self::walk($fields, function ($field) use (&$dropped) { |
| 35 |
if ('input_date' !== ArrayHelper::get($field, 'element')) { |
| 36 |
return $field; |
| 37 |
} |
| 38 |
$config = (string) ArrayHelper::get($field, 'settings.date_config'); |
| 39 |
if ('' !== trim($config) && !self::isPlainJsonObject($config)) { |
| 40 |
$dropped++; |
| 41 |
$field['settings']['date_config'] = ''; |
| 42 |
} |
| 43 |
|
| 44 |
return $field; |
| 45 |
}); |
| 46 |
} |
| 47 |
|
| 48 |
// Strict JSON cannot carry functions, so it is safe to emit into the picker's script sink verbatim. |
| 49 |
private static function isPlainJsonObject($config) |
| 50 |
{ |
| 51 |
$config = trim($config); |
| 52 |
if ('{' !== substr($config, 0, 1) || false !== strpos($config, '__ff_')) { |
| 53 |
return false; |
| 54 |
} |
| 55 |
$decoded = json_decode($config, true); |
| 56 |
|
| 57 |
return JSON_ERROR_NONE === json_last_error() && is_array($decoded); |
| 58 |
} |
| 59 |
|
| 60 |
private static function walk($fields, $callback) |
| 61 |
{ |
| 62 |
if (!is_array($fields)) { |
| 63 |
return $fields; |
| 64 |
} |
| 65 |
|
| 66 |
foreach ($fields as &$field) { |
| 67 |
if (isset($field['columns']) && is_array($field['columns'])) { |
| 68 |
foreach ($field['columns'] as &$column) { |
| 69 |
if (isset($column['fields'])) { |
| 70 |
$column['fields'] = self::walk($column['fields'], $callback); |
| 71 |
} |
| 72 |
} |
| 73 |
unset($column); |
| 74 |
} |
| 75 |
if (isset($field['fields'])) { |
| 76 |
$field['fields'] = self::walk($field['fields'], $callback); |
| 77 |
} |
| 78 |
$field = call_user_func($callback, $field); |
| 79 |
} |
| 80 |
unset($field); |
| 81 |
|
| 82 |
return $fields; |
| 83 |
} |
| 84 |
} |
| 85 |
|