<?php

namespace Core\Form\Element;

use Laminas\Form\Element;
use Laminas\InputFilter\InputProviderInterface;
use Laminas\Validator\Regex as RegexValidator;

class Phone extends Element implements InputProviderInterface
{
    /**
     * @var \Laminas\Validator\ValidatorInterface
     */
    protected $validator;

    /**
    * Get a validator if none has been set.
    * https://github.com/posabsolute/jQuery-Validation-Engine/issues/265
    * @return RegexValidator
    */
    public function getValidator()
    {
        if (null === $this->validator) {
            $validator = new RegexValidator('~^(\+\d\d)?[0-9 ()]+$~');
            $validator->setMessage(
                /*@translate */ 'Please enter a phone Number. May start with \'+\'. Only digits, \'(\', \')\' and \' \'.',
                RegexValidator::NOT_MATCH
            );

            $this->validator = $validator;
        }

        return $this->validator;
    }

    /**
     * Sets the validator to use for this element
     *
     * @param  RegexValidator $validator
     * @return Phone
     */
    public function setValidator(RegexValidator $validator)
    {
        $this->validator = $validator;
        return $this;
    }

    /**
     * Provide default input rules for this element
     *
     * Attaches a phone number validator.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        return array(
            'name' => $this->getName(),
            'required' => true,
            'filters' => array(
                array('name' => 'Laminas\Filter\StringTrim'),
            ),
            'validators' => array(
                $this->getValidator(),
            ),
        );
    }
}
