conditions = $conditions ?? new ConditionGroup(); } /** * Returns every action with its label. * * @return array Translated labels keyed by action. */ public static function actions(): array { return array( self::SHOW => __( 'Show this field', 'devplugins-custom-form-builder' ), self::HIDE => __( 'Hide this field', 'devplugins-custom-form-builder' ), self::REQUIRE_FIELD => __( 'Make this field required', 'devplugins-custom-form-builder' ), self::ENABLE => __( 'Enable this field', 'devplugins-custom-form-builder' ), self::DISABLE => __( 'Disable this field', 'devplugins-custom-form-builder' ), ); } /** * Builds a rule from stored data. * * @param mixed $data Stored payload. */ public static function from_array( mixed $data ): LogicRule { if ( ! is_array( $data ) ) { return new self(); } $action = (string) ( $data['action'] ?? self::SHOW ); return new self( ! empty( $data['enabled'] ), array_key_exists( $action, self::actions() ) ? $action : self::SHOW, ConditionGroup::from_array( is_array( $data['rules'] ?? null ) ? $data['rules'] : array() ) ); } /** * Determines whether the rule should be applied. * * A rule switched on but carrying no conditions is treated as inactive, so a * half built rule never hides a field from visitors. * * @return bool True when the rule affects the field. */ public function is_active(): bool { return $this->enabled && ! $this->conditions->is_empty(); } /** * Returns the action taken when the conditions hold. */ public function action(): string { return $this->action; } /** * Returns the conditions. */ public function conditions(): ConditionGroup { return $this->conditions; } /** * Determines whether the conditions hold. * * @param array $values Submitted values keyed by field key. * * @return bool True when the conditions hold. */ public function holds( array $values ): bool { return $this->conditions->evaluate( $values ); } /** * Returns the rule as storable data. * * @return array The payload. */ public function to_array(): array { return array( 'enabled' => $this->enabled, 'action' => $this->action, 'rules' => $this->conditions->to_array(), ); } }