RockLobsterInc\Swv\Rules

TelRule{} │ final │ CF7 1.0└─ AbstractRule

Хуков нет.

Использование

$TelRule = new TelRule();
// use class methods

Методы

  1. public __construct(array $properties = [])
  2. public static isTel(string $value)
  3. public matches(array $context)
  4. public toArray()
  5. public validate(FormDataTree $form_data, array $context = [])

Код TelRule{} CF7 6.2.4.1

final class TelRule extends AbstractRule
{
    const RULE_NAME = "tel";

    /**
     * Rule properties.
     */
    public readonly string $field;
    public readonly string $error;

    /**
     * Constructor.
     *
     * @param array $properties Rule properties.
     */
    public function __construct(array $properties = [])
    {
        $this->field = $properties["field"] ?? "";
        $this->error = $properties["error"] ?? "";
    }

    /**
     * Returns true if the given string is a well-formed telephone number.
     *
     * @param string $value String to check.
     */
    public static function isTel(string $value): bool
    {
        $value = preg_replace('/[#*].*$/', "", $value); // Remove extension.
        $value = preg_replace("%[()/.*#\s-]+%", "", $value);

        $is_international =
            "+" === substr($value, 0, 1) || "00" === substr($value, 0, 2);

        if ($is_international) {
            $value = "+" . preg_replace("/^[+0]+/", "", $value);
        }

        if (!preg_match('/^[+]?[0-9]+$/', $value)) {
            return false;
        }

        if (!(5 < strlen($value) and strlen($value) < 16)) {
            return false;
        }

        return true;
    }

    /**
     * Returns true if this rule matches the given context.
     *
     * @param array $context Context.
     */
    public function matches(array $context): bool
    {
        if (false === parent::matches($context)) {
            return false;
        }

        if (empty($context["text"])) {
            return false;
        }

        return true;
    }

    /**
     * Validates the form data according to the logic defined by this rule.
     *
     * @param FormDataTree $form_data Form data.
     * @param array $context Optional context.
     */
    public function validate(FormDataTree $form_data, array $context = [])
    {
        $values = $form_data->getAll($this->field);
        $values = array_flatten($values);

        if (empty($values)) {
            return true;
        }

        foreach ($values as $value) {
            if (!self::isTel($value)) {
                throw new Invalidity($this, ["cause" => $value]);
            }
        }

        return true;
    }

    /**
     * Returns an array that represents the rule properties.
     *
     * @return array Array of rule properties.
     */
    public function toArray(): array
    {
        return [
            "rule" => self::RULE_NAME,
            "field" => $this->field,
            "error" => $this->error,
        ];
    }
}