<?php
|
namespace JVBase\registrar\config;
|
|
use JVBase\registrar\Registrar;
|
|
if (!defined('ABSPATH')) {
|
exit;
|
}
|
|
final class Section extends Config{
|
protected string $title;
|
protected string $slug;
|
protected string $description = '';
|
protected string $icon = '';
|
protected array $fields = [];
|
protected Registrar $registrar;
|
|
public function __construct(string $title, Registrar $registrar) {
|
$this->title = $title;
|
$this->slug = sanitize_title($title);
|
$this->registrar = $registrar;
|
}
|
|
public function setTitle(string $title): self {
|
$this->title = $title;
|
return $this;
|
}
|
public function getTitle():string
|
{
|
return $this->title;
|
}
|
|
public function setDescription(string $description):self
|
{
|
$this->description = $description;
|
return $this;
|
}
|
public function getDescription():string|array
|
{
|
return $this->description;
|
}
|
|
public function setIcon(string $icon):self
|
{
|
$this->icon = $icon;
|
return $this;
|
}
|
|
protected function checkFields(string|array $fields):string|array
|
{
|
$allFields = $this->registrar->getFields();
|
if (is_array($fields)){
|
foreach ($fields as $index =>$fieldName){
|
if (!array_key_exists($fieldName, $allFields)){
|
error_log('Attempted to add '.$fieldName.' to section. No field defined.');
|
unset($fields[$index]);
|
}
|
}
|
} else {
|
if (!array_key_exists($fields, $allFields)){
|
error_log('Attempted to add '.$fields.' to section. No field defined.');
|
return '';
|
}
|
}
|
return $fields;
|
}
|
|
|
|
public function setFields(array $fields):self
|
{
|
$fields = $this->checkFields($fields);
|
$this->fields = $fields;
|
return $this;
|
}
|
public function addField(string $field):self
|
{
|
$field = $this->checkFields($field);
|
if ($field !== ''){
|
$this->fields[] = $field;
|
}
|
return $this;
|
}
|
|
public function getFields():array
|
{
|
return $this->fields;
|
}
|
|
/**
|
* If the user has defined a 'section' key for this section for specific fields, they can autogenerate the section with this
|
* @return $this
|
*/
|
public function generateFields():self
|
{
|
$this->fields = array_keys(array_filter(Registrar::getInstance($this->slug)->getFields(), function($field){
|
return array_key_exists('section', $field) && $field['section'] === $this->slug;
|
}));
|
return $this;
|
|
}
|
|
public function getConfig(): array
|
{
|
return [
|
'slug' => $this->slug,
|
'title' => $this->title,
|
'description' => $this->description,
|
'icon' => $this->icon,
|
'fields' => $this->fields,
|
];
|
}
|
}
|