Example #1
0
/**
 * Запуск скрипта
 *
 * @param array &$ServiceManager объект сервис-менеджера
 */
function run(array &$ServiceManager)
{
    $shardsConfig = MysqlFactory\getShardsConfig(ServiceManager\getFactory($ServiceManager, 'Mysql'));
    // Заказчики
    $CustomerRepository =& ServiceManager\get($ServiceManager, 'CustomerRepository');
    foreach ($shardsConfig[CustomerRepository\SHARD_CONFIG] as $shardId => $_) {
        CustomerRepository\createShard($CustomerRepository, $shardId);
    }
    CustomerRepository\syncLastCustomerId($CustomerRepository, 0);
    // Два тестовых заказчика
    CustomerRepository\create($CustomerRepository, 'customer_1', 'Петров', '8anbAw4BbuoM');
    CustomerRepository\create($CustomerRepository, 'customer_2', 'Васечкин', 'GZx5ixNwYtos');
    // Заказы
    $OrderRepository =& ServiceManager\get($ServiceManager, 'OrderRepository');
    OrderRepository\createDatabaseAndTable($OrderRepository);
    // Два тестовых заказа
    OrderRepository\create($OrderRepository, 'text', 100);
    OrderRepository\create($OrderRepository, 'text2', 200);
    // Исполнители
    $ExecutorRepository =& ServiceManager\get($ServiceManager, 'ExecutorRepository');
    foreach ($shardsConfig[ExecutorRepository\SHARD_CONFIG] as $shardId => $_) {
        ExecutorRepository\createShard($ExecutorRepository, $shardId);
    }
    ExecutorRepository\syncLastExecutorId($ExecutorRepository, 0);
    // Два тестовых исполнителя
    ExecutorRepository\create($ExecutorRepository, 'executor_1', 'Иванов', 100, '3urvrPhNvEpZ');
    ExecutorRepository\create($ExecutorRepository, 'executor_2', 'Церетели', 200, 'ki22YIk1FR29');
}
Example #2
0
/**
 * @param array &$Response объект ответа
 *
 * @return string контент клиенту
 */
function toString(array &$Response)
{
    $Application =& ServiceManager\get(getServiceManager($Response), 'Application');
    switch (Application\getMode($Application)) {
        case Application\MODE_CLI:
            return toStringCli($Response);
            break;
        case Application\MODE_WEB:
            return toStringWeb($Response);
            break;
        default:
            trigger_error('Неизвестный режим запуска', E_USER_ERROR);
    }
}
Example #3
0
/**
 * @param array &$ServiceManager объект сервис-менеджер
 *
 * @return &array объект фабрики
 */
function &construct(array &$ServiceManager)
{
    $config =& Config\get(ServiceManager\get($ServiceManager, 'Config'), CONFIGURATION_SECTION);
    foreach ($config as $name => $pool) {
        if (count($pool) == 0) {
            trigger_error('Пустой пул серверов для мемкеша [' . $name . ']', E_USER_ERROR);
        }
        foreach ($pool as $server) {
            if (!isset($server[CONFIGURATION_HOST])) {
                trigger_error('Отсутствует параметр [' . CONFIGURATION_HOST . '] для мемкеша [' . $name . ']', E_USER_ERROR);
            }
            if (!isset($server[CONFIGURATION_PORT])) {
                trigger_error('Отсутствует параметр [' . CONFIGURATION_PORT . '] для мемкеша [' . $name . ']', E_USER_ERROR);
            }
        }
    }
    $MemcachedFactory = [FIELD_INSTANCES => [], FIELD_CONFIG => $config];
    return $MemcachedFactory;
}
Example #4
0
/**
 * @param array &$ServiceManager объект сервис-менеджер
 *
 * @return &array объект фабрики
 */
function &construct(array &$ServiceManager)
{
    $config =& Config\get(ServiceManager\get($ServiceManager, 'Config'), CONFIGURATION_SECTION);
    if (isset($config[CONFIGURATION_INSTANCES])) {
        foreach ($config[CONFIGURATION_INSTANCES] as $name => $configuration) {
            validateInstanceConfig($name, $configuration);
        }
    }
    if (isset($config[CONFIGURATION_SHARD_INSTANCES])) {
        foreach ($config[CONFIGURATION_SHARD_INSTANCES] as $name => $configuration) {
            if (!is_array($configuration) || count($configuration) == 0) {
                trigger_error('Пустой конфиг для mysql шард-инстанса [' . $name . ']');
            }
            foreach ($configuration as $shard => $instance) {
                validateInstanceConfig($name, $instance, $shard);
            }
        }
    }
    $MysqlFactory = [FIELD_INSTANCES => [], FIELD_SHARD_INSTANCES => [], FIELD_CONFIG => $config];
    return $MysqlFactory;
}
Example #5
0
/**
 * Запуск скрипта
 *
 * @param array &$ServiceManager объект сервис-менеджера
 */
function run(array &$ServiceManager)
{
    $MysqlFactory =& ServiceManager\getFactory($ServiceManager, 'Mysql');
    $shardsConfig = MysqlFactory\getShardsConfig($MysqlFactory);
    // Заказчики
    $CustomerRepository =& ServiceManager\get($ServiceManager, 'CustomerRepository');
    $maxCustomerId = 1;
    foreach ($shardsConfig[CustomerRepository\SHARD_CONFIG] as $shardId => $_) {
        $Mysql = MysqlFactory\createShard($MysqlFactory, CustomerRepository\SHARD_CONFIG, $shardId);
        $data = Mysql\query($Mysql, 'SELECT * FROM ' . CustomerRepository\DATABASE_NAME . '.' . CustomerRepository\TABLE_NAME);
        while (($customerData = Mysql\fetchAssoc($Mysql, $data)) !== false) {
            $Customer =& Customer\unserializeFromMysql($customerData);
            CustomerRepository\saveToMemcached($CustomerRepository, $Customer);
            CustomerRepository\savePasswordHashToMemcached($CustomerRepository, $Customer, $customerData['password_hash']);
            $maxCustomerId = max($maxCustomerId, Customer\getId($Customer));
        }
    }
    CustomerRepository\syncLastCustomerId($CustomerRepository, $maxCustomerId);
    // Исполнители
    $ExecutorRepository =& ServiceManager\get($ServiceManager, 'ExecutorRepository');
    $maxExecutorId = 1;
    foreach ($shardsConfig[ExecutorRepository\SHARD_CONFIG] as $shardId => $_) {
        $Mysql =& MysqlFactory\createShard($MysqlFactory, ExecutorRepository\SHARD_CONFIG, $shardId);
        $data = Mysql\query($Mysql, 'SELECT * FROM ' . ExecutorRepository\TABLE_NAME . '.' . ExecutorRepository\TABLE_NAME);
        while (($executorData = Mysql\fetchAssoc($Mysql, $data)) !== false) {
            $Executor =& Executor\unserializeFromMysql($executorData);
            ExecutorRepository\saveLoginToMemcached($ExecutorRepository, Executor\getLogin($Executor), Executor\getId($Executor));
            ExecutorRepository\savePasswordHashToMemcached($ExecutorRepository, $Executor, $executorData['password_hash']);
            $maxExecutorId = max($maxExecutorId, Executor\getId($Executor));
        }
    }
    ExecutorRepository\syncLastExecutorId($ExecutorRepository, $maxExecutorId);
    // Заказы
    $OrderRepository =& ServiceManager\get($ServiceManager, 'OrderRepository');
    foreach (OrderRepository\fetchAll($OrderRepository) as $Order) {
        OrderRepository\savePriceToMemcached($OrderRepository, Order\getPrice($Order));
    }
}
Example #6
0
/**
 * Запуск приложения
 *
 * @param array &$Application
 */
function run(array &$Application)
{
    $ServiceManager =& getServiceManager($Application);
    /**
     * У нас нет ни dispatch, ни forward, ни event, поэтому далее простой код
     */
    // Определим роутинг
    $Router =& Router\construct(ServiceManager\get($ServiceManager, 'Config'), ServiceManager\get($ServiceManager, 'Request'), $Application);
    Router\match($Router);
    $controllerName = Router\getControllerName($Router);
    $actionName = Router\getActionName($Router);
    $routeName = Router\getRouteName($Router);
    if (getMode($Application) === MODE_WEB) {
        if ($routeName === 'root') {
            header('Location: /index', true, 307);
            return;
        }
        $ActiveUser = null;
        $userData = Session\getActiveUserData();
        if (!is_null($userData)) {
            if ($userData[1] == 'customer') {
                // Заказчик
                if ($routeName !== 'customer' && ($routeName !== 'index' || $actionName !== 'logout')) {
                    header('Location: /customer', true, 307);
                    return;
                }
                $CustomerRepository =& CustomerRepository\construct(MemcachedFactory\create(ServiceManager\getFactory($ServiceManager, 'Memcached'), 'cache'), ServiceManager\getFactory($ServiceManager, 'Mysql'));
                $ActiveUser =& CustomerRepository\fetch($CustomerRepository, $userData[0]);
            } else {
                // Исполнитель
                if ($routeName !== 'executor' && ($routeName !== 'index' || $actionName !== 'logout')) {
                    header('Location: /executor', true, 307);
                    return;
                }
                $ExecutorRepository =& ServiceManager\get($ServiceManager, 'ExecutorRepository');
                $ActiveUser =& ExecutorRepository\fetch($ExecutorRepository, $userData[0]);
            }
            Session\regenerate();
        } else {
            if ($routeName !== 'index') {
                header('Location: /index', true, 307);
                return;
            }
        }
        ServiceManager\set($ServiceManager, 'ActiveUser', $ActiveUser);
    }
    // Создадим контроллер, вызовем action
    load('Avaritia\\Controller\\' . $controllerName);
    $controllerNamespace = 'Avaritia\\Controller\\' . $controllerName . '\\';
    // У контроллера должен быть конструктор
    if (!function_exists($controllerNamespace . 'construct')) {
        trigger_error('У контроллера [' . $controllerName . '] отсутствует конструктор', E_USER_ERROR);
    }
    $Controller =& call_user_func_array($controllerNamespace . 'construct', [&$ServiceManager]);
    $Request =& ServiceManager\get($ServiceManager, 'Request');
    // Полное имя функции экшена для вызова
    $actionFunction = $controllerNamespace . (Request\isXmlHttpRequest($Request) ? 'cmd' . ucfirst($actionName) : $actionName . 'Action');
    if (!function_exists($actionFunction)) {
        header('HTTP/1.0 404 Not Found');
        exit;
    }
    if (Request\isXmlHttpRequest($Request)) {
        // ajax запросы просто возвращают массив данных
        $View =& View\construct();
        View\setVariables($View, call_user_func_array($actionFunction, [&$Controller]));
        View\setRenderStrategy($View, View\RENDER_STRATEGY_JSON);
    } else {
        $View =& call_user_func_array($actionFunction, [&$Controller]);
    }
    ServiceManager\set($ServiceManager, 'View', $View);
    echo Response\toString(ServiceManager\get($ServiceManager, 'Response'));
}
Example #7
0
/**
 * Стартовая страница сервиса
 *
 * @param array &$Controller объект контроллера
 *
 * @return &array объект отображения
 */
function &indexAction(array &$Controller)
{
    $Request =& getRequest($Controller);
    $errorMsg = '';
    if (Request\isPost($Request)) {
        // Auth
        $login = Request\getPostParam($Request, 'login');
        $password = Request\getPostParam($Request, 'password');
        $loginAs = Request\getPostParam($Request, 'loginAs');
        if ($loginAs !== 'customer' && $loginAs !== 'executor' || is_null($login) || is_null($password)) {
            $errorMsg = 'Неверные данные';
        } else {
            $ServiceManager =& getServiceManager($Controller);
            if ($loginAs == 'customer') {
                // Заказчик
                $CustomerRepository =& ServiceManager\get($ServiceManager, 'CustomerRepository');
                if (!CustomerRepository\validateAuth($CustomerRepository, $login, $password)) {
                    $errorMsg = 'Неверный логин/пароль';
                } else {
                    ServiceManager\set($ServiceManager, 'ActiveUser', CustomerRepository\fetch($CustomerRepository, $login));
                    Session\setActiveUserData($login, 'customer');
                    header('Location: /customer', true, 307);
                    exit;
                }
            } else {
                // Исполнитель
                $ExecutorRepository =& ServiceManager\get($ServiceManager, 'ExecutorRepository');
                if (!ExecutorRepository\validateAuth($ExecutorRepository, $login, $password)) {
                    $errorMsg = 'Неверный логин/пароль';
                } else {
                    ServiceManager\set($ServiceManager, 'ActiveUser', ExecutorRepository\fetch($ExecutorRepository, $login));
                    Session\setActiveUserData($login, 'executor');
                    header('Location: /executor', true, 307);
                    exit;
                }
            }
        }
    } else {
        $loginAs = 'customer';
    }
    $View =& View\construct();
    View\setTemplateName($View, 'index\\index');
    View\setVariables($View, ['errorMsg' => $errorMsg, 'loginAs' => $loginAs]);
    return $View;
}
Example #8
0
/**
 * Запрос на добавление заказа
 *
 * @param array &$Controller объект котнроллера
 *
 * @return array
 */
function cmdAdd(array &$Controller)
{
    $Request =& getRequest($Controller);
    $price = (int) Request\getPostParam($Request, 'price');
    $text = Request\getPostParam($Request, 'text');
    $token = Request\getPostParam($Request, 'token');
    $isValid = validateParams($price, $text, $token);
    if ($isValid !== true) {
        return ['errorMsg' => $isValid];
    }
    $OrderRepository =& ServiceManager\get(getServiceManager($Controller), 'OrderRepository');
    if (OrderRepository\create($OrderRepository, $price, $text) === false) {
        return ['errorMsg' => 'Ошибка создания запроса'];
    } else {
        return [];
    }
}
Example #9
0
/**
 * Подгрузка новых заказов, если есть
 *
 * @param array &$Controller объект контроллера
 *
 * @return array сериализованный список заказов
 */
function cmdCheckNew(array &$Controller)
{
    $Request =& getRequest($Controller);
    $token = Request\getPostParam($Request, 'token');
    $fromId = (int) Request\getPostParam($Request, 'fromId');
    if ($fromId < 1 || is_null($token) || $token !== Session\getToken()) {
        return ['errorMsg' => 'Неверные данные'];
    }
    $OrderRepository =& ServiceManager\get(getServiceManager($Controller), 'OrderRepository');
    return array_map(function (array $Order) {
        return ['id' => Order\getId($Order), 'text' => htmlspecialchars(Order\getText($Order), ENT_COMPAT | ENT_QUOTES), 'price' => Order\getPrice($Order)];
    }, OrderRepository\fetchWithIdOffset($OrderRepository, $fromId));
}