Debian Codegraph @

vendor/oojs/oojs-ui/php/mixins/RequiredElement.php

raw
1 <?php
2
3 namespace OOUI;
4
5 /**
6 * Element with a required attribute.
7 *
8 * @abstract
9 */
10 trait RequiredElement {
11 /**
12 * Mark as required.
13 *
14 * @var bool
15 */
16 protected $required = false;
17
18 /**
19 * @var Element
20 */
21 protected $requiredElement;
22
23 /**
24 * @var IndicatorElement|null
25 */
26 protected $indicatorElement;
27
28 /**
29 * @var Element|null
30 */
31 protected $input;
32
33 /**
34 * @param array $config Configuration options
35 * - bool $config['required'] Mark the field as required.
36 * Implies `indicator: 'required'`. Note that `false` & setting `indicator: 'required'
37 * will result in no indicator shown. (default: false)
38 * - Element $config['requiredElement']
39 * - IndicatorElement $config['indicatorElement']
40 */
41 public function initializeRequiredElement( array $config = [] ) {
42 // Properties
43 $this->requiredElement = $config['requiredElement'] ?? ( $this->input ?? $this );
44 $this->indicatorElement = array_key_exists( 'indicatorElement', $config ) ? $config['indicatorElement'] : $this;
45
46 if ( $this->indicatorElement && !method_exists( $this->indicatorElement, 'getIndicator' ) ) {
47 throw new Exception( 'config[\'indicatorElement\'] must use the IndicatorElement trait.' );
48 }
49
50 // Initialization
51 $this->setRequired( $config['required'] ?? false );
52
53 $this->registerConfigCallback( function ( &$config ) {
54 $config['required'] = $this->required;
55 } );
56 }
57
58 /**
59 * Check if the widget is required.
60 *
61 * @return bool
62 */
63 public function isRequired(): bool {
64 return $this->required;
65 }
66
67 /**
68 * Set the required state of the widget.
69 *
70 * @param bool $state Make input required
71 * @return $this
72 */
73 public function setRequired( bool $state ) {
74 $this->required = $state;
75 if ( $this->required ) {
76 $this->requiredElement->setAttributes( [
77 'required' => null
78 ] );
79 if ( $this->indicatorElement && $this->indicatorElement->getIndicator() === null ) {
80 $this->indicatorElement->setIndicator( 'required' );
81 }
82 } else {
83 $this->requiredElement->removeAttributes( [
84 'required'
85 ] );
86 if ( $this->indicatorElement && $this->indicatorElement->getIndicator() === 'required' ) {
87 $this->indicatorElement->setIndicator( null );
88 }
89 }
90 return $this;
91 }
92
93 /**
94 * @param callable $func
95 */
96 abstract public function registerConfigCallback( callable $func );
97 }