6 * Element with named flags that can be added, removed, listed and checked.
8 * A flag, when set, adds a CSS class on the `$element` by combining `oo-ui-flaggedElement-` with
9 * the flag name. Flags are primarily useful for styling.
13 trait FlaggedElement {
19 protected $flags = [];
27 * @param array $config Configuration options
28 * @param string|string[] $config['flags'] Flags describing importance and functionality, e.g.
29 * 'primary', 'safe', 'progressive', 'destructive' or 'constructive'
31 public function initializeFlaggedElement( array $config = [] ) {
33 $this->flagged = isset( $config['flagged'] ) ? $config['flagged'] : $this;
36 $this->setFlags( isset( $config['flags'] ) ? $config['flags'] : null );
38 $this->registerConfigCallback( function ( &$config ) {
39 if ( !empty( $this->flags ) ) {
40 $config['flags'] = $this->getFlags();
46 * Check if a flag is set.
48 * @param string $flag Name of flag
49 * @return bool Has flag
51 public function hasFlag( $flag ) {
52 return isset( $this->flags[$flag] );
56 * Get the names of all flags set.
58 * @return string[] Flag names
60 public function getFlags() {
61 return array_keys( $this->flags );
69 public function clearFlags() {
71 $classPrefix = 'oo-ui-flaggedElement-';
73 foreach ( $this->flags as $flag ) {
74 $remove[] = $classPrefix . $flag;
77 $this->flagged->removeClasses( $remove );
84 * Add one or more flags.
86 * @param string|array $flags One or more flags to add, or an array keyed by flag name
87 * containing boolean set/remove instructions.
90 public function setFlags( $flags ) {
93 $classPrefix = 'oo-ui-flaggedElement-';
95 if ( is_string( $flags ) ) {
97 if ( !isset( $this->flags[$flags] ) ) {
98 $this->flags[$flags] = true;
99 $add[] = $classPrefix . $flags;
101 } elseif ( is_array( $flags ) ) {
102 foreach ( $flags as $key => $value ) {
103 if ( is_numeric( $key ) ) {
105 if ( !isset( $this->flags[$value] ) ) {
106 $this->flags[$value] = true;
107 $add[] = $classPrefix . $value;
112 if ( !isset( $this->flags[$key] ) ) {
113 $this->flags[$key] = true;
114 $add[] = $classPrefix . $key;
118 if ( isset( $this->flags[$key] ) ) {
119 unset( $this->flags[$key] );
120 $remove[] = $classPrefix . $key;
129 ->removeClasses( $remove );