*/ public static function fromPages(): array { $names = []; foreach (PageRepository::pageValueRows() as $row) { foreach (PageRepository::decode($row->page_value)['pages'] ?? [] as $page) { foreach ($page['fields'] ?? [] as $field) { if (!empty($field['field_name'])) { $names[] = $field['field_name']; } } } } return array_values(array_unique($names)); } /** * Rebuild `aop_option_names`, and the list of fields for the shortcode and the blocks, from the stored pages. */ public static function sync(): void { update_option(Plugin::PREFIX_ . 'option_names', self::fromPages()); PublicFields::rebuild(); } /** * A page was created: give every option of its fields its default value, with the autoload of the field. * Options that already exist keep their value. * * @param array $pageValue The stored page value. */ public static function createFor(array $pageValue): void { foreach (self::fieldsWithDefaults($pageValue) as $field) { $autoload = ($field['toggle_autoload'] ?? 'yes') === 'no' ? 'no' : 'yes'; add_option($field['field_name'], $field['default_value'], '', $autoload); } } /** * A page was saved again: make sure every option exists (a new field) and follows the autoload setting of its * field. The value of an existing option is kept, also when it is empty or 0. * * @param array $pageValue The stored page value. */ public static function updateFor(array $pageValue): void { $missing = '__aop_missing__'; foreach (self::fieldsWithDefaults($pageValue) as $field) { $autoload = isset($field['toggle_autoload']) ? $field['toggle_autoload'] : 'yes'; $current = get_option($field['field_name'], $missing); Plugin::updateOption($field['field_name'], $current === $missing ? $field['default_value'] : $current, $autoload); } } /** * @return array The stored fields that have an option and a default value. */ private static function fieldsWithDefaults(array $pageValue): array { $fields = []; foreach ($pageValue['pages'] ?? [] as $page) { foreach ($page['fields'] ?? [] as $field) { if (isset($field['default_value']) && isset($field['field_name'])) { $fields[] = $field; } } } return $fields; } }