handler.php 2.84 KB
<?php
## params
$mailTo = 'mind.it@ya.ru';
## fields
$name  = isset($_POST['name'])   ? $_POST['name'] : null;
$phone = isset($_POST['phone'])  ? $_POST['phone']      : null;
$city  = isset($_POST['city'])   ? $_POST['city']       : null;
$email = isset($_POST['email'])  ? $_POST['email']      : null;
$till  = isset($_POST['till'])   ? $_POST['till']       : null;
$from  = isset($_POST['from'])   ? $_POST['from']       : null;
## additional fields
$type = isset($_POST['type']) ? $_POST['type'] : null;
switch ($type) {
    case 'callback':
        $data = ['phone' => $phone, 'from' => $from, 'till' => $till];
        $callback = new callback($data);
        $callback->send($data);
        echo json_encode(array('type'=>'success_send', 'text'=>'Ваша заявка успешно отправлена'));
        break;

    case 'order':
        $data = ['name' => $name, 'email' => $email, 'city' =>  $city,];
        $order = new order($data);
        $order->send($data);
        break;

    default:
        echo json_encode(array('type'=>'no_template', 'text'=>'Задайте шаблон обработчика!'));
        break;
}

class Form{

    public static function validate($data, $field = null)
    {
        switch ($field) {

            case 'phone':
                if (!preg_match("/^(8|\+7) ? ?\(?(\d{3})\)? ?(\d{3})[ -]?(\d{2})[ -]?(\d{2})/", $data))
                    die(json_encode(array('type'=>'error_phone', 'text'=>'Телефон введен неверно')));
                return $data;
                break;
            case 'name':
                if (mb_strlen($data) <= 1)
                    die(json_encode(array('type'=>'error_name', 'text'=>'Вы не ввели имя')));
                return $data;
                break;
            case 'email':
                if (!preg_match("/.+@.+\..+/i", $data))
                    die(json_encode(array('type'=>'error_email', 'text'=>'Почтовый адрес введен неверно')));
                return $data;
                break;
            default:
                if (strlen($data) < 2)
                    die(json_encode(array('type'=>'error', 'text'=>"Поле $field пусто")));
                return $data;
        }
    }
    public function send(array $data)
    {
    }
}

class callback extends Form {

    public $phone;
    public $till;
    public $from;
    
    
    function __construct(array $data)
    {
        $this->phone = Form::validate($data['phone'], 'phone');
        $this->till = $data['till'];
        $this->from = $data['from'];
    }
}

class order extends Form {

    public $name;
    public $city;
    public $email;


    function __construct(array $data)
    {
        $this->name = Form::validate($data['name'], 'name');
        $this->city = $data['city'];
        $this->email = Form::validate($data['email'], 'email');
    }
}