<?php

/* * ********************************************************************
 * ProxmoxAddon product developed. (Aug 23, 2018)
 * *
 *
 *  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
 *  CONTACT                        ->       contact@modulesgarden.com
 *
 *
 * This software is furnished under a license and may be used and copied
 * only  in  accordance  with  the  terms  of such  license and with the
 * inclusion of the above copyright notice.  This software  or any other
 * copies thereof may not be provided or otherwise made available to any
 * other person.  No title to and  ownership of the  software is  hereby
 * transferred.
 *
 *
 * ******************************************************************** */

namespace ModulesGarden\ProxmoxAddon\App\UI\Validators;

use ModulesGarden\ProxmoxAddon\Core\UI\Widget\Forms\Validators\BaseValidator;

/**
 * Description of NumberValidator
 *
 * @author Pawel Kopec <pawelk@modulesgardne.com>
 */
class CidrValidator extends BaseValidator
{
    protected $required = false;

    public function __construct($required = true)
    {
        $this->required = $required;
    }

    protected function validate($data, $additionalData = null)
    {
        if (!$this->required && empty($data))
        {
            return true;
        }
        else
        {
            if ($this->required && empty($data))
            {
                $this->addValidationError('PleaseProvideANumericValue');
                return false;
            }
        }
        $min = 1;
        $max = 32;
        //ipv6 range
        if ($additionalData && $additionalData->get('formData')['ip'] && preg_match('/\:/', $additionalData->get('formData')['ip']))
        {
            $max = 128;
        }
        else
        {
            if ($additionalData && $additionalData->get('formData')['ipPool'] && preg_match('/\:/', $additionalData->get('formData')['ipPool']))
            {
                $max = 128;
            }
        }
        if (!is_numeric($data) || (int)$data < $min || (int)$data > $max)
        {
            $this->addValidationError('PleaseProvideANumericValueBetween', false, ['minValue' => $min, 'maxValue' => $max]);
            return false;
        }
        return true;
    }
}
