<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Validators;


use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Forms\Validators\BaseValidator;
use ModulesGarden\Servers\ZimbraEmail\Core\UI\Widget\Forms\Validators\boolen;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 16.10.19
 * Time: 12:21
 * Class TaggerEmailValidator
 */
class TaggerEmailValidator extends BaseValidator
{

    private $invalidEmails = [];

    /**
     * return true if data is valid, false if not,
     * add error messages to $errorsList
     *
     * @param $data mixed
     * @param $additionalData mixed
     * @return boolen
     */
    protected function validate($data, $additionalData = null)
    {
        /**
         * return if empty
         */
        if (trim($data) === '')
        {
            return true;
        }

        /**
         * explode emails
         */
        $emails = explode(',',$data);

        /**
         * check each email and add to invalid if true
         */
        foreach($emails as $email)
        {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL))
            {
                $this->invalidEmails[] = html_entity_decode($email);
            }
        }

        /**
         * return invalid message
         */
        if($this->invalidEmails)
        {
            $this->addValidationError('incorrectEmailAddresses',false,['emails' => implode(',', $this->invalidEmails)]);
            return false;
        }

        return true;
    }
}