| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\FieldsAPI; |
| 4 |
|
| 5 |
use Give\Framework\Exceptions\Primitives\RuntimeException; |
| 6 |
|
| 7 |
/** |
| 8 |
* @since 2.32.0 added description |
| 9 |
* @since 2.28.0 |
| 10 |
*/ |
| 11 |
class Checkbox extends Field |
| 12 |
{ |
| 13 |
use Concerns\HasHelpText; |
| 14 |
use Concerns\HasLabel; |
| 15 |
use Concerns\HasDescription; |
| 16 |
|
| 17 |
const TYPE = 'checkbox'; |
| 18 |
|
| 19 |
/** |
| 20 |
* @var bool whether the checkbox is checked by default |
| 21 |
*/ |
| 22 |
protected $checked = false; |
| 23 |
|
| 24 |
/** |
| 25 |
* @var mixed the value of the checkbox when checked |
| 26 |
*/ |
| 27 |
protected $value; |
| 28 |
|
| 29 |
/** |
| 30 |
* Sets the value the checkbox returns when checked. |
| 31 |
* |
| 32 |
* The default value is also set because the getDefaultMethod() method is not called during serialization. |
| 33 |
* |
| 34 |
* @since 2.28.0 |
| 35 |
*/ |
| 36 |
public function value($value): self |
| 37 |
{ |
| 38 |
$this->value = $value; |
| 39 |
$this->defaultValue = $this->checked ? $value : null; |
| 40 |
|
| 41 |
return $this; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* @since 2.28.0 |
| 46 |
*/ |
| 47 |
public function getValue() |
| 48 |
{ |
| 49 |
return $this->value; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Since the default value needs to reflect the value of the checkbox, this method is not supported. |
| 54 |
* |
| 55 |
* @since 2.28.0 |
| 56 |
*/ |
| 57 |
public function defaultValue($defaultValue) |
| 58 |
{ |
| 59 |
throw new RuntimeException( |
| 60 |
'Do not set the default value. Instead, set the value and use the checked() method.' |
| 61 |
); |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Sets the checkbox as checked by default |
| 66 |
* |
| 67 |
* The default value is also set because the getDefaultMethod() method is not called during serialization. |
| 68 |
* |
| 69 |
* @since 2.28.0 |
| 70 |
*/ |
| 71 |
public function checked(bool $checked = true): self |
| 72 |
{ |
| 73 |
$this->checked = $checked; |
| 74 |
$this->defaultValue = $this->checked ? $this->value : null; |
| 75 |
|
| 76 |
return $this; |
| 77 |
} |
| 78 |
|
| 79 |
/** |
| 80 |
* @since 2.28.0 |
| 81 |
*/ |
| 82 |
public function isChecked(): bool |
| 83 |
{ |
| 84 |
return $this->checked; |
| 85 |
} |
| 86 |
} |
| 87 |
|