| 1 |
<?php |
| 2 |
|
| 3 |
namespace SimpleAnalytics\Settings\Blocks\Fields; |
| 4 |
|
| 5 |
use Closure; |
| 6 |
use SimpleAnalytics\Setting; |
| 7 |
use SimpleAnalytics\Settings\Concerns\HasDocs; |
| 8 |
use SimpleAnalytics\UI\LabelComponent; |
| 9 |
|
| 10 |
class Checkboxes extends Field |
| 11 |
{ |
| 12 |
use HasDocs; |
| 13 |
|
| 14 |
/** @var array<mixed, string> */ |
| 15 |
protected $options; |
| 16 |
|
| 17 |
/** |
| 18 |
* @param mixed[]|\Closure $options |
| 19 |
*/ |
| 20 |
public function options($options): self |
| 21 |
{ |
| 22 |
$this->options = $options instanceof Closure ? $options() : $options; |
| 23 |
|
| 24 |
return $this; |
| 25 |
} |
| 26 |
|
| 27 |
public function getValueType(): string |
| 28 |
{ |
| 29 |
return 'array'; |
| 30 |
} |
| 31 |
|
| 32 |
public function getValueSanitizer(): callable |
| 33 |
{ |
| 34 |
return function ($value) { |
| 35 |
if (! is_array($value)) $value = [$value]; |
| 36 |
|
| 37 |
return array_filter($value, function ($item) { |
| 38 |
return array_key_exists($item, $this->options); |
| 39 |
}); |
| 40 |
}; |
| 41 |
} |
| 42 |
|
| 43 |
public function render(): void |
| 44 |
{ |
| 45 |
$currentValue = Setting::array($this->getKey()); |
| 46 |
?> |
| 47 |
<fieldset> |
| 48 |
<?php |
| 49 |
(new LabelComponent($this->getLabel(), $this->docs, null, 'legend'))(); |
| 50 |
?> |
| 51 |
<div class="mt-2 space-y-2"> |
| 52 |
<?php |
| 53 |
foreach ($this->options as $value => $label): ?> |
| 54 |
<div class="relative flex items-start"> |
| 55 |
<div class="flex h-6 items-center"> |
| 56 |
<input |
| 57 |
id="<?php echo esc_attr($this->getKey() . '-' . $value); ?>" |
| 58 |
name="<?php echo esc_attr($this->getKey()); ?>[]" |
| 59 |
type="checkbox" |
| 60 |
value="<?php echo esc_attr($value); ?>" |
| 61 |
<?php checked(in_array($value, $currentValue)); ?> |
| 62 |
class="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary" |
| 63 |
> |
| 64 |
</div> |
| 65 |
<div class="ml-3 text-sm leading-6"> |
| 66 |
<label |
| 67 |
for="<?php echo esc_attr($this->getKey() . '-' . $value); ?>" |
| 68 |
class="font-medium text-gray-900" |
| 69 |
> |
| 70 |
<?php echo esc_html($label); ?> |
| 71 |
</label> |
| 72 |
</div> |
| 73 |
</div> |
| 74 |
<?php endforeach; |
| 75 |
?> |
| 76 |
</div> |
| 77 |
<?php |
| 78 |
if ($this->description): ?> |
| 79 |
<p class="mt-2 text-gray-500"> |
| 80 |
<?php echo esc_html($this->description); ?> |
| 81 |
</p> |
| 82 |
<?php endif; |
| 83 |
?> |
| 84 |
</fieldset> |
| 85 |
<?php |
| 86 |
} |
| 87 |
} |
| 88 |
|