$subject_types Subjects. * @param string $field Context field. * @param string $operator eq|neq|in|not_in|gt|lt|gte|lte|truthy|falsy. * @param string $config_key Config key for the comparison value. */ public function __construct( private readonly string $identifier, private readonly string $label, private readonly array $subject_types, private readonly string $field, private readonly string $operator, private readonly string $config_key = 'value', ) {} /** * {@inheritDoc} */ public function identifier(): string { return $this->identifier; } /** * {@inheritDoc} */ public function label(): string { return $this->label; } /** * {@inheritDoc} * * @return list */ public function subject_types(): array { return $this->subject_types; } /** * {@inheritDoc} * * @param AutomationContext $ctx Context. * @param array $config Config. */ public function evaluate( AutomationContext $ctx, array $config ): bool { $actual = $ctx->fields()[ $this->field ] ?? null; $expect = $config[ $this->config_key ] ?? null; return match ( $this->operator ) { 'eq' => $this->stringify( $actual ) === $this->stringify( $expect ), 'neq' => $this->stringify( $actual ) !== $this->stringify( $expect ), 'in' => in_array( $this->stringify( $actual ), $this->as_list( $expect ), true ), 'not_in' => ! in_array( $this->stringify( $actual ), $this->as_list( $expect ), true ), 'gt' => is_numeric( $actual ) && is_numeric( $expect ) && (float) $actual > (float) $expect, 'lt' => is_numeric( $actual ) && is_numeric( $expect ) && (float) $actual < (float) $expect, 'gte' => is_numeric( $actual ) && is_numeric( $expect ) && (float) $actual >= (float) $expect, 'lte' => is_numeric( $actual ) && is_numeric( $expect ) && (float) $actual <= (float) $expect, 'truthy' => (bool) $actual, 'falsy' => ! (bool) $actual, default => false, }; } /** * {@inheritDoc} * * @return array */ public function schema(): array { $schema = [ 'field' => $this->field, 'operator' => $this->operator, 'key' => $this->config_key, ]; if ( 'truthy' !== $this->operator && 'falsy' !== $this->operator ) { $schema['fields'] = [ [ 'name' => $this->config_key, 'type' => 'text', 'label' => 'Value', 'required' => true, ], ]; } return $schema; } /** * Stringify a scalar. * * @param mixed $value Value. */ private function stringify( mixed $value ): string { if ( is_bool( $value ) ) { return $value ? '1' : '0'; } return is_scalar( $value ) ? (string) $value : ''; } /** * Config value as a list of strings. * * @param mixed $value Value. * @return list */ private function as_list( mixed $value ): array { if ( is_array( $value ) ) { $out = []; foreach ( $value as $item ) { $out[] = $this->stringify( $item ); } return $out; } return [ $this->stringify( $value ) ]; } }