adrema/app/Form/Fields/CheckboxesField.php

99 lines
2.3 KiB
PHP
Raw Normal View History

2023-12-26 01:05:45 +01:00
<?php
namespace App\Form\Fields;
2024-02-16 14:18:16 +01:00
use App\Form\Models\Form;
use App\Form\Models\Participant;
2024-02-09 23:22:49 +01:00
use App\Form\Presenters\EnumPresenter;
use App\Form\Presenters\Presenter;
2023-12-26 20:06:57 +01:00
use Faker\Generator;
2024-02-06 01:45:25 +01:00
use Illuminate\Validation\Rule;
2023-12-26 20:06:57 +01:00
2023-12-26 01:05:45 +01:00
class CheckboxesField extends Field
{
2024-02-06 01:45:25 +01:00
/** @var array<int, string> */
public array $options;
2024-06-10 17:46:41 +02:00
public ?int $min;
public ?int $max;
2024-02-06 01:45:25 +01:00
2023-12-26 01:05:45 +01:00
public static function name(): string
{
return 'Checkboxes';
}
public static function meta(): array
{
return [
2023-12-26 20:20:32 +01:00
['key' => 'options', 'default' => [], 'rules' => ['options' => 'array', 'options.*' => 'required|string'], 'label' => 'Optionen'],
2024-06-10 17:46:41 +02:00
['key' => 'min', 'default' => null, 'rules' => ['min' => 'present'], 'label' => 'minimale Anzahl'],
['key' => 'max', 'default' => null, 'rules' => ['max' => 'present'], 'label' => 'maximale Anzahl'],
2023-12-26 01:05:45 +01:00
];
}
public static function default()
{
return [];
}
2023-12-26 20:06:57 +01:00
public static function fake(Generator $faker): array
{
2023-12-27 22:39:23 +01:00
return [
'options' => $faker->words(4),
2024-06-10 17:46:41 +02:00
'min' => null,
'max' => null,
2023-12-27 22:39:23 +01:00
];
2023-12-26 20:06:57 +01:00
}
2024-02-06 01:45:25 +01:00
/**
* @inheritdoc
*/
2024-02-19 02:10:58 +01:00
public function getRegistrationRules(Form $form): array
2024-02-06 01:45:25 +01:00
{
2024-06-10 17:46:41 +02:00
$globalRules = ['array'];
if ($this->min > 0) {
$globalRules[] = 'min:' . $this->min;
}
if ($this->max > 0) {
$globalRules[] = 'max:' . $this->max;
}
2024-02-06 01:45:25 +01:00
return [
2024-06-10 17:46:41 +02:00
$this->key => $globalRules,
2024-02-06 01:45:25 +01:00
$this->key . '.*' => ['string', Rule::in($this->options)],
];
}
/**
* @inheritdoc
*/
2024-02-19 02:10:58 +01:00
public function getRegistrationAttributes(Form $form): array
2024-02-06 01:45:25 +01:00
{
return [
...collect($this->options)->mapWithKeys(fn ($option, $key) => [$this->key . '.' . $key => $this->name])->toArray(),
$this->key => $this->name,
];
}
/**
* @inheritdoc
*/
2024-02-19 02:10:58 +01:00
public function getRegistrationMessages(Form $form): array
2024-02-06 01:45:25 +01:00
{
return [];
}
2024-02-09 23:22:49 +01:00
public function getPresenter(): Presenter
{
return app(EnumPresenter::class);
}
2024-02-16 14:18:16 +01:00
2024-02-16 14:32:16 +01:00
/**
* @inheritdoc
*/
2024-02-16 14:18:16 +01:00
public function afterRegistration(Form $form, Participant $participant, array $input): void
{
}
2023-12-26 01:05:45 +01:00
}