<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Session\SaveHandler\Database;

use Traversable;
use Xloit\Bridge\Zend\Session\Exception;
use Zend\Stdlib\AbstractOptions;

/**
 * A {@link DatabaseOptions} class.
 *
 * @package Xloit\Bridge\Zend\Session\SaveHandler\Database
 */
class DatabaseOptions extends AbstractOptions
{
    /**
     * Class name.
     *
     * @var string
     */
    protected $className;

    /**
     * ID Column.
     *
     * @var string
     */
    protected $idColumn = 'id';

    /**
     * Name Column.
     *
     * @var string
     */
    protected $nameColumn = 'name';

    /**
     * Data Column.
     *
     * @var string
     */
    protected $dataColumn = 'data';

    /**
     * Lifetime Column.
     *
     * @var string
     */
    protected $lifetimeColumn = 'lifetime';

    /**
     * Modified Column.
     *
     * @var string
     */
    protected $modifiedColumn = 'modified';

    /**
     * Created Column.
     *
     * @var string
     */
    protected $createdColumn = 'created';

    /**
     * Constructor to prevent {@link DatabaseOptions} from being loaded more than once.
     *
     * @param array|Traversable|null $options
     *
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function __construct($options)
    {
        parent::__construct($options);

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($this->className)) {
            throw new Exception\InvalidArgumentException('Class Name must be a non-empty string.');
        }
    }

    /**
     * Returns the ClassName value.
     *
     * @return string
     */
    public function getClassName()
    {
        return $this->className;
    }

    /**
     * Sets the ClassName value.
     *
     * @param string $className
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setClassName($className)
    {
        $className = (string) $className;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($className)) {
            throw new Exception\InvalidArgumentException('Class Name must be a non-empty string.');
        }

        $this->className = $className;

        return $this;
    }

    /**
     * Returns the IdColumn value.
     *
     * @return string
     */
    public function getIdColumn()
    {
        return $this->idColumn;
    }

    /**
     * Sets the IdColumn value.
     *
     * @param string $idColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setIdColumn($idColumn)
    {
        $idColumn = (string) $idColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($idColumn)) {
            throw new Exception\InvalidArgumentException('ID column must be a non-empty string.');
        }

        $this->idColumn = $idColumn;

        return $this;
    }

    /**
     * Returns the NameColumn value.
     *
     * @return string
     */
    public function getNameColumn()
    {
        return $this->nameColumn;
    }

    /**
     * Sets the NameColumn value.
     *
     * @param string $nameColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setNameColumn($nameColumn)
    {
        $nameColumn = (string) $nameColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($nameColumn)) {
            throw new Exception\InvalidArgumentException('Name column must be a non-empty string.');
        }

        $this->nameColumn = $nameColumn;

        return $this;
    }

    /**
     * Returns the DataColumn value.
     *
     * @return string
     */
    public function getDataColumn()
    {
        return $this->dataColumn;
    }

    /**
     * Sets the DataColumn value.
     *
     * @param string $dataColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setDataColumn($dataColumn)
    {
        $dataColumn = (string) $dataColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($dataColumn)) {
            throw new Exception\InvalidArgumentException('Data column must be a non-empty string.');
        }

        $this->dataColumn = $dataColumn;

        return $this;
    }

    /**
     * Returns the LifetimeColumn value.
     *
     * @return string
     */
    public function getLifetimeColumn()
    {
        return $this->lifetimeColumn;
    }

    /**
     * Sets the LifetimeColumn value.
     *
     * @param string $lifetimeColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setLifetimeColumn($lifetimeColumn)
    {
        $lifetimeColumn = (string) $lifetimeColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($lifetimeColumn)) {
            throw new Exception\InvalidArgumentException('Lifetime column must be a non-empty string.');
        }

        $this->lifetimeColumn = $lifetimeColumn;

        return $this;
    }

    /**
     * Returns the ModifiedColumn value.
     *
     * @return string
     */
    public function getModifiedColumn()
    {
        return $this->modifiedColumn;
    }

    /**
     * Sets the ModifiedColumn value.
     *
     * @param string $modifiedColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setModifiedColumn($modifiedColumn)
    {
        $modifiedColumn = (string) $modifiedColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($modifiedColumn)) {
            throw new Exception\InvalidArgumentException('Modified column must be a non-empty string.');
        }

        $this->modifiedColumn = $modifiedColumn;

        return $this;
    }

    /**
     * Returns the CreatedColumn value.
     *
     * @return string
     */
    public function getCreatedColumn()
    {
        return $this->createdColumn;
    }

    /**
     * Sets the CreatedColumn value.
     *
     * @param string $createdColumn
     *
     * @return $this
     * @throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException
     */
    public function setCreatedColumn($createdColumn)
    {
        $createdColumn = (string) $createdColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($createdColumn)) {
            throw new Exception\InvalidArgumentException('Created column must be a non-empty string.');
        }

        $this->createdColumn = $createdColumn;

        return $this;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Marco Bunge
 * Date: 04.11.2015
 * Time: 14:35
 */

namespace Blast\Application\Kernel;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class Foundation extends AbstractKernel implements KernelInterface
{

    /**
     * Dispatch the application
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return mixed
     */
    public function dispatch(ServerRequestInterface $request, ResponseInterface $response)
    {
        return $this->getStrategy()->dispatch($this, $request, $response);
    }

}


<?php

namespace Think\Model;

use Think\Model;

/**
 * 视图模型
 */
abstract class ViewModel extends Model
{

    protected $viewFields = [];

    /**
     * 自动检测数据表信息

     * @return void
     */
    protected function _checkTableInfo()
    {
    }

    /**
     * 得到完整的数据表名

     * @return string
     */
    public function getTableName()
    {
        if (empty($this->trueTableName)) {
            $tableName = '';
            foreach ($this->viewFields as $key => $view) {
                // 获取数据表名称
                // 添加实际表名定义支持 可以实现同一个表的视图
                if (isset($view['_table'])) {
                    $tableName .= $view['_table'];
                    $prefix = $this->tablePrefix;
                    $tableName = preg_replace_callback(
                        "/__([A-Z_-]+)__/sU",
                        function ($match) use ($prefix) {
                            return $prefix.strtolower($match[1]);
                        },
                        $tableName
                    );
                } else {
                    $class = $key.'Model';
                    $Model = class_exists($class) ? new $class() : D($key);
                    $tableName .= $Model->getTableName();
                }
                // 表别名定义
                $tableName .= !empty($view['_as']) ? ' '.$view['_as'] : ' '.$key;
                // 支持ON 条件定义
                $tableName .= !empty($view['_on']) ? ' ON '.$view['_on'] : '';
                // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效
                $type = !empty($view['_type']) ? $view['_type'] : '';
                $tableName .= ' '.strtoupper($type).' JOIN ';
                $len = strlen($type.'_JOIN ');
            }
            $tableName = substr($tableName, 0, -$len);
            $this->trueTableName = $tableName;
        }

        return $this->trueTableName;
    }

    /**
     * 表达式过滤方法

     *
     * @param array $options 表达式
     *
     * @return void
     */
    protected function _options_filter(&$options)
    {
        if (isset($options['field'])) {
            $options['field'] = $this->checkFields($options['field']);
        } else {
            $options['field'] = $this->checkFields();
        }
        if (isset($options['group'])) {
            $options['group'] = $this->checkGroup($options['group']);
        }
        if (isset($options['where'])) {
            $options['where'] = $this->checkCondition($options['where']);
        }
        if (isset($options['order'])) {
            $options['order'] = $this->checkOrder($options['order']);
        }
    }

    /**
     * 检查是否定义了所有字段

     *
     * @param string $name 模型名称
     * @param array $fields 字段数组
     *
     * @return array
     */
    private function _checkFields($name, $fields)
    {
        // 定义所有字段
        if (false !== $pos = array_search('*', $fields)) {
            $fields = array_merge($fields, D($name)->getDbFields());
            unset($fields[$pos]);
        }

        return $fields;
    }

    /**
     * 检查条件中的视图字段

     *
     * @param array $where 条件表达式
     *
     * @return array
     */
    protected function checkCondition(array $where = [])
    {
        if (is_array($where)) {
            $view = [];
            // 检查视图字段
            foreach ($this->viewFields as $key => $val) {
                $k = isset($val['_as']) ? $val['_as'] : $key;
                $val = $this->_checkFields($key, $val);
                foreach ($where as $name => $value) {
                    if (false !== $field = array_search($name, $val, true)) {
                        // 存在视图字段
                        $_key = is_numeric($field) ? $k.'.'.$name : $k.'.'.$field;
                        $view[$_key] = $value;
                        unset($where[$name]);
                    }
                }
            }
            $where = array_merge($where, $view);
        }

        return $where;
    }

    /**
     * 检查Order表达式中的视图字段

     *
     * @param string $order 字段
     *
     * @return string
     */
    protected function checkOrder($order = '')
    {
        if (is_string($order) && !empty($order)) {
            $orders = explode(',', $order);
            $_order = [];
            foreach ($orders as $order) {
                $array = explode(' ', trim($order));
                $field = $array[0];
                $sort = isset($array[1]) ? $array[1] : 'ASC';
                // 解析成视图字段
                foreach ($this->viewFields as $name => $val) {
                    $k = isset($val['_as']) ? $val['_as'] : $name;
                    $val = $this->_checkFields($name, $val);
                    if (false !== $_field = array_search($field, $val, true)) {
                        // 存在视图字段
                        $field = is_numeric($_field) ? $k.'.'.$field : $k.'.'.$_field;
                        break;
                    }
                }
                $_order[] = $field.' '.$sort;
            }
            $order = implode(',', $_order);
        }

        return $order;
    }

    /**
     * 检查Group表达式中的视图字段

     *
     * @param string $group 字段
     *
     * @return string
     */
    protected function checkGroup($group = '')
    {
        if (!empty($group)) {
            $groups = explode(',', $group);
            $_group = [];
            foreach ($groups as $field) {
                // 解析成视图字段
                foreach ($this->viewFields as $name => $val) {
                    $k = isset($val['_as']) ? $val['_as'] : $name;
                    $val = $this->_checkFields($name, $val);
                    if (false !== $_field = array_search($field, $val, true)) {
                        // 存在视图字段
                        $field = is_numeric($_field) ? $k.'.'.$field : $k.'.'.$_field;
                        break;
                    }
                }
                $_group[] = $field;
            }
            $group = implode(',', $_group);
        }

        return $group;
    }

    /**
     * 检查fields表达式中的视图字段

     *
     * @param string $fields 字段
     *
     * @return string
     */
    protected function checkFields($fields = '')
    {
        if (empty($fields) || '*' == $fields) {
            // 获取全部视图字段
            $fields = [];
            foreach ($this->viewFields as $name => $val) {
                $k = isset($val['_as']) ? $val['_as'] : $name;
                $val = $this->_checkFields($name, $val);
                foreach ($val as $key => $field) {
                    if (is_numeric($key)) {
                        $fields[] = $k.'.'.$field.' AS '.$field;
                    } elseif ('_' != substr($key, 0, 1)) {
                        // 以_开头的为特殊定义
                        if (false !== strpos($key, '*') || false !== strpos($key, '(') || false !== strpos(
                                $key,
                                '.'
                            )
                        ) {
                            //如果包含* 或者 使用了sql方法 则不再添加前面的表名
                            $fields[] = $key.' AS '.$field;
                        } else {
                            $fields[] = $k.'.'.$key.' AS '.$field;
                        }
                    }
                }
            }
            $fields = implode(',', $fields);
        } else {
            if (!is_array($fields)) {
                $fields = explode(',', $fields);
            }
            // 解析成视图字段
            $array = [];
            foreach ($fields as $key => $field) {
                if (strpos($field, '(') || strpos(strtolower($field), ' as ')) {
                    // 使用了函数或者别名
                    $array[] = $field;
                    unset($fields[$key]);
                }
            }
            foreach ($this->viewFields as $name => $val) {
                $k = isset($val['_as']) ? $val['_as'] : $name;
                $val = $this->_checkFields($name, $val);
                foreach ($fields as $key => $field) {
                    if (false !== $_field = array_search($field, $val, true)) {
                        // 存在视图字段
                        if (is_numeric($_field)) {
                            $array[] = $k.'.'.$field.' AS '.$field;
                        } elseif ('_' != substr($_field, 0, 1)) {
                            //如果包含* 或者 使用了sql方法 则不再添加前面的表名
                            if (false !== strpos($_field, '*') || false !== strpos(
                                    $_field,
                                    '('
                                ) || false !== strpos($_field, '.')
                            ) {
                                $array[] = $_field.' AS '.$field;
                            } else {
                                $array[] = $k.'.'.$_field.' AS '.$field;
                            }
                        }
                    }
                }
            }
            $fields = implode(',', $array);
        }

        return $fields;
    }
}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Caster
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\CollectionHelper\Caster;

use CSDT\CollectionsBundle\CollectionHelper\HelperInterface\ArrayCasterInterface;
use CSDT\CollectionsBundle\CollectionInterfaces\MapCollectionInterface;

/**
 * Map collection caster
 *
 * This class is used to cast array to MapCollection type.
 *
 * @category Caster
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
class MapCollectionCaster implements ArrayCasterInterface
{

    /**
     * To collection
     *
     * This method cast an array into
     * a specific collection.
     *
     * @param array  $array The array to cast
     * @param string $class The class to render
     *
     * @throws LogicException if the given class is not supported
     * @return CollectionInterface
     */
    public function toCollection(array $array, $class)
    {
        $reflection = new \ReflectionClass($class);
        $collection = $reflection->newInstanceWithoutConstructor();

        if ($collection instanceof MapCollectionInterface) {
            $collection->setAll($array);
            return $collection;
        }

        throw new \LogicException(
            sprintf("The MapCollectionCaster does not support type %s", $class)
        );
    }

    /**
     * Support
     *
     * Return true if the array caster
     * support the given collection class.
     *
     * @param string $class The collection class name
     *
     * @return boolean
     */
    public function support($class)
    {
        return in_array(
            MapCollectionInterface::class,
            class_implements($class)
        );
    }
}


<?php

namespace QCharts\FrontendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use QCharts\CoreBundle\Exception\NoTableNamesException;

class MainController extends Controller
{
    /**
     * @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function mainAction()
    {
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        $urls = $this->getParameter("qcharts.urls");
        $allow_demo_users = $this->getParameter("qcharts.allow_demo_users");

        if ($authChecker->isGranted($roles["user"]) || $allow_demo_users)
        {
            try
            {
                return $this->render('@Frontend/blocks/main/main.html.twig', array(
                    'isAdmin' => $authChecker->isGranted($roles["admin"]),
                    'user_roles' => $roles,
                    'redirectUrls' => $urls
                ));
            }
            catch (NoTableNamesException $e)
            {
                return $this->render('@Frontend/blocks/main/main.html.twig', array(
                    'queries' => [],
                    'user_roles' => $roles,
                    'redirectUrls' => $urls
                ));
            }

        }

        return new RedirectResponse('/login');
    }

    /**
     * @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function successAction()
    {
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        $urls = $this->getParameter("qcharts.urls");

        if (!$authChecker->isGranted($roles["admin"]))
        {
            return new RedirectResponse($urls["redirects"]["login"]);
        }

        return $this->render('@Frontend/blocks/registerQuery/confirmed.html.twig', [
            'redirectUrls' => $urls,
            "user_roles" => $roles
        ]);

    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function aboutAction()
    {
        $urls = $this->getParameter("qcharts.urls");
        return $this->render('@Frontend/blocks/about/about.html.twig', [
            "user_roles" => $this->getParameter("qcharts.user_roles"),
            'redirectUrls' => $urls
        ]);
    }

    // TODO: continue this here!
    public function databaseSelection(Request $request)
    {
        $authChecker = $this->get("security.authorization_checker");
        $roles = $this->getParameter("qcharts.user_roles");
        $urls = $this->getParameter("qcharts.urls");
        if (!$authChecker->isGranted($roles["user"]))
        {
            return new RedirectResponse($this->generateUrl($urls["redirects"]["logout"]));
        }

        //return the page to load!
    }

}


<?php
/**
 * Драйвер на основе стандарта SQL
 *
 * @version ${product.version}
 *
 * @copyright 2013, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Драйвер на основе стандарта SQL
 *
 * @package ORM
 * @since 3.00
 */
class ORM_Driver_SQL
{
    /**
     * Менеджер ORM
     *
     * @var ORM_Manager
     */
    private $manager;

    /**
     * Конструктор драйвера
     *
     * @param ORM_Manager $manager
     */
    public function __construct(ORM_Manager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * Возвращает используемый менеджер ORM
     *
     * @return ORM_Manager
     */
    public function getManager()
    {
        return $this->manager;
    }

    /**
     * Создаёт таблицу
     *
     * @param ORM_Table $table
     *
     * @return void
     *
     * @throws Eresus_DB_Exception_QueryFailed
     *
     * @since 3.00
     */
    public function createTable(ORM_Table $table)
    {
        if ($table->isAlias())
        {
            return;
        }
        $db = Eresus_DB::getHandler();
        $tableName = $db->options->tableNamePrefix . $table->getName();

        $fieldDefinitions = array();
        foreach ($table->getColumns() as $field)
        {
            if (!$field->isVirtual())
            {
                $fieldDefinitions []= $this->getFieldDefinition($field);
            }
        }
        $primaryKey = $this->getPrimaryKeyDefinition($table->getPrimaryKey());
        $indexDefinitions = array();
        foreach ($table->getIndexes() as $name => $params)
        {
            $indexDefinitions []= $this->getIndexDefinition($name, $params);
        }
        $sql = $this->getCreateTableDefinition($tableName, $fieldDefinitions, $primaryKey,
            $indexDefinitions);
        try
        {
            $db->exec($sql);
        }
        catch (PDOException $e)
        {
            throw Eresus_DB_Exception_QueryFailed::create($sql, $e);
        }

        $columns = $table->getColumns();
        foreach ($columns as $name => $column)
        {
            $column->afterTableCreate($table, $name);
        }
    }

    /**
     * Удаляет таблицу
     *
     * @param ORM_Table $table
     *
     * @return void
     *
     * @throws Eresus_DB_Exception_QueryFailed
     *
     * @since 3.00
     */
    public function dropTable(ORM_Table $table)
    {
        if ($table->isAlias())
        {
            return;
        }
        $db = Eresus_DB::getHandler();
        $tableName = $db->options->tableNamePrefix . $table->getName();

        $sql = $this->getDropTableDefinition($tableName);
        try
        {
            $db->exec($sql);
        }
        catch (PDOException $e)
        {
            throw Eresus_DB_Exception_QueryFailed::create($sql, $e);
        }

        $columns = $table->getColumns();
        foreach ($columns as $name => $column)
        {
            $column->afterTableDrop($table, $name);
        }
    }

    /**
     * Возвращает выражение SQL для создания таблицы
     *
     * @param string   $name        имя таблицы
     * @param string[] $fields      выражения для полей
     * @param string   $primaryKey  выражение для главного ключа
     * @param string[] $indexes     выражения для индексов
     *
     * @return string  SQL
     */
    protected function getCreateTableDefinition($name, $fields, $primaryKey, $indexes)
    {
        return "CREATE TABLE $name ("
            . implode(', ', array_merge($fields, array($primaryKey), $indexes))
            . ')';
    }

    /**
     * Возвращает выражение SQL для удаления таблицы
     *
     * @param string   $name        имя таблицы
     *
     * @return string  SQL
     */
    protected function getDropTableDefinition($name)
    {
        return "DROP TABLE $name";
    }

    /**
     * Возвращает выражение SQL для описания поля таблицы
     *
     * @param ORM_Field_Abstract $field  поле
     *
     * @return string  SQL
     */
    protected function getFieldDefinition(ORM_Field_Abstract $field)
    {
        $sql = $this->getDriverFieldType($field)->getSqlFieldDefinition();
        if ($field->hasParam('default'))
        {
            $sql .= ' DEFAULT ';
            if ($field->getParam('default') === null)
            {
                $sql .= 'NULL';
            }
            elseif ($field->getPdoType() == PDO::PARAM_STR)
            {
                $sql .= "'" . $field->getParam('default') . "'";
            }
            elseif ($field->getPdoType() == PDO::PARAM_BOOL)
            {
                $sql .= $field->getParam('default') ? '1' : '0';
            }
            else
            {
                $sql .= $field->getParam('default');
            }
        }
        return $sql;
    }

    /**
     * Возвращает выражение SQL для главного ключа
     *
     * @param string $key
     *
     * @return string
     */
    protected function getPrimaryKeyDefinition($key)
    {
        if (is_array($key))
        {
            $key = implode(', ', $key);
        }
        return 'PRIMARY KEY (' . $key . ')';
    }

    /**
     * Возвращает объявление индекса
     *
     * @param string $name
     * @param array  $params
     *
     * @return string  SQL
     */
    protected function getIndexDefinition($name, array $params)
    {
        $sql = 'KEY ' . $name . ' (' . implode(', ', $params['fields']) . ')';
        if (array_key_exists('type', $params))
        {
            $sql = strtoupper(@$params['type']) . ' ' . $sql;
        }
        return $sql;
    }

    /**
     * Возвращает объявление типа поля
     *
     * @param ORM_Field_Abstract $field
     *
     * @return ORM_Field_Abstract|ORM_Driver_SQL_Field
     */
    private function getDriverFieldType(ORM_Field_Abstract $field)
    {
        $fieldType = get_class($field);
        $driver = substr(get_class($this), strrpos(get_class($this), '_') + 1);
        $driverFieldType = str_replace('_Field_', '_Driver_' . $driver . '_', $fieldType);
        if (class_exists($driverFieldType))
        {
            $driverField = new $driverFieldType($field);
            if ($driverField instanceof ORM_Driver_SQL_Field)
            {
                return $driverField;
            }
        }
        return $field;
    }
}


<?php
namespace Li;

class Mysql
{
    public $_link;
    public $charset='utf8';
    public $_statement;
    private $_sql;

    public function beginTransaction()
    {
        return $this->_link->beginTransaction();
    }

    public function commit()
    {
        return $this->_link->commit();
    }

    public function rollBack()
    {
        return $this->_link->rollBack();
    }

    public function __construct($config)
    {
        if(!empty($config))
        {
            $this->host = $config['host'];
            $this->port = $config['port'];
            $this->dbname = $config['name'];
            $this->user = $config['user'];
            $this->password = $config['pass'];
            if(isset($config['charset']))
                $this->charset = $config['charset'];

            $this->connect();
        }
    }

    public function connect()
    {
        $dns = 'mysql:dbname=' . $this->dbname . ";host=" . $this->host . ";port=" . $this->port;
        try {
            $this->_link = new \PDO($dns, $this->user, $this->password);
            $this->exec('SET NAMES '.$this->_link->quote($this->charset));
        }
        catch(Exception $e)
        {
            die('database connect error');
        }
    }

    public function error()
    {

    }

    /**
     * 获得该引擎对应的CommandBuilder
     */
    public function getCommandBuilder()
    {
        return new MysqlCommandBuilder($this);
    }

    /**
     * 创建command
     */
    public function createCommand($query)
    {
        return new Command($this, $query);
    }

    public function getPdoInstance()
    {
        return $this->_link;
    }

    /**
     * 为sql语句过滤变量值
     */

    public function quoteValue($str)
    {
        if(is_int($str) || is_float($str))
            return $str;

        if(($value=$this->_link->quote($str))!==false)
            return $value;
        else  // the driver doesn't support quote (e.g. oci)
            return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
    }

    /**
     * Determines the PDO type for the specified PHP type.
     * @param string $type The PHP type (obtained by gettype() call).
     * @return integer the corresponding PDO type
     */
    public function getPdoType($type)
    {
        static $map=array
        (
            'boolean'=>\PDO::PARAM_BOOL,
            'integer'=>\PDO::PARAM_INT,
            'string'=>\PDO::PARAM_STR,
            'resource'=>\PDO::PARAM_LOB,
            'NULL'=>\PDO::PARAM_NULL,
        );
        return isset($map[$type]) ? $map[$type] : \PDO::PARAM_STR;
    }

    public function getLastInsertID($sequenceName='')
    {
        return $this->_link->lastInsertId($sequenceName);
    }

    public function prepare($sql)
    {
        $this->_sql = $sql;
        $this->_statement=$this->_link->prepare($sql);
    }

    public function bindValues($values)
    {
        if(is_array($values) && !empty($values))
        {
            $i=0;
            foreach($values as $v)
            {
                // $this->_statement->bindValue(':v'.$i, $v[1], $this->getPdoType($v[1]));
                $this->_statement->bindValue($v[0], $v[1], $this->getPdoType($v[1]));
                $i++;
            }
        }
    }

    public function fetchAll($fetchStyle=\PDO::FETCH_ASSOC)
    {
        if(!$this->_statement->execute())
        {
            $error = $this->_statement->errorInfo();
            throw new  Exception('SQLSTATE['.$error[0] . ']: ' . $error[2]);
        }

        return $this->_statement->fetchAll($fetchStyle);
    }

    public function fetch($fetchStyle=\PDO::FETCH_ASSOC)
    {
        if(!$this->_statement->execute())
        {
            $error = $this->_statement->errorInfo();
            throw new  Exception('SQLSTATE['.$error[0] . ']: ' . $error[2]);
        }

        return $this->_statement->fetch($fetchStyle);
    }

    public function execute()
    {
        if(!$this->_statement->execute())
        {
            $error = $this->_statement->errorInfo();
            throw new  Exception('SQLSTATE['.$error[0] . ']: ' . $error[2]);
        }

        $count = $this->_statement->rowCount();
        return $count;
    }

    /**
     * 构建查询的sql
     */
    public function buildQuery($query)
    {
        $sql=!empty($query['distinct']) ? 'SELECT DISTINCT' : 'SELECT';
        $sql.=' '.(!empty($query['select']) ? $query['select'] : '*');

        if(!empty($query['from']))
            $sql.="\nFROM ".$query['from'];
        else
            throw new CDbException(Yii::t('yii','The DB query must contain the "from" portion.'));

        if(!empty($query['join']))
            $sql.="\n".(is_array($query['join']) ? implode("\n",$query['join']) : $query['join']);

        if(!empty($query['where']))
            $sql.="\nWHERE ".$query['where'];

        if(!empty($query['group']))
            $sql.="\nGROUP BY ".$query['group'];

        if(!empty($query['having']))
            $sql.="\nHAVING ".$query['having'];

        if(!empty($query['union']))
            $sql.="\nUNION (\n".(is_array($query['union']) ? implode("\n) UNION (\n",$query['union']) : $query['union']) . ')';

        if(!empty($query['order']))
            $sql.="\nORDER BY ".$query['order'];

        $limit=isset($query['limit']) ? (int)$query['limit'] : -1;
        $offset=isset($query['offset']) ? (int)$query['offset'] : -1;
        if($limit>=0 || $offset>0)
            $sql=$this->_connection->getCommandBuilder()->applyLimit($sql,$limit,$offset);

        return $sql;
    }

    public function exec($sql)
    {
        return $this->_link->exec($sql);
    }
    public function query($sql)
    {
        $rs = $this->_link->query($sql);
        if($rs == false)
        {
            $error = $this->_link->errorInfo();
            throw new  Exception('SQLSTATE['.$error[0] . ']: ' . $error[2]);
        }

        return $rs->fetchAll();
    }

}


<?php

namespace Laralum\Social\Models;

use Illuminate\Database\Eloquent\Model;
use Laralum\Users\Models\User;

class Social extends Model
{
    public $table = 'laralum_social';
    public $fillable = [
        'user_id', 'provider', 'token', 'secret_token', 'email',
    ];

    /**
     * Return the user from the social account.
     *
     * @return \Laralum\Users\Moodels\User;
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Return all the providers supported.
     *
     * @return array
     */
    public static function providers()
    {
        return collect(Settings::first()->fillable)->filter(function ($value) {
            return strpos($value, '_client_id') !== false;
        })->map(function ($value) {
            return str_replace('_client_id', '', $value);
        })->toArray();
    }

    /**
     * Returns all the available providers.
     *
     * @return array
     */
    public static function availableProviders()
    {
        $settings = Settings::first();

        return collect(static::providers())->filter(function ($value) use ($settings) {
            $ci = $value.'_client_id';
            $cs = $value.'_client_secret';

            return $settings->$ci && $settings->$cs;
        })->toArray();
    }
}


<?php

namespace JDesrosiers\Silex\Provider;

use JDesrosiers\Silex\Provider\ContentNegotiation\JmsSerializerContentNegotiation;
use JDesrosiers\Silex\Provider\ContentNegotiation\SymfonySerializerContentNegotiation;
use JMS\Serializer as JMS;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Silex\Application;
use Silex\Api\BootableProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
use Symfony\Component\Serializer as SymfonySerializer;

/**
 * This ServiceProvider provides HTTP Content Negotiation support to a silex
 * application.
 */
class ContentNegotiationServiceProvider implements ServiceProviderInterface, BootableProviderInterface
{
    /**
     * Add filters to check that the request and repsonse formats are supported
     * by the application.
     *
     * @param Application $app
     */
    public function boot(Application $app)
    {
        $app->before(array($this, "setRequestFormat"), Application::EARLY_EVENT);
        $app->before(array($this, "validateRequestContentType"), Application::EARLY_EVENT);
    }

    /**
     * Set defaults and build the conneg service.
     *
     * @param Container $app
     * @throws ServiceUnavailableHttpException
     */
    public function register(Container $app)
    {
        $app["conneg.responseFormats"] = array("html");
        $app["conneg.requestFormats"] = array("form");
        $app["conneg.defaultFormat"] = "html";

        $app["conneg"] = function (Container $app) {
            if ($app->offsetExists("serializer")) {
                if ($app["serializer"] instanceof JMS\Serializer) {
                    if (!$app->offsetExists("conneg.serializationContext")) {
                        $app["conneg.serializationContext"] = null;
                    }
                    if (!$app->offsetExists("conneg.deserializationContext")) {
                        $app["conneg.deserializationContext"] = null;
                    }

                    return new JmsSerializerContentNegotiation($app);
                } elseif ($app["serializer"] instanceof SymfonySerializer\Serializer) {
                    if (!$app->offsetExists("conneg.serializationContext")) {
                        $app["conneg.serializationContext"] = array();
                    }
                    if (!$app->offsetExists("conneg.deserializationContext")) {
                        $app["conneg.deserializationContext"] = array();
                    }

                    return new SymfonySerializerContentNegotiation($app);
                }
            }

            throw new ServiceUnavailableHttpException(null, "No supported serializer found");
        };
    }

    /**
     * This before middleware validates whether the application will be able to
     * respond in a format that the client understands.
     *
     * @param Request $request
     * @throws NotAcceptableHttpException
     */
    public function setRequestFormat(Request $request, Application $app)
    {
        // If there is no Accept header, do nothing
        if (!$request->headers->get("Accept")) {
            return;
        }

        // Check the Accept header for acceptable formats
        foreach ($request->getAcceptableContentTypes() as $contentType) {
            // If any format is acceptable, do nothing
            if ($contentType === "*/*") {
                return;
            }

            $format = $request->getFormat($contentType);
            if (in_array($format, $app["conneg.responseFormats"])) {
                // An acceptable format was found.  Set it as the requestFormat
                // where it can be referenced later.
                $request->setRequestFormat($format);
                return;
            }
        }

        // No acceptable formats were found
        throw new NotAcceptableHttpException();
    }

    /**
     * This before middleware validates that the request body is in a format
     * that the application understands.
     *
     * @param Request $request
     * @throws UnsupportedMediaTypeHttpException
     */
    public function validateRequestContentType(Request $request, Application $app)
    {
        // Define the "form" format so we can use it for validation
        $request->setFormat("form", array("application/x-www-form-urlencoded", "multipart/form-data"));

        $format = $request->getContentType();
        if (strlen($request->getContent()) > 0 && !in_array($format, $app["conneg.requestFormats"])) {
            // The request has a body but it is not a supported media type
            throw new UnsupportedMediaTypeHttpException();
        }
    }
}


<?php

namespace Think\Cache\Driver;

use Think\Cache;

/**
 * 文件类型缓存类
 */
class File extends Cache
{

    /**
     *
     * @param array $options
     */
    public function __construct(array $options = [])
    {
        if (!empty($options)) {
            $this->options = $options;
        }
        $this->options['temp'] = !empty($options['temp']) ? $options['temp'] : C('DATA_CACHE_PATH');
        $this->options['prefix'] = isset($options['prefix']) ? $options['prefix'] : C('DATA_CACHE_PREFIX');
        $this->options['expire'] = isset($options['expire']) ? $options['expire'] : C('DATA_CACHE_TIME');
        $this->options['length'] = isset($options['length']) ? $options['length'] : 0;
        if (substr($this->options['temp'], -1) != '/') {
            $this->options['temp'] .= '/';
        }
        $this->init();
    }

    /**
     * 初始化检查
     * @return void
     */
    private function init()
    {
        // 创建应用缓存目录
        if (!is_dir($this->options['temp'])) {
            mkdir($this->options['temp']);
        }
    }

    /**
     * 取得变量的存储文件名
     *
     * @param string $name 缓存变量名
     *
     * @return string
     */
    private function filename($name)
    {
        $name = md5(C('DATA_CACHE_KEY').$name);
        if (C('DATA_CACHE_SUBDIR')) {
            // 使用子目录
            $dir = '';
            for ($i = 0; $i < C('DATA_PATH_LEVEL'); $i++) {
                $dir .= $name{$i}.'/';
            }
            if (!is_dir($this->options['temp'].$dir)) {
                mkdir($this->options['temp'].$dir, 0755, true);
            }
            $filename = $dir.$this->options['prefix'].$name.'.php';
        } else {
            $filename = $this->options['prefix'].$name.'.php';
        }

        return $this->options['temp'].$filename;
    }

    /**
     * 读取缓存
     *
     * @param string $name 缓存变量名
     *
     * @return mixed
     */
    public function get($name)
    {
        $filename = $this->filename($name);
        if (!is_file($filename)) {
            return false;
        }
//            N('cache_read', 1);
        $content = file_get_contents($filename);
        if (false !== $content) {
            $expire = (int)substr($content, 8, 12);
            if ($expire != 0 && time() > filemtime($filename) + $expire) {
                //缓存过期删除缓存文件
                @unlink($filename);

                return false;
            }
            //开启数据校验
            if (C('DATA_CACHE_CHECK')) {
                $check = substr($content, 20, 32);
                $content = substr($content, 52, -3);
                //校验错误
                if ($check != md5($content)) {
                    return false;
                }
            } else {
                $content = substr($content, 20, -3);
            }
            if (C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
                //启用数据压缩
                $content = gzuncompress($content);
            }

            return unserialize($content);
        } else {
            return false;
        }
    }

    /**
     * 写入缓存
     *
     * @param string $name 缓存变量名
     * @param mixed $value 存储数据
     * @param int $expire 有效时间 0为永久
     *
     * @return bool
     */
    public function set($name, $value, $expire = null)
    {
//            N('cache_write', 1);
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        $filename = $this->filename($name);
        $data = serialize($value);
        if (C('DATA_CACHE_COMPRESS') && function_exists('gzcompress')) {
            //数据压缩
            $data = gzcompress($data, 3);
        }
        //开启数据校验
        if (C('DATA_CACHE_CHECK')) {
            $check = md5($data);
        } else {
            $check = '';
        }
        $data = "<?php\n//".sprintf('%012d', $expire).$check.$data."\n?>";
        $result = file_put_contents($filename, $data);
        if ($result) {
            if ($this->options['length'] > 0) {
                // 记录缓存队列
                $this->queue($name);
            }
            clearstatcache();

            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param string $name 缓存变量名
     *
     * @return bool
     */
    public function rm($name)
    {
        return @unlink($this->filename($name));
    }

    /**
     * 清除缓存
     * @return bool
     */
    public function clear()
    {
        $path = $this->options['temp'];
        $files = scandir($path);
        if ($files) {
            foreach ($files as $file) {
                if ($file != '.' && $file != '..' && is_dir($path.$file)) {
                    array_map('unlink', glob($path.$file.'/*.*'));
                } elseif (is_file($path.$file)) {
                    @unlink($path.$file);
                }
            }

            return true;
        }

        return false;
    }
}


<?php

namespace Kcs\FunctionMock\Promise;

use Kcs\FunctionMock\FunctionProphecy;

/**
 * Return promise.
 */
class ReturnPromise implements PromiseInterface
{
    private $returnValues = [];

    /**
     * Initializes promise.
     *
     * @param array $returnValues Array of values
     */
    public function __construct(array $returnValues)
    {
        $this->returnValues = $returnValues;
    }

    /**
     * Returns saved values one by one until last one, then continuously returns last value.
     *
     * @param array          $args
     * @param FunctionProphecy $function
     *
     * @return mixed
     */
    public function execute(array $args, FunctionProphecy $function)
    {
        $value = array_shift($this->returnValues);

        if (!count($this->returnValues)) {
            $this->returnValues[] = $value;
        }

        return $value;
    }
}