| 1 |
<?php |
| 2 |
|
| 3 |
namespace SimpleAnalytics\Settings\Concerns; |
| 4 |
|
| 5 |
use SimpleAnalytics\Settings\Blocks\Fields\Field; |
| 6 |
use SimpleAnalytics\Settings\Tab; |
| 7 |
use SimpleAnalytics\UI\PageLayoutComponent; |
| 8 |
|
| 9 |
trait WordPressPageIntegration |
| 10 |
{ |
| 11 |
public function register(): void |
| 12 |
{ |
| 13 |
add_action('admin_menu', [$this, 'wpAddMenu']); |
| 14 |
add_action('admin_init', [$this, 'wpAddFields']); |
| 15 |
} |
| 16 |
|
| 17 |
public function getOptionGroup(Tab $tab): string |
| 18 |
{ |
| 19 |
return $this->getSlug() . '-' . $tab->getSlug(); |
| 20 |
} |
| 21 |
|
| 22 |
/** @internal */ |
| 23 |
public function wpAddMenu(): void |
| 24 |
{ |
| 25 |
add_options_page($this->getTitle(), $this->getTitle(), 'manage_options', $this->getSlug(), (new PageLayoutComponent($this))); |
| 26 |
} |
| 27 |
|
| 28 |
/** @internal */ |
| 29 |
public function wpAddFields(): void |
| 30 |
{ |
| 31 |
foreach ($this->getTabs() as $tab) { |
| 32 |
$this->registerTab($tab); |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
protected function registerTab(Tab $tab): void |
| 37 |
{ |
| 38 |
$fields = array_filter($tab->getBlocks(), function ($block) { |
| 39 |
return $block instanceof Field; |
| 40 |
}); |
| 41 |
|
| 42 |
foreach ($fields as $field) { |
| 43 |
$this->registerField($field, $tab); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
protected function registerField(Field $field, Tab $tab): void |
| 48 |
{ |
| 49 |
register_setting( |
| 50 |
$this->getOptionGroup($tab), |
| 51 |
$field->getKey(), |
| 52 |
[ |
| 53 |
'type' => $field->getValueType(), |
| 54 |
'sanitize_callback' => $field->getValueSanitizer(), |
| 55 |
] |
| 56 |
); |
| 57 |
} |
| 58 |
} |
| 59 |
|