Carbon_Fields\Field\Field::parse_conditional_rules PHP Method

parse_conditional_rules() protected method

Validate and parse the conditional logic rules.
protected parse_conditional_rules ( array $rules ) : array
$rules array
return array
    protected function parse_conditional_rules($rules)
    {
        if (!is_array($rules)) {
            Incorrect_Syntax_Exception::raise('Conditional logic rules argument should be an array.');
        }
        $allowed_operators = array('=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN');
        $allowed_relations = array('AND', 'OR');
        $parsed_rules = array('relation' => 'AND', 'rules' => array());
        foreach ($rules as $key => $rule) {
            // Check if we have a relation key
            if ($key === 'relation') {
                $relation = strtoupper($rule);
                if (!in_array($relation, $allowed_relations)) {
                    Incorrect_Syntax_Exception::raise('Invalid relation type ' . $rule . '. ' . 'The rule should be one of the following: "' . implode('", "', $allowed_relations) . '"');
                }
                $parsed_rules['relation'] = $relation;
                continue;
            }
            // Check if the rule is valid
            if (!is_array($rule) || empty($rule['field'])) {
                Incorrect_Syntax_Exception::raise('Invalid conditional logic rule format. ' . 'The rule should be an array with the "field" key set.');
            }
            // Check the compare operator
            if (empty($rule['compare'])) {
                $rule['compare'] = '=';
            }
            if (!in_array($rule['compare'], $allowed_operators)) {
                Incorrect_Syntax_Exception::raise('Invalid conditional logic compare operator: <code>' . $rule['compare'] . '</code><br>Allowed operators are: <code>' . implode(', ', $allowed_operators) . '</code>');
            }
            if ($rule['compare'] === 'IN' || $rule['compare'] === 'NOT IN') {
                if (!is_array($rule['value'])) {
                    Incorrect_Syntax_Exception::raise('Invalid conditional logic value format. ' . 'An array is expected, when using the "' . $rule['compare'] . '" operator.');
                }
            }
            // Check the value
            if (!isset($rule['value'])) {
                $rule['value'] = '';
            }
            $parsed_rules['rules'][] = $rule;
        }
        return $parsed_rules;
    }