<?php

/*
 * This file is part of Core.
 *
 * (c) DraperStudio <hello@draperstudio.tech>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apivore\Core;

use Apivore\Core\Contracts\HttpClient;

/**
 * Class AbstractApi.
 */
abstract class AbstractApi
{
    /**
     * @var HttpClient
     */
    protected $client;

    /**
     * AbstractApi constructor.
     *
     * @param HttpClient $client
     */
    public function __construct(HttpClient $client)
    {
        $this->client = $client;
    }

    /**
     * @param $data
     *
     * @return mixed|object
     */
    protected function hydrateOne($data)
    {
        if (empty($this->model) || empty($this->hydrator)) {
            return (object) $data;
        }

        $incoming = new \Incoming\Processor();

        return $incoming->process($data, new $this->model(), new $this->hydrator());
    }

    /**
     * @param $data
     *
     * @return array|object
     */
    protected function hydrateMany($data)
    {
        if (empty($this->model) || empty($this->hydrator)) {
            return (object) $data;
        }

        $items = [];

        foreach ($data as $item) {
            $items[] = $this->hydrateOne($item);
        }

        return $items;
    }

    /**
      * @param $url
      * @param array $parameters
      *
      * @return mixed
      */
    protected function get($url, $parameters = [])
    {
        $this->client->flushQuery();
        foreach($parameters as $key => $value)
        {
            $this->client->addQuery($key, $value);
        }

        return $this->client->get($url, $parameters);
    }

    /**
     * Call inaccessible methods of this class through the HttpClient.
     *
     * @param $name
     * @param $arguments
     *
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->client, $name], $arguments);
    }
}


<?php
/**
 *  Soluble Components (http://belgattitude.github.io/solublecomponents)
 *
 *  @link      http://github.com/belgattitude/solublecomponents for the canonical source repository
 *  @copyright Copyright (c) 2013-2014 Sébastien Vanvelthem
 *  @license   https://github.com/belgattitude/solublecomponents/blob/master/LICENSE.txt MIT License
 */
namespace Soluble\Db\Compat;

use Zend\Db\Adapter\Adapter;

class Adodb
{
    /**
     * Return a Zend\Db\Adapter\Adapter connection from an existing ADODb connection
     *
     * @throws Exception\UnsupportedDriverException
     * @throws Exception\AdoNotConnectedException when connection is not initialized
     *
     * @param \ADOConnection $adoConnection
     * @return Adapter
     */
    public static function getAdapter(\ADOConnection $adoConnection)
    {
        $adoConnectionDriver = strtolower(get_class($adoConnection));
        switch ($adoConnectionDriver) {
            //case 'adodb_mysqlt':
            case 'adodb_mysqli':
                $connectionId = self::getADOConnectionId($adoConnection);
                $adapter = Mysqli::getAdapter($connectionId);
                break;
            case 'adodb_pdo':
            case 'adodb_pdo_mysql':
                $connectionId = self::getADOConnectionId($adoConnection);
                $adapter = PDO::getAdapter($connectionId);
                break;
            default:
                throw new Exception\UnsupportedDriverException(__METHOD__ . ". Driver '$adoConnectionDriver' not supported");
        }
        return $adapter;
    }

    /**
     * Return internal adodb internal connection id
     * @throws Exception\AdoNotConnectedException when connection is not initialized
     * @param \ADOConnection $adoConnection
     * @return \MySQLI|\PDO
     */
    protected static function getADOConnectionId(\ADOConnection $adoConnection)
    {
        $connectionId = $adoConnection->_connectionID;
        if (!$connectionId) {
            throw new Exception\AdoNotConnectedException(__METHOD__ . ". Error: Invalid usage, adodb connection must be connected before use (see connect(), pconnect()");
        }
        return $connectionId;
    }
}


<?php
namespace Core\Toolbox\IO;

use Core\Toolbox\Converter\Filesize;

/**
 * Upload.php
 *
 * @author Michael "Tekkla" Zorn <tekkla@tekkla.de>
 * @copyright 2016-2017
 * @license MIT
 */
class Upload extends AbstractFile
{

    /**
     *
     * @var string
     */
    private $destination = '';

    /**
     *
     * @var bool
     */
    private $check_exists = true;

    /**
     * Sets destination
     *
     * @param string $destination
     *            Destination of the uploaded file
     */
    public function setDestination(string $destination)
    {
        $this->destination = $destination;
    }

    /**
     * Retruns destination
     *
     * @return string
     */
    public function getDestination(): string
    {
        return $this->destination;
    }

    /**
     * Set flag to check if the destination already exists
     *
     * @param bool $check_exists
     */
    public function setCheckExists(bool $check_exists)
    {
        $this->check_exists = $check_exists;
    }

    /**
     * Returns check destination already exists flag
     *
     * @return bool
     */
    public function getCheckExists(): bool
    {
        return $this->check_exists;
    }

    /**
     * Returns the maximum size for uploads in bytes
     *
     * @return int
     */
    public function getMaximumFileUploadSize()
    {
        $converter = new Filesize(ini_get('upload_max_filesize'));

        return $converter->phpSizeToBytes();
    }

    /**
     * Same as php's core move_uploaded_file extended with optional destination file exists check.
     *
     * @throws FileException when exists check is requested and destination already exists
     *
     * @return boolean
     */
    public function moveFile(): bool
    {
        if ($this->check_exists == true && file_exists($this->destination)) {
            Throw new FileException(sprintf('Destinationfile "%s" already exits.', $this->destination));
        }

        return move_uploaded_file($this->filename, $this->destination);
    }
}


<?php
namespace gossi\trixionary\client\action;

use gossi\trixionary\model\SportQuery;
use keeko\framework\domain\payload\Blank;
use keeko\framework\foundation\AbstractAction;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\OptionsResolver\OptionsResolver;
use phootwork\json\Json;
use keeko\framework\page\Meta;

/**
 * Shows the trixionary for a sport
 *
 * This code is automatically created. Modifications will probably be overwritten.
 *
 * @author Thomas Gossmann
 */
class SportAction extends AbstractAction {

	protected function configureParams(OptionsResolver $resolver) {
		$resolver->setDefined(['suffix', 'sport']);
	}

	/**
	 * Automatically generated run method
	 *
	 * @param Request $request
	 * @return Response
	 */
	public function run(Request $request) {
		$url = str_replace($request->getRequestUri(), '', $request->getUri());
		$baseurl = str_replace($url, '', $this->getBaseUrl());
		$sport = SportQuery::create()->findOneById($this->getParam('sport'));
		if (!$sport->getIsDefault()) {
			$baseurl .= '/' . $sport->getSlug();
		}

		// load assets
		$page = $this->getServiceContainer()->getKernel()->getApplication()->getPage();
		$repo = $this->getServiceContainer()->getResourceRepository();

		$page->addStyles($repo->find('/gossi/trixionary-client/public/app/assets/*.css')->getPaths());
		$page->addScripts($repo->find('/gossi/trixionary-client/public/app/assets/vendor-*.js')->getPaths());
		$page->addScripts($repo->find('/gossi/trixionary-client/public/app/assets/trixionary-*.js')->getPaths());

		// set configuration
		$prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences();
		$config = [
			'modulePrefix' => 'trixionary',
			'environment' => 'production',
			'rootURL' => $baseurl,
			'locationType' => 'auto',
			'APP' => [
				'name' => 'trixionary',
				'version' => '0.0.0+0d11dfba'
			],
			'keeko' => [
				'api' => $prefs->getApiUrl(),
				'trixionary' => [
					'sportId' => $sport->getId(),
					'slug' => [
						'skill' => $sport->getSkillSlug(),
						'group' => $sport->getGroupSlug(),
						'object' => $sport->getObjectSlug()
					]
				]
			]
		];
		$meta = new Meta();
		$meta->setName('trixionary/config/environment');
		$meta->setContent(rawurlencode(Json::encode($config)));
		$page->addMeta($meta);

		return $this->responder->run($request, new Blank([
			'sport' => $sport
		]));
	}
}


<?php

namespace Reaction\Console\Controllers;

use Reaction\Console\Routes\Controller;
use Reaction\RequestApplicationInterface;
use Reaction\Routes\ControllerInternalInterface;

/**
 * Controller used to print errors
 * @package Reaction\Console\Controllers
 */
class ErrorController extends Controller implements ControllerInternalInterface
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->baseViewPath = \Reaction::$app->getAlias('@reaction/Views');
        parent::init();
    }

    /**
     * Show error to user
     * @param RequestApplicationInterface $app
     * @param \Throwable                  $exception
     */
    public function actionError(RequestApplicationInterface $app, \Throwable $exception) {
        $logMessage = get_class($exception);
        if ($exception->getMessage()) {
            $logMessage .= "\n" . $exception->getMessage();
        }
        if ($exception->getFile() || $exception->getLine()) {
            $logMessage .= "\n" . $exception->getFile() . ":" . $exception->getLine();
        }
        \Reaction::$app->logger->logRaw($logMessage);
    }
}


<?php
namespace Li;

// $data = News::model()->findByPk(2);
// SELECT * FROM `news` WHERE (id = '2') LIMIT 1

// $data = News::model()->find(array(
//     // 'field'=>'id',
//     'condition'=>array(
//         array('id','=',1),
//     )
// ));
// SELECT * FROM `news` WHERE (id = '1') LIMIT 1

// $data = News::model()->findAll(array(
//     'field'=>'*',
//     'condition'=>array(
//         array('id','>',2),
//         array('title','!=',''),
//         array('id','in',array(1,2,3)),
//         array('id','between',array(1,5)),
//     ),
//     'order'=>'id desc',
// ));
// SELECT * FROM `news` WHERE (id > '2') AND (title != '') AND (id IN ('1','2','3')) AND (id BETWEEN '1' AND '5') ORDER BY id desc

// $data = News::model()
//     ->leftJoin('news_class','news_class.id=news.class')
//     ->findAll(array(
//         'field'=>'news.*,news_class.name',
//         'condition'=>array(
//             array('news.id','>',2),
//             array('title','!=',''),
//             array('news.id','in',array(1,2,3)),
//             array('news.id','between',array(1,5)),
//         ),
//         'order'=>'news.id desc',
//     )
// );
// SELECT news.*,news_class.name FROM `news` LEFT JOIN news_class ON news_class.id=news.class WHERE (news.id > '2') AND (title != '') AND (news.id IN ('1','2','3')) AND (news.id BETWEEN '1' AND '5') ORDER BY news.id desc

/*
criteria:
statement   // 类型
-all         // 暂时废弃
field       // 选择的列
condition   // where条件
values      // 绑定的值
limit       // limit
join        // 数组，存储join信息
order       // 排序
sql         // 最终解析的sql
 */

abstract class Model implements \ArrayAccess
{
    protected $_db = 'default'; // 数据库名
    protected $_table; // 表名
    protected $_pk = 'id'; // 主键

    const BELONGS_TO = 'BelongsToRelation';
    const HAS_ONE = 'HasOneRelation';
    const HAS_MANY = 'HasManyRelation';
    const MANY_MANY = 'ManyManyRelation';
    // const STAT = 'StatRelation';

    protected $_validator;
    protected $attributes = []; // 保存查询结果
    protected $_data; // 保存查询结果
    protected $_field;
    protected $_events = array(
        'beforeFind' => false,
        'beforeDelete' => false,
        'beforeSave' => false,
        'afterFind' => false,
        'afterDelete' => false,
        'afterSave' => false,
    );

    protected $_isNew = true;
    protected $_scenario = 'default';
    protected $_fetchStyle = \PDO::FETCH_ASSOC;

    protected static $_models = array();

    protected $_criteria;

    private $_position = 0;

    public function __construct($scenario = null)
    {
        if (!empty($scenario)) {
            $this->_scenario = $scenario;
        }
    }

    public function __get($name)
    {
        if (isset($this->$name)) {
            return $this->$name;
        }

        if (array_key_exists($name, $this->relations())) {
            $relation = $this->relations()[$name];
            if ($relation[1] == 'BelongsToRelation') {
                $this->attributes[$name] = $relation[2]::model()->find([
                    'condition' => [
                        [$relation[3], '=', $this->$relation[0]],
                    ],
                ]);

                return $this->attributes[$name];
            }
        }
        return null;
    }

    // public function __set($name, $value) {
    //     if($name == 'attributes' && is_array($value)) {
    //         $this->attributes = array_merge($this->attributes, $value);
    //     } else {
    //         $this->attributes[$name] = $value;
    //     }
    // }

    public function __isset($name)
    {
        return isset($this->attributes[$name]);
    }

    public function getDb()
    {
        return $this->_db;
    }

    public function getTable()
    {
        if (empty($this->_table)) {
            $this->_table = strtolower(get_class($this));
        }
        return $this->_table;
    }

    public function getPk()
    {
        return $this->_pk;
    }

    public function getCriteria($createIfNull = false)
    {
        if($createIfNull || $this->_criteria === null) {
            $this->_criteria = new Criteria();
        }

        return $this->_criteria;
    }

    public static function model($className = __CLASS__)
    {
        if (isset(self::$_models[$className])) {
            return self::$_models[$className];
        } else {
            $model = self::$_models[$className] = new $className(null);
            return $model;
        }
    }

    /**
     * [relations description]
     *
     *
     * return [
     *     '关系名' => ['当前表列名', 关系, '关联model名', '关联表列名'］
     * ]
     * @return [type] [description]
     */
    public function relations()
    {
        return [];
    }

    /**
     * [with description]
     * ->with('关系名', '关系名')
     * @return [type] [description]
     */

    public function with() {
        if(func_num_args()>0)
        {
            $this->_fetchStyle = \PDO::FETCH_NUM;
            $with=func_get_args();

            foreach($with as $name) {
                if (!array_key_exists($name, $this->relations())) {
                    throw new Exception('没有这个关系'.$name);
                }
            }

            $this->getCriteria()->with = $with;
        }

        return $this;
    }

    // protected function _transKeys($table, $keys)
    // {
    //     $field = [];

    //     if(!is_array($keys)) {
    //         $keys = explode(',', $keys);
    //     }

    //     foreach ($keys as $key) {
    //         $key = trim($key);
    //         $field[] = "{$table}.{$key} as {$table}_{$key}";
    //     }
    //     return $field;
    // }
    protected function _transKeys()
    {
        $ret_fields = [];
        $arr_fields = array_map('trim', explode(',', $this->_criteria->field));

        if (empty($this->_criteria['with'])) {
            if(in_array('*', $arr_fields)) {
                $ret_fields =  array_keys($this->alias());
            } else {
                $ret_fields = $arr_fields;
            }

        } else {
            if(in_array('*', $arr_fields)) {
                foreach($this->alias() as $col => $alias) {
                    $ret_fields[] = $this->getTable() . '.' . $col;
                }

                foreach($this->_criteria['with'] as $rela) {
                    $model = M($this->relations()[$rela][2]);
                    foreach($model->alias() as $col => $alias) {
                        $ret_fields[] = $model->getTable() . '.' . $col;
                    }
                }
            } else {
                foreach($arr_fields as $field) {
                    list($table, $field) = explode('.', $field);

                    if($table == $this->getTable()) {
                        $model = $this;
                    } else {
                        $model = M($this->getModelName($table));
                    }

                    if($field == '*') {
                        foreach($model->alias() as $col => $alias) {
                            $ret_fields[] = $table . '.' . $col;
                        }
                    } else {
                        $ret_fields[] = $table . '.' . $field;
                    }
                }
            }
        }

        return $ret_fields;
    }

    /**
     * 唤起事件
     */
    public function event($event)
    {
        if (!isset($this->_events[$event])) {
            throw new Exception("不支持事件：" . $event);
        }
        $this->_events[$event] = true;
        return $this;
    }

    /**
     * @return mixed null or array
     */
    public function find($criteria = null)
    {
        $this->getCriteria()->merge($criteria);

        $this->_criteria->statement = 'select';
        $this->_criteria->limit = 1;

        $this->build();

        return $this->populateRecord($this->_query($this->_fetchStyle));
    }

    /**
     * @return mixed null or model
     */
    public function findByPk($pk)
    {
        $this->getCriteria()->where($this->_pk, $pk);

        $this->_criteria['statement'] = 'select';
        $this->build();
        return $this->populateRecord($this->_query($this->_fetchStyle));
    }

    /**
     * @param mixed criteria find condition
     */
    public function findAll($criteria = null)
    {
        $this->getCriteria()->merge($criteria);

        $this->_criteria['statement'] = 'select';
        $this->build();

        return $this->populateRecords($this->_queryAll($this->_fetchStyle));
    }

    public function count($criteria = array())
    {
        $this->getCriteria()->merge($criteria);

        $this->_criteria->statement = 'select';
        $this->_criteria->field = 'COUNT(*) as `count`';

        $this->build();
        $ret = $this->_query()['count'];
        $this->reset();
        return $ret;
    }

    public function update($data, $criteria = null)
    {
        $this->getCriteria()->merge($criteria);

        $this->_criteria['statement'] = 'update';
        $this->_criteria['data'] = $data;

        $this->build();
        return $this->exec();
    }

    public function updateByPk($pk, $data)
    {
        if (empty($data) && !is_array($data)) {
            return false;
        }

        $this->_criteria['statement'] = 'update';

        $this->_criteria['condition'][] = array($this->_pk, $pk);

        $this->_criteria['data'] = $data;

        $this->build();
        return $this->exec();
    }

    public function delete($criteria = null)
    {
        if ($this->_events['beforeDelete']) {
            $this->beforeDelete();
        }
        $this->getCriteria()->merge($criteria);
        $this->_criteria['statement'] = 'delete';

        $this->build();

        if (!$this->exec()) {
            return false;
        }

        if ($this->_events['afterDelete']) {
            $this->afterDelete();
        }
        return true;
    }

    public function deleteByPk($pk)
    {
        if ($this->_events['beforeDelete']) {
            $this->beforeDelete();
        }
        $this->_criteria['statement'] = 'delete';
        $this->_criteria['condition'][] = array($this->_pk, $pk);
        $this->build();

        if (!$this->exec()) {
            return false;
        }

        if ($this->_events['afterDelete']) {
            $this->afterDelete();
        }
        return true;
    }

    /**
     * 返回结果数组以$index为key
     * @param  [type] $index [description]
     * @return [type]        [description]
     */
    public function index($index)
    {
        $this->getCriteria()->index = $index;

        return $this;
    }

    protected function build()
    {
        $sqlConditon = '';

        if (is_array($this->_criteria->condition)
            && !empty($this->_criteria->condition)
        ) {
            $i = 0;
            $condition = null;
            foreach ($this->_criteria->condition as $value) {
                if (is_array($value)) {
                    if (count($value) == 3) {
                        $value[1] = strtolower($value[1]);
                        if ($value[1] == 'in') {
                            $inCount = count($value[2]);
                            $in = '';
                            foreach ($value[2] as $key => $inValue) {
                                $in .= ':' . $i;
                                if ($key < $inCount - 1) {
                                    $in .= ',';
                                }
                                $this->_criteria->values[] = array(':' . $i, $inValue);
                                $i++;
                            }

                            $condition[] = '(' . $value[0] . ' IN ' . '(' . $in . '))';
                        } elseif ($value[1] == 'between') {
                            $condition[] = '(' . $value[0] . ' BETWEEN ' . ':' . $i . ' AND :' . ($i + 1) . ')';
                            $this->_criteria->values[] = array(':' . $i, $value[2][0]);
                            $this->_criteria->values[] = array(':' . ($i + 1), $value[2][1]);
                            $i += 2;
                        } else {
                            $condition[] = '(' . $value[0] . ' ' . $value[1] . ' ' . ':' . $i . ')';
                            $this->_criteria->values[] = array(':' . $i, $value[2]);
                        }
                    }
                    $i++;
                } else {
                    $condition[] = $value;
                }
            }

            $sqlConditon .= ' WHERE ' . implode(' AND ', $condition);
        }

        if ($this->_criteria['statement'] == 'select') {
            $this->_field = $this->_transKeys();

            if (!empty($this->_criteria['with'])) {

                foreach ($this->_criteria['with'] as $rela) {
                    $relation = $this->relations()[$rela];

                    $this->leftJoin(M($relation[2])->getTable(), $this->getTable() . '.' . $relation[0] . '=' . M($relation[2])->getTable() . '.'. $relation[3]);
                }

                $this->_criteria['field'] = implode(',', $this->_field);
            }

            $sql = 'SELECT ' . $this->_criteria['field'] . ' FROM `' . $this->getTable() . '`';

            if (!empty($this->_criteria->join)) {
                foreach ($this->_criteria->join as $key => $value) {
                    $sql .= $value;
                }
            }

            $sql .= $sqlConditon;

            if (isset($this->_criteria['group'])) {
                $sql .= ' GROUP BY ' . $this->_criteria['group'];

                if (isset($this->_criteria['having'])) {
                    $sql .= ' HAVING ' . $this->_criteria['having'];
                }
            }

            if (isset($this->_criteria['order'])) {
                $sql .= ' ORDER BY ' . $this->_criteria['order'];
            }

            if (!empty($this->_criteria['limit'])) {
                $sql .= ' LIMIT ' . $this->_criteria['limit'];
            }
        } elseif ($this->_criteria['statement'] == 'update') {
            $sql = 'UPDATE `' . $this->getTable() . '` SET';

            $countData = count($this->_criteria['data']);
            $iData = 0;
            foreach ($this->_criteria['data'] as $key => $value) {
                if ($value instanceof Expression) {
                    $sql .= '`'. $key . '`='.$value;
                } else {
                    $sql .= ' `' . $key . '`=:' . $key;
                    $this->_criteria->values[] = array(':' . $key, $value);
                }

                if ($iData < $countData - 1) {
                    $sql .= ',';
                }

                $iData++;
            }

            $sql .= $sqlConditon;
        } elseif ($this->_criteria['statement'] == 'insert') {
            $sql = 'INSERT INTO `' . $this->getTable() . '` (';
            $sqlField = '';
            $sqlValue = '';

            $countField = count($this->_criteria['field']);

            foreach ($this->_criteria['field'] as $key => $value) {
                $sqlField .= '`' . $value . '`';
                $sqlValue .= ':' . $value;
                if ($key < $countField - 1) {
                    $sqlField .= ',';
                    $sqlValue .= ',';
                }
            }

            $sql .= $sqlField . ') VALUES (' . $sqlValue . ')';
        } elseif ($this->_criteria['statement'] == 'delete') {
            $sql = 'DELETE FROM `' . $this->getTable() . '`';
            $sql .= $sqlConditon;
        }

        $this->_criteria->sql = $sql;
    }

    public function getCondition()
    {
        return $this->_criteria->condition;
    }

    private function _query($fetchStyle = \PDO::FETCH_ASSOC)
    {
        if ($this->_events['beforeFind']) {
            $this->beforeFind();
        }
        $dbName = $this->getDb();
        Db::db()->$dbName->prepare($this->_criteria->sql);
        if(isset($this->_criteria->values) && is_array($this->_criteria->values)) {
            Db::db()->$dbName->bindValues($this->_criteria->values);
        }
        return Db::db()->$dbName->fetch($fetchStyle);
    }

    private function _queryAll($fetchStyle = \PDO::FETCH_ASSOC)
    {
        if ($this->_events['beforeFind']) {
            $this->beforeFind();
        }
        $dbName = $this->getDb();
        Db::db()->$dbName->prepare($this->_criteria->sql);
        if(isset($this->_criteria->values) && is_array($this->_criteria->values)) {
            Db::db()->$dbName->bindValues($this->_criteria->values);
        }
        return Db::db()->$dbName->fetchAll($fetchStyle);
    }

    protected function init()
    {
    }

    protected function instantiate($attributes)
    {
        $class = get_class($this);
        $model = new $class();

        foreach ($attributes as $name=>$value) {
            if (property_exists($model, $name)) {
                throw new Exception('类中不允许有和表字段名相同的属性'.$name);
            } else {
                if(is_array($value)) {
                    $model->$name = M($this->getModelName($name))->instantiate($value);
                } else {
                    $model->$name=$value;
                }
                $model->attributes[] = $name;
            }
        }

        return $model;
    }

    protected function populateRecord($attributes, $reset=true)
    {
        $data = [];

        if(empty($this->_criteria['with'])) {
            $data = $attributes;
        } else {
            foreach($this->_field as $key => $field) {
                list($table, $field) = explode('.', $field);

                if($table == $this->getTable()) {
                    $data[$field] = $attributes[$key];
                } else {
                    $data[$table][$field] = $attributes[$key];
                }
            }

        }

        $record = $this->instantiate($data);
        $record->_isNew = false;
        $record->init();
        if ($this->_events['afterFind']) {
            $record->afterFind();
        }
        if ($reset) {
            $this->reset();
        }
        return $record;
    }

    protected function beforeFind()
    {
    }
    protected function beforeDelete()
    {
    }
    protected function beforeSave()
    {
    }
    protected function afterFind()
    {
    }
    protected function afterDelete()
    {
    }
    protected function afterSave()
    {
    }

    /**
     * 获得关联查询结果集中的数据
     * @return [type] [description]
     */
    protected function _getRelationAttributes($data, $relation)
    {
    }

    protected function populateRecords($data)
    {
        $records = array();
        if (!empty($this->_criteria['with'])) {
            foreach ($data as $value) {
                if (($record = $this->populateRecord($value, false)) !== null) {
                    $records[] = $record;
                }
            }
        } else {
            foreach ($data as $attributes) {
                if (($record = $this->populateRecord($attributes, false)) !== null) {
                    if (!isset($this->_criteria->index)) {
                        $records[] = $record;
                    } else {
                        $records[$record->{$this->_criteria->index}] = $record;
                    }
                }
            }
        }
        $this->reset();
        return $records;
    }

    protected function exec()
    {
        $dbName = $this->getDb();
        Db::db()->$dbName->prepare($this->_criteria->sql);
        Db::db()->$dbName->bindValues($this->_criteria->values);
        $this->reset();
        return Db::db()->$dbName->execute();
    }

    public function save($runValidation = true, $attributeNames = null)
    {
        if ($runValidation === true) {
            if ($this->_isNew) {
                if ($this->validate($this->_scenario)) {
                    return false;
                }
            }
        }

        if ($this->_events['beforeSave']) {
            $this->beforeSave();
        }
        $pk = $this->getPk();

        if ($this->_isNew) {
            $this->_criteria['statement'] = 'insert';
            $this->_criteria['field'] = array();

            foreach ($this->attributes as $key => $value) {
                $this->_criteria['field'][] = $key;
                $this->_criteria->values[] = array(':' . $key, $value);
            }
        } else {
            $this->_criteria['statement'] = 'update';
            $this->where($pk, $this->$pk);
            $this->_criteria['data'] = $this->attributes;
        }
        $this->build();
        $ret = $this->exec();
        if ($this->_isNew) {
            $this->$pk = $this->getLastId();
        }
        if ($this->_events['afterSave']) {
            $this->afterSave();
        }
        return $ret;
    }

    public function getLastId()
    {
        $dbName = $this->getDb();
        return Db::db()->$dbName->getLastInsertID();
    }

    /**
     * ->whereSql('id>%d and id < %d', 6, 9)
     * 不推荐使用
     */
    public function whereSql()
    {
        $this->getCriteria()->whereSql(...func_get_args());
        return $this;
    }

    /**
     * 支持1,2,3个参数
     * $model->where('name','=','test')
     *       ->where('id','in',array(1,2,3))
     *       ->where('id=1 or id=2')
     *       ->where('score','>',10);
     *       ->where('score',8);
     *       ->where( [
     *           ['id','in',array(1,2,3)],
     *           ['score','>',10],
     *       ]
     *       )
     */
    public function where()
    {
        $this->getCriteria()->where(...func_get_args());
        return $this;
    }

    // public function first()
    // {
    //     if(empty($this->_data))
    //     {
    //         return null;
    //     }
    //     $this->attributes = $this->_data[0];
    //     return $this;
    // }

    protected function filter()
    {
        $num_args = func_num_args();
        $args = func_get_args();

        if ($num_args == 1) {
            if (isset($_GET[$args[0]]) && !empty($_GET[$args[0]])) {
                $this->where($args[0], $_GET[$args[0]]);
            }
        } elseif ($num_args == 2 && !empty($args[1])) {
            $this->where($args[0], $args[1]);
        } elseif ($num_args == 3 && !empty($args[2])) {
            $this->where($args[0], $args[1], $args[2]);
        }
    }

    public function group($group)
    {
        $this->_criteria['group'] = $group;
        return $this;
    }

    public function order($order)
    {
        $this->getCriteria()->order = $order;
        return $this;
    }

    protected function having($having)
    {
        $this->_criteria['having'] = $having;
        return $this;
    }

    public function page($page, $pageSize = 10)
    {
        $page = $page;
        if ($page < 1) {
            $page = 1;
        }
        return $this->limit(($page - 1) * $pageSize, $pageSize);
    }

    public function limit($offset, $row_count)
    {
        $offset = intval($offset);
        $row_count = intval($row_count);
        $this->getCriteria()->limit = "$offset, $row_count";

        return $this;
    }

    public function field($field)
    {
        $this->getCriteria()->field = $field;
        return $this;
    }

    protected function join($table, $condition)
    {
        $this->getCriteria()->join[] = " INNER JOIN $table ON $condition";
        return $this;
    }

    protected function leftJoin($table, $condition)
    {
        $this->getCriteria()->join[] = " LEFT JOIN $table ON $condition";
        return $this;
    }
    protected function rightJoin($table, $condition)
    {
        $this->getCriteria()->join[] = " RIGHT JOIN $table ON $condition";
        return $this;
    }

    public function reset()
    {
        $this->_criteria = null;
        $this->attributes = [];
    }

    protected function getColumns($tableName = '')
    {
        if ($tableName == '') {
            $tableName = $this->getTable();
        }

        $this->_criteria->sql = 'SHOW FULL COLUMNS FROM `' . $tableName . '`';

        $dbName = $this->getDb();
        Db::db()->$dbName->prepare($this->_criteria->sql);
        $column = Db::db()->$dbName->fetchAll();
        $this->reset();

        unset($value);
        foreach ($column as &$value) {
            $value['dataType'] = $this->_extractType($value['Type']);
        }

        return $column;
    }

    private function _extractType($dbType)
    {
        if (stripos($dbType, 'int') !== false && stripos($dbType, 'unsigned int') === false) {
            $type = 'integer';
        } elseif (stripos($dbType, 'bool') !== false) {
            $type = 'boolean';
        } elseif (preg_match('/(real|floa|doub)/i', $dbType)) {
            $type = 'double';
        } else {
            $type = 'string';
        }

        return $type;
    }

    public function validate($scenario = '')
    {
        if (!empty($scenario)) {
            $this->_scenario = $scenario;
        }

        $rules = $this->rules();

        if (isset($rules[$this->_scenario])) {
            $this->_validator = Validator::make($this->attributes, $rules[$this->_scenario], [], $this->alias());
            return $this->_validator->fails();
        }

        return true;
    }

    public function getValidator($scene = 'default')
    {
        $rule = $this->rules();
        if (isset($this->_validator) && $this->_validator instanceof Validator) {
            $this->_validator->getValidator();
        } else {
            return '{}';
        }
    }

    public function getErrors()
    {
        if ($this->_validator instanceof Validator) {
            return $this->_validator->errors;
        }

        return [];
    }

    protected function rules()
    {
        return array();
    }

    protected function alias()
    {
        return array();
    }

    // private $container = array();
    // public function __construct() {
    //     $this->container = array(
    //         "one"   => 1,
    //         "two"   => 2,
    //         "three" => 3,
    //     );
    // }

    public function offsetSet($offset, $value)
    {
        $this->$offset = $value;
    }
    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }
    public function offsetUnset($offset)
    {
        unset($this->$offset);
    }
    public function offsetGet($offset)
    {
        return isset($this->$offset) ? $this->$offset : null;
    }

    public function getAttributes()
    {
        return $this->attributes;
    }

    public function getModelName($name, $ucfrist = true)
    {
        $newName = '';
        for ($i=0; $i<strlen($name); $i++) {
            if ($name[$i] == '_') {
                $name[$i+1] = strtoupper($name[$i+1]);
            } else {
                $newName .= $name[$i];
            }
        }
        if ($ucfrist) {
            return ucfirst($newName);
        }
        return $newName;
    }
}


<?php
/**
 * Adapter for HTTP_Request2 wrapping around cURL extension
 *
 * PHP version 5
 *
 * LICENSE
 *
 * This source file is subject to BSD 3-Clause License that is bundled
 * with this package in the file LICENSE and available at the URL
 * https://raw.github.com/pear/HTTP_Request2/trunk/docs/LICENSE
 *
 * @category  HTTP
 * @package   HTTP_Request2
 * @author    Alexey Borzov <avb@php.net>
 * @copyright 2008-2014 Alexey Borzov <avb@php.net>
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
 * @link      http://pear.php.net/package/HTTP_Request2
 */

/**
 * Base class for HTTP_Request2 adapters
 */
require_once 'HTTP/Request2/Adapter.php';

/**
 * Adapter for HTTP_Request2 wrapping around cURL extension
 *
 * @category HTTP
 * @package  HTTP_Request2
 * @author   Alexey Borzov <avb@php.net>
 * @license  http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
 * @version  Release: 2.2.1
 * @link     http://pear.php.net/package/HTTP_Request2
 */
class HTTP_Request2_Adapter_Curl extends HTTP_Request2_Adapter
{
    /**
     * Mapping of header names to cURL options
     * @var  array
     */
    protected static $headerMap = array(
        'accept-encoding' => CURLOPT_ENCODING,
        'cookie'          => CURLOPT_COOKIE,
        'referer'         => CURLOPT_REFERER,
        'user-agent'      => CURLOPT_USERAGENT
    );

    /**
     * Mapping of SSL context options to cURL options
     * @var  array
     */
    protected static $sslContextMap = array(
        'ssl_verify_peer' => CURLOPT_SSL_VERIFYPEER,
        'ssl_cafile'      => CURLOPT_CAINFO,
        'ssl_capath'      => CURLOPT_CAPATH,
        'ssl_local_cert'  => CURLOPT_SSLCERT,
        'ssl_passphrase'  => CURLOPT_SSLCERTPASSWD
    );

    /**
     * Mapping of CURLE_* constants to Exception subclasses and error codes
     * @var  array
     */
    protected static $errorMap = array(
        CURLE_UNSUPPORTED_PROTOCOL  => array('HTTP_Request2_MessageException',
                                             HTTP_Request2_Exception::NON_HTTP_REDIRECT),
        CURLE_COULDNT_RESOLVE_PROXY => array('HTTP_Request2_ConnectionException'),
        CURLE_COULDNT_RESOLVE_HOST  => array('HTTP_Request2_ConnectionException'),
        CURLE_COULDNT_CONNECT       => array('HTTP_Request2_ConnectionException'),
        // error returned from write callback
        CURLE_WRITE_ERROR           => array('HTTP_Request2_MessageException',
                                             HTTP_Request2_Exception::NON_HTTP_REDIRECT),
        CURLE_OPERATION_TIMEOUTED   => array('HTTP_Request2_MessageException',
                                             HTTP_Request2_Exception::TIMEOUT),
        CURLE_HTTP_RANGE_ERROR      => array('HTTP_Request2_MessageException'),
        CURLE_SSL_CONNECT_ERROR     => array('HTTP_Request2_ConnectionException'),
        CURLE_LIBRARY_NOT_FOUND     => array('HTTP_Request2_LogicException',
                                             HTTP_Request2_Exception::MISCONFIGURATION),
        CURLE_FUNCTION_NOT_FOUND    => array('HTTP_Request2_LogicException',
                                             HTTP_Request2_Exception::MISCONFIGURATION),
        CURLE_ABORTED_BY_CALLBACK   => array('HTTP_Request2_MessageException',
                                             HTTP_Request2_Exception::NON_HTTP_REDIRECT),
        CURLE_TOO_MANY_REDIRECTS    => array('HTTP_Request2_MessageException',
                                             HTTP_Request2_Exception::TOO_MANY_REDIRECTS),
        CURLE_SSL_PEER_CERTIFICATE  => array('HTTP_Request2_ConnectionException'),
        CURLE_GOT_NOTHING           => array('HTTP_Request2_MessageException'),
        CURLE_SSL_ENGINE_NOTFOUND   => array('HTTP_Request2_LogicException',
                                             HTTP_Request2_Exception::MISCONFIGURATION),
        CURLE_SSL_ENGINE_SETFAILED  => array('HTTP_Request2_LogicException',
                                             HTTP_Request2_Exception::MISCONFIGURATION),
        CURLE_SEND_ERROR            => array('HTTP_Request2_MessageException'),
        CURLE_RECV_ERROR            => array('HTTP_Request2_MessageException'),
        CURLE_SSL_CERTPROBLEM       => array('HTTP_Request2_LogicException',
                                             HTTP_Request2_Exception::INVALID_ARGUMENT),
        CURLE_SSL_CIPHER            => array('HTTP_Request2_ConnectionException'),
        CURLE_SSL_CACERT            => array('HTTP_Request2_ConnectionException'),
        CURLE_BAD_CONTENT_ENCODING  => array('HTTP_Request2_MessageException'),
    );

    /**
     * Response being received
     * @var  HTTP_Request2_Response
     */
    protected $response;

    /**
     * Whether 'sentHeaders' event was sent to observers
     * @var  boolean
     */
    protected $eventSentHeaders = false;

    /**
     * Whether 'receivedHeaders' event was sent to observers
     * @var boolean
     */
    protected $eventReceivedHeaders = false;

    /**
     * Position within request body
     * @var  integer
     * @see  callbackReadBody()
     */
    protected $position = 0;

    /**
     * Information about last transfer, as returned by curl_getinfo()
     * @var  array
     */
    protected $lastInfo;

    /**
     * Creates a subclass of HTTP_Request2_Exception from curl error data
     *
     * @param resource $ch curl handle
     *
     * @return HTTP_Request2_Exception
     */
    protected static function wrapCurlError($ch)
    {
        $nativeCode = curl_errno($ch);
        $message    = 'Curl error: ' . curl_error($ch);
        if (!isset(self::$errorMap[$nativeCode])) {
            return new HTTP_Request2_Exception($message, 0, $nativeCode);
        } else {
            $class = self::$errorMap[$nativeCode][0];
            $code  = empty(self::$errorMap[$nativeCode][1])
                     ? 0 : self::$errorMap[$nativeCode][1];
            return new $class($message, $code, $nativeCode);
        }
    }

    /**
     * Sends request to the remote server and returns its response
     *
     * @param HTTP_Request2 $request HTTP request message
     *
     * @return   HTTP_Request2_Response
     * @throws   HTTP_Request2_Exception
     */
    public function sendRequest(HTTP_Request2 $request)
    {
        if (!extension_loaded('curl')) {
            throw new HTTP_Request2_LogicException(
                'cURL extension not available', HTTP_Request2_Exception::MISCONFIGURATION
            );
        }

        $this->request              = $request;
        $this->response             = null;
        $this->position             = 0;
        $this->eventSentHeaders     = false;
        $this->eventReceivedHeaders = false;

        try {
            if (false === curl_exec($ch = $this->createCurlHandle())) {
                $e = self::wrapCurlError($ch);
            }
        } catch (Exception $e) {
        }
        if (isset($ch)) {
            $this->lastInfo = curl_getinfo($ch);
            curl_close($ch);
        }

        $response = $this->response;
        unset($this->request, $this->requestBody, $this->response);

        if (!empty($e)) {
            throw $e;
        }

        if ($jar = $request->getCookieJar()) {
            $jar->addCookiesFromResponse($response, $request->getUrl());
        }

        if (0 < $this->lastInfo['size_download']) {
            $request->setLastEvent('receivedBody', $response);
        }
        return $response;
    }

    /**
     * Returns information about last transfer
     *
     * @return   array   associative array as returned by curl_getinfo()
     */
    public function getInfo()
    {
        return $this->lastInfo;
    }

    /**
     * Creates a new cURL handle and populates it with data from the request
     *
     * @return   resource    a cURL handle, as created by curl_init()
     * @throws   HTTP_Request2_LogicException
     * @throws   HTTP_Request2_NotImplementedException
     */
    protected function createCurlHandle()
    {
        $ch = curl_init();

        curl_setopt_array($ch, array(
            // setup write callbacks
            CURLOPT_HEADERFUNCTION => array($this, 'callbackWriteHeader'),
            CURLOPT_WRITEFUNCTION  => array($this, 'callbackWriteBody'),
            // buffer size
            CURLOPT_BUFFERSIZE     => $this->request->getConfig('buffer_size'),
            // connection timeout
            CURLOPT_CONNECTTIMEOUT => $this->request->getConfig('connect_timeout'),
            // save full outgoing headers, in case someone is interested
            CURLINFO_HEADER_OUT    => true,
            // request url
            CURLOPT_URL            => $this->request->getUrl()->getUrl()
        ));

        // set up redirects
        if (!$this->request->getConfig('follow_redirects')) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        } else {
            if (!@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true)) {
                throw new HTTP_Request2_LogicException(
                    'Redirect support in curl is unavailable due to open_basedir or safe_mode setting',
                    HTTP_Request2_Exception::MISCONFIGURATION
                );
            }
            curl_setopt($ch, CURLOPT_MAXREDIRS, $this->request->getConfig('max_redirects'));
            // limit redirects to http(s), works in 5.2.10+
            if (defined('CURLOPT_REDIR_PROTOCOLS')) {
                curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
            }
            // works in 5.3.2+, http://bugs.php.net/bug.php?id=49571
            if ($this->request->getConfig('strict_redirects') && defined('CURLOPT_POSTREDIR')) {
                curl_setopt($ch, CURLOPT_POSTREDIR, 3);
            }
        }

        // set local IP via CURLOPT_INTERFACE (request #19515)
        if ($ip = $this->request->getConfig('local_ip')) {
            curl_setopt($ch, CURLOPT_INTERFACE, $ip);
        }

        // request timeout
        if ($timeout = $this->request->getConfig('timeout')) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        }

        // set HTTP version
        switch ($this->request->getConfig('protocol_version')) {
        case '1.0':
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            break;
        case '1.1':
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        }

        // set request method
        switch ($this->request->getMethod()) {
        case HTTP_Request2::METHOD_GET:
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            break;
        case HTTP_Request2::METHOD_POST:
            curl_setopt($ch, CURLOPT_POST, true);
            break;
        case HTTP_Request2::METHOD_HEAD:
            curl_setopt($ch, CURLOPT_NOBODY, true);
            break;
        case HTTP_Request2::METHOD_PUT:
            curl_setopt($ch, CURLOPT_UPLOAD, true);
            break;
        default:
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->request->getMethod());
        }

        // set proxy, if needed
        if ($host = $this->request->getConfig('proxy_host')) {
            if (!($port = $this->request->getConfig('proxy_port'))) {
                throw new HTTP_Request2_LogicException(
                    'Proxy port not provided', HTTP_Request2_Exception::MISSING_VALUE
                );
            }
            curl_setopt($ch, CURLOPT_PROXY, $host . ':' . $port);
            if ($user = $this->request->getConfig('proxy_user')) {
                curl_setopt(
                    $ch, CURLOPT_PROXYUSERPWD,
                    $user . ':' . $this->request->getConfig('proxy_password')
                );
                switch ($this->request->getConfig('proxy_auth_scheme')) {
                case HTTP_Request2::AUTH_BASIC:
                    curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
                    break;
                case HTTP_Request2::AUTH_DIGEST:
                    curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_DIGEST);
                }
            }
            if ($type = $this->request->getConfig('proxy_type')) {
                switch ($type) {
                case 'http':
                    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
                    break;
                case 'socks5':
                    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
                    break;
                default:
                    throw new HTTP_Request2_NotImplementedException(
                        "Proxy type '{$type}' is not supported"
                    );
                }
            }
        }

        // set authentication data
        if ($auth = $this->request->getAuth()) {
            curl_setopt($ch, CURLOPT_USERPWD, $auth['user'] . ':' . $auth['password']);
            switch ($auth['scheme']) {
            case HTTP_Request2::AUTH_BASIC:
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                break;
            case HTTP_Request2::AUTH_DIGEST:
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
            }
        }

        // set SSL options
        foreach ($this->request->getConfig() as $name => $value) {
            if ('ssl_verify_host' == $name && null !== $value) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $value? 2: 0);
            } elseif (isset(self::$sslContextMap[$name]) && null !== $value) {
                curl_setopt($ch, self::$sslContextMap[$name], $value);
            }
        }

        $headers = $this->request->getHeaders();
        // make cURL automagically send proper header
        if (!isset($headers['accept-encoding'])) {
            $headers['accept-encoding'] = '';
        }

        if (($jar = $this->request->getCookieJar())
            && ($cookies = $jar->getMatching($this->request->getUrl(), true))
        ) {
            $headers['cookie'] = (empty($headers['cookie'])? '': $headers['cookie'] . '; ') . $cookies;
        }

        // set headers having special cURL keys
        foreach (self::$headerMap as $name => $option) {
            if (isset($headers[$name])) {
                curl_setopt($ch, $option, $headers[$name]);
                unset($headers[$name]);
            }
        }

        $this->calculateRequestLength($headers);
        if (isset($headers['content-length']) || isset($headers['transfer-encoding'])) {
            $this->workaroundPhpBug47204($ch, $headers);
        }

        // set headers not having special keys
        $headersFmt = array();
        foreach ($headers as $name => $value) {
            $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
            $headersFmt[]  = $canonicalName . ': ' . $value;
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headersFmt);

        return $ch;
    }

    /**
     * Workaround for PHP bug #47204 that prevents rewinding request body
     *
     * The workaround consists of reading the entire request body into memory
     * and setting it as CURLOPT_POSTFIELDS, so it isn't recommended for large
     * file uploads, use Socket adapter instead.
     *
     * @param resource $ch       cURL handle
     * @param array    &$headers Request headers
     */
    protected function workaroundPhpBug47204($ch, &$headers)
    {
        // no redirects, no digest auth -> probably no rewind needed
        if (!$this->request->getConfig('follow_redirects')
            && (!($auth = $this->request->getAuth())
                || HTTP_Request2::AUTH_DIGEST != $auth['scheme'])
        ) {
            curl_setopt($ch, CURLOPT_READFUNCTION, array($this, 'callbackReadBody'));

        } else {
            // rewind may be needed, read the whole body into memory
            if ($this->requestBody instanceof HTTP_Request2_MultipartBody) {
                $this->requestBody = $this->requestBody->__toString();

            } elseif (is_resource($this->requestBody)) {
                $fp = $this->requestBody;
                $this->requestBody = '';
                while (!feof($fp)) {
                    $this->requestBody .= fread($fp, 16384);
                }
            }
            // curl hangs up if content-length is present
            unset($headers['content-length']);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestBody);
        }
    }

    /**
     * Callback function called by cURL for reading the request body
     *
     * @param resource $ch     cURL handle
     * @param resource $fd     file descriptor (not used)
     * @param integer  $length maximum length of data to return
     *
     * @return   string      part of the request body, up to $length bytes
     */
    protected function callbackReadBody($ch, $fd, $length)
    {
        if (!$this->eventSentHeaders) {
            $this->request->setLastEvent(
                'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
            );
            $this->eventSentHeaders = true;
        }
        if (in_array($this->request->getMethod(), self::$bodyDisallowed)
            || 0 == $this->contentLength || $this->position >= $this->contentLength
        ) {
            return '';
        }
        if (is_string($this->requestBody)) {
            $string = substr($this->requestBody, $this->position, $length);
        } elseif (is_resource($this->requestBody)) {
            $string = fread($this->requestBody, $length);
        } else {
            $string = $this->requestBody->read($length);
        }
        $this->request->setLastEvent('sentBodyPart', strlen($string));
        $this->position += strlen($string);
        return $string;
    }

    /**
     * Callback function called by cURL for saving the response headers
     *
     * @param resource $ch     cURL handle
     * @param string   $string response header (with trailing CRLF)
     *
     * @return   integer     number of bytes saved
     * @see      HTTP_Request2_Response::parseHeaderLine()
     */
    protected function callbackWriteHeader($ch, $string)
    {
        // we may receive a second set of headers if doing e.g. digest auth
        if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
            // don't bother with 100-Continue responses (bug #15785)
            if (!$this->eventSentHeaders
                || $this->response->getStatus() >= 200
            ) {
                $this->request->setLastEvent(
                    'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
                );
            }
            $upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
            // if body wasn't read by a callback, send event with total body size
            if ($upload > $this->position) {
                $this->request->setLastEvent(
                    'sentBodyPart', $upload - $this->position
                );
                $this->position = $upload;
            }
            if ($upload && (!$this->eventSentHeaders
                            || $this->response->getStatus() >= 200)
            ) {
                $this->request->setLastEvent('sentBody', $upload);
            }
            $this->eventSentHeaders = true;
            // we'll need a new response object
            if ($this->eventReceivedHeaders) {
                $this->eventReceivedHeaders = false;
                $this->response             = null;
            }
        }
        if (empty($this->response)) {
            $this->response = new HTTP_Request2_Response(
                $string, false, curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)
            );
        } else {
            $this->response->parseHeaderLine($string);
            if ('' == trim($string)) {
                // don't bother with 100-Continue responses (bug #15785)
                if (200 <= $this->response->getStatus()) {
                    $this->request->setLastEvent('receivedHeaders', $this->response);
                }

                if ($this->request->getConfig('follow_redirects') && $this->response->isRedirect()) {
                    $redirectUrl = new Net_URL2($this->response->getHeader('location'));

                    // for versions lower than 5.2.10, check the redirection URL protocol
                    if (!defined('CURLOPT_REDIR_PROTOCOLS') && $redirectUrl->isAbsolute()
                        && !in_array($redirectUrl->getScheme(), array('http', 'https'))
                    ) {
                        return -1;
                    }

                    if ($jar = $this->request->getCookieJar()) {
                        $jar->addCookiesFromResponse($this->response, $this->request->getUrl());
                        if (!$redirectUrl->isAbsolute()) {
                            $redirectUrl = $this->request->getUrl()->resolve($redirectUrl);
                        }
                        if ($cookies = $jar->getMatching($redirectUrl, true)) {
                            curl_setopt($ch, CURLOPT_COOKIE, $cookies);
                        }
                    }
                }
                $this->eventReceivedHeaders = true;
            }
        }
        return strlen($string);
    }

    /**
     * Callback function called by cURL for saving the response body
     *
     * @param resource $ch     cURL handle (not used)
     * @param string   $string part of the response body
     *
     * @return   integer     number of bytes saved
     * @throws   HTTP_Request2_MessageException
     * @see      HTTP_Request2_Response::appendBody()
     */
    protected function callbackWriteBody($ch, $string)
    {
        // cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
        // response doesn't start with proper HTTP status line (see bug #15716)
        if (empty($this->response)) {
            throw new HTTP_Request2_MessageException(
                "Malformed response: {$string}",
                HTTP_Request2_Exception::MALFORMED_RESPONSE
            );
        }
        if ($this->request->getConfig('store_body')) {
            $this->response->appendBody($string);
        }
        $this->request->setLastEvent('receivedBodyPart', $string);
        return strlen($string);
    }
}
?>


<?php

declare(strict_types=1);

namespace NAttreid\Console;

use Nette\Reflection\ClassType;
use Nette\Reflection\Method;
use Nette\SmartObject;
use Nette\Utils\Html;
use Nette\Utils\Strings;

/**
 *
 *
 * @author Attreid <attreid@gmail.com>
 */
class Console
{
	use SmartObject;

	/** @var bool */
	private $isConsole;

	/** @var string */
	private $prefix;

	/** @var CommandCollection[] */
	private $collections = [];

	public function __construct(bool $isConsole, string $prefix)
	{
		$this->isConsole = $isConsole;
		$this->prefix = $prefix;
	}

	/**
	 * Je apliakce spustena pres prikazovy radek?
	 * @return bool
	 */
	public function isConsole(): bool
	{
		return $this->isConsole;
	}

	/**
	 * Prida kolekci prikazu
	 * @param CommandCollection $collection
	 */
	public function addCommandCollection(CommandCollection $collection)
	{
		$collection->setConsole($this);
		$class = new ClassType($collection);
		$this->collections[Strings::lower($class->getShortName())] = $collection;
	}

	/**
	 * Spusti prikaz
	 * @param string $collection
	 * @param string $command
	 * @param array $args
	 * @throws InvalidArgumentException
	 */
	public function execute(string $collection = null, string $command = null, array $args = []): void
	{
		$collection = Strings::lower($collection);

		if (isset($this->collections[$collection])) {
			$class = new ClassType($this->collections[$collection]);
		} else {
			$class = null;
		}

		if ($command === 'help' || (empty($command) && empty($collection)) || (($collection === 'help' || $class !== null) && empty($command))) {
			$this->help($class);
			return;
		} elseif ($class !== null) {
			if ($class->hasMethod($command)) {
				$method = $class->getMethod($command);
				if ($method->isPublic() && !$method->isAbstract() && !$method->isStatic()) {
					$this->printTime($class->getShortName() . ' => ' . $method->name);

					$parameters = [];
					foreach ($method->getParameters() as $param) {
						if (isset($args[$param->name])) {
							$parameters[$param->name] = $args[$param->name];
						}
					}

					$method->invokeArgs($this->collections[$collection], $parameters);
					$this->printTime($method->name . ' done');
					return;
				}
			}
		}
		throw new InvalidArgumentException;
	}

	/**
	 * Vypise cas a text
	 * @param string $text
	 */
	private function printTime(string $text): void
	{
		$line = '[' . date('d.m.Y H:i:s', time()) . '] ' . $text;
		$this->printLine($line);
	}

	/**
	 * Vypise napovedu
	 * @param ClassType $class
	 */
	private function help(ClassType $class = null): void
	{
		if ($class === null) {
			foreach ($this->collections as $collection) {
				$this->printHelp(new ClassType($collection));
			}
		} else {
			$this->printHelp($class);
		}
	}

	/**
	 * Vypise napovedu pro danou tridu
	 * @param ClassType $class
	 */
	private function printHelp(ClassType $class): void
	{
		if ($this->isConsole) {
			$this->printConsoleHelp($class);
		} else {
			$this->printHtmlHelp($class);
		}
	}

	/**
	 * Vypise napovedu pro danou tridu v konzoli
	 * @param ClassType $class
	 */
	private function printConsoleHelp(ClassType $class): void
	{
		$this->printLine($class->getDescription());
		$this->printLine();

		foreach ($this->getMethod($class) as $method) {
			$line = $class->getShortName() . ':' . $method->name;

			foreach ($method->getParameters() as $param) {
				$line .= ' /' . $param->getName();
				if ($param->isDefaultValueAvailable()) {
					$line .= '=' . $this->getValue($param->getDefaultValue());
				}
			}
			$description = $method->getDescription();
			if (!empty($description)) {
				$line .= "\t\t(" . Strings::replace($description, '/\ +/', ' ') . ')';
			}
			$this->printLine($line);
		}
		$this->printLine();
	}

	/**
	 * Vypise napovedu pro danou tridu v HTML
	 * @param ClassType $class
	 */
	private function printHtmlHelp(ClassType $class): void
	{
		$desc = Html::el('h1');
		$desc->setText($class->getDescription());
		$this->printLine((string) $desc);

		foreach ($this->getMethod($class) as $method) {
			$desc = Html::el('pre');
			$desc->setStyle('margin-bottom: 0px');
			$desc->setText(Strings::replace($method->getDocComment(), '/(\ |\t)+/', ' '));

			$el = Html::el('a');
			$el->setHtml($method->name);

			$args = '';
			$params = [];
			foreach ($method->getParameters() as $param) {
				$p = $param->getName();
				if ($param->isDefaultValueAvailable()) {
					$value = $param->getDefaultValue();
					$p .= '=' . $this->getValue($value);
				} else {
					$args .= (empty($args) ? '?' : '&') . $param->getName() . '=';
				}
				$params[] = $p;
			}

			$link = Strings::lower(str_replace(':', '/', $this->prefix . '/' . $class->getShortName()) . '/' . $method->name);
			$el->href('/' . $link . $args);

			$line = $desc . $el;
			if (!empty($params)) {
				$line .= ' (' . implode(', ', $params) . ')';
			}
			$this->printLine($line);
		}
	}

	/**
	 * @param mixed $value
	 * @return string
	 */
	private function getValue($value): string
	{
		switch ($value) {
			default:
				return $value;
			case null:
				return 'null';
			case true:
				return '1';
			case false:
				return '0';
		}
	}

	/**
	 * @param ClassType $class
	 * @return Method[]
	 */
	private function getMethod(ClassType $class): array
	{
		$methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC & ~\ReflectionMethod::IS_PROTECTED);
		$result = [];
		foreach ($methods as $method) {
			if (Strings::startsWith($method->name, '__') ||
				$method->name === 'setConsole'
			) {
				continue;
			}
			$result[] = $method;
		}
		return $result;
	}

	/**
	 * Vypise retezec na jeden radek
	 * @param string $string
	 */
	public function printLine(string $string = null): void
	{
		if ($string !== null) {
			echo $string;
		}
		if ($this->isConsole) {
			echo "\n";
		} else {
			echo '<br/>';
		}
	}
}


<?php
/**
 * Created by Maxim Omelchenko <omelchenko@samsonos.com>
 * on 31.03.2015 at 19:31
 */

namespace samsoncms\input\wysiwyg;

/**
 * SamsonCMS WYSIWYG input module
 * @author Maxim Omelchenko <omelchenko@samsonos.com>
 */
class Application extends \samsoncms\input\Application
{
    /** @var int Field type number */
    public static $type = 8;

    /** @var string SamsonCMS field class */
    protected $fieldClass = '\samsoncms\input\wysiwyg\WYSIWYG';

    public function init(array $params = array())
    {
        \samsonphp\event\Event::subscribe('samson.cms.input.table.render', array($this, 'renderForTable'));
    }

    /**
     * Function to upload images into WYSIWYG
     *
     * @return array Asynchronous result
     */
    public function __async_upload()
    {
        /** @var array $result Asynchronous result array */
        $result = array('status' => false);
        /** @var \samsonphp\upload\Upload $upload  Pointer to uploader object */
        $upload = null;
        // If file was uploaded
        if (uploadFile($upload)) {
            $result['status'] = true;
            $result['tag'] = 'fullPath() . '">';
        }
        // Return result
        return $result;
    }

    /**
     * Change view of wysiwyg for changing dysplaying of field on table row
     */
    public function renderForTable($input)
    {
        // If there is right field then call renderer of this field
        if ($input instanceof Application) {

            $input->field->setDefautlView('indexTable');
        }
    }

	 /**
     * The function is intended for cleaning html code
     * @return array
     */

    public function __async_clearHtml()
    {
        // Tags that do not change
        $allowed_tags = '

';
        // Getting html value
        $html = json_decode(file_get_contents('php://input'), true);
        // Replace tags class
        $html = strip_tags($html['html'], $allowed_tags);
        // Replace tags class
        $html = preg_replace("/<([^>]*)(class)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags lang
        $html = preg_replace("/<([^>]*)(lang)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags style
        $html = preg_replace("/<([^>]*)(style)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags size
        $html = preg_replace("/<([^>]*)(size)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace all transfers and
        $html = str_replace(array("\r\n", "\r", "\n", ' '), ' ', $html);
        // Replace empty tags p and b
        $html = str_replace(array("

", "

", " ", ""), '', $html);
        // Added border to table
        $html = str_replace(array(" $html);
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\Loader;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\Kernel;
use \CarteBlanche\Interfaces\DependencyLoaderInterface;

/**
 * @author  Piero Wbmstr <me@e-piwi.fr>
 */
class EntityManagerLoader implements DependencyLoaderInterface
{

    /**
     * Instance loader
     *
     * @param   array                       $config
     * @param   \CarteBlanche\App\Container $container
     * @return  object
     */
    public function load(array $config = null, \CarteBlanche\App\Container $container)
    {
        $em_name = isset($config['name']) ? $config['name'] : 'default';
       $em_fullname = $em_name.'_entity_manager';

        $existing = $container->get($em_fullname);
        if (!empty($existing)) {
            return $existing;
        }
        return $this->_buildEntityManager($em_fullname);
    }

    /**
     * Build a specific entity manager
     *
     * @param   string  $em_fullname    The name of the entity manager to build
     * @return  object  Returns an object to manage the entity
     * @throws  \RuntimeException if no classname is defined in the EM config
     */
    protected function _buildEntityManager($em_fullname)
    {
        $em_cfg = CarteBlanche::getConfig($em_fullname);

        if (isset($em_cfg['class'])) {
            $em_class = $em_cfg['class'];
        } else {
            throw new \RuntimeException(
                sprintf('An entity manager configuration must define a class name ("%s")!', $em_fullname)
            );
        }

        $em_options = array();
        if (isset($em_cfg['options'])) {
            $em_options = $em_cfg['options'];
    /*
        } else {
            throw new \RuntimeException(
                sprintf('An entity manager configuration must define an options array ("%s")!', $em_fullname)
            );
    */
        }

        if (!empty($em_class)) {
            $factory = \Library\Factory::create()
                ->factoryName('EntityManager')
                ->mustImplement(Kernel::ENTITY_MANAGER_INTERFACE)
                ;
            return $factory->build($em_class, $em_options);
        }
        return null;
    }

}

// Endfile


<?php
/**
 * JsonAttributeBehavior class file.
 * @author Christoffer Niska <christoffer.niska@gmail.com>
 * @copyright Copyright © Christoffer Niska 2013-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package crisu83.yii-arbehaviors.behaviors
 */

/**
 * Active record behavior for handling JSON attributes.
 * @property CActiveRecord $owner
 */
class JsonAttributeBehavior extends CActiveRecordBehavior
{
    /**
     * @var array attributes that should be treated as JSON attributes.
     */
    public $attributes = array();

    /**
     * Actions to take before saving the owner of this behavior.
     * @param CModelEvent $event event parameter.
     */
    public function beforeSave($event)
    {
        foreach ($this->attributes as $name) {
            if (!empty($this->owner->$name)) {
                $this->owner->$name = $this->jsonEncodeAttribute($name);
            } else {
                $this->owner->$name = null;
            }
        }
    }

    /**
     * Actions to take after loading the owner of this behavior.
     * @param CEvent $event event parameter.
     */
    public function afterFind($event)
    {
        foreach ($this->attributes as $name) {
            $this->owner->$name = $this->jsonDecodeAttribute($name);
        }
    }

    /**
     * JSON encodes the given attribute on the owner of this behavior
     * @param string $name name of the attribute
     * @param int $options option bitmask.
     * @return string the encoded value.
     */
    public function jsonEncodeAttribute($name, $options = 0)
    {
        return json_encode($this->owner->$name, $options);
    }

    /**
     * JSON decodes the given attribute on the owner of this behavior.
     * @param string $name name of the attribute.
     * @param bool $assoc whether the result should be an associated array (default to true).
     * @param int $depth recursion depth.
     * @return string the decoded value.
     * @throws CException if the value cannot be decoded.
     */
    public function jsonDecodeAttribute($name, $assoc = true, $depth = 512)
    {
        $string = json_decode($this->owner->$name, $assoc, $depth);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new CException(sprintf('Failed to decode JSON attribute "%s".', $name));
        }
        return $string;
    }
}


<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * 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@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Boolean.php 24593 2012-01-05 20:35:02Z matthew $
 */

/**
 * @see Zend_Filter_Interface
 */

/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Boolean implements Zend_Filter_Interface
{
    const BOOLEAN      = 1;
    const INTEGER      = 2;
    const FLOAT        = 4;
    const STRING       = 8;
    const ZERO         = 16;
    const EMPTY_ARRAY  = 32;
    const NULL         = 64;
    const PHP          = 127;
    const FALSE_STRING = 128;
    const YES          = 256;
    const ALL          = 511;

    protected $_constants = array(
        self::BOOLEAN      => 'boolean',
        self::INTEGER      => 'integer',
        self::FLOAT        => 'float',
        self::STRING       => 'string',
        self::ZERO         => 'zero',
        self::EMPTY_ARRAY  => 'array',
        self::NULL         => 'null',
        self::PHP          => 'php',
        self::FALSE_STRING => 'false',
        self::YES          => 'yes',
        self::ALL          => 'all',
    );

    /**
     * Internal type to detect
     *
     * @var integer
     */
    protected $_type = self::PHP;

    /**
     * Internal locale
     *
     * @var array
     */
    protected $_locale = array('auto');

    /**
     * Internal mode
     *
     * @var boolean
     */
    protected $_casting = true;

    /**
     * Constructor
     *
     * @param string|array|Zend_Config $options OPTIONAL
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        } elseif (!is_array($options)) {
            $options = func_get_args();
            $temp    = array();
            if (!empty($options)) {
                $temp['type'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['casting'] = array_shift($options);
            }

            if (!empty($options)) {
                $temp['locale'] = array_shift($options);
            }

            $options = $temp;
        }

        if (array_key_exists('type', $options)) {
            $this->setType($options['type']);
        }

        if (array_key_exists('casting', $options)) {
            $this->setCasting($options['casting']);
        }

        if (array_key_exists('locale', $options)) {
            $this->setLocale($options['locale']);
        }
    }

    /**
     * Returns the set null types
     *
     * @return int
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * Set the null types
     *
     * @param  integer|array $type
     * @throws Zend_Filter_Exception
     * @return Zend_Filter_Boolean
     */
    public function setType($type = null)
    {
        if (is_array($type)) {
            $detected = 0;
            foreach($type as $value) {
                if (is_int($value)) {
                    $detected += $value;
                } elseif (in_array($value, $this->_constants)) {
                    $detected += array_search($value, $this->_constants);
                }
            }

            $type = $detected;
        } elseif (is_string($type) && in_array($type, $this->_constants)) {
            $type = array_search($type, $this->_constants);
        }

        if (!is_int($type) || ($type < 0) || ($type > self::ALL)) {

            throw new Zend_Filter_Exception('Unknown type');
        }

        $this->_type = $type;
        return $this;
    }

    /**
     * Returns the set locale
     *
     * @return array
     */
    public function getLocale()
    {
        return $this->_locale;
    }

    /**
     * Set the locales which are accepted
     *
     * @param  string|array|Zend_Locale $locale
     * @throws Zend_Filter_Exception
     * @return Zend_Filter_Boolean
     */
    public function setLocale($locale = null)
    {
        if (is_string($locale)) {
            $locale = array($locale);
        } elseif ($locale instanceof Zend_Locale) {
            $locale = array($locale->toString());
        } elseif (!is_array($locale)) {

            throw new Zend_Filter_Exception('Locale has to be string, array or an instance of Zend_Locale');
        }

        foreach ($locale as $single) {
            if (!Zend_Locale::isLocale($single)) {

                throw new Zend_Filter_Exception("Unknown locale '$single'");
            }
        }

        $this->_locale = $locale;
        return $this;
    }

    /**
     * Returns the casting option
     *
     * @return boolean
     */
    public function getCasting()
    {
        return $this->_casting;
    }

    /**
     * Set the working mode
     *
     * @param  boolean $locale When true this filter works like cast
     *                         When false it recognises only true and false
     *                         and all other values are returned as is
     * @throws Zend_Filter_Exception
     * @return Zend_Filter_Boolean
     */
    public function setCasting($casting = true)
    {
        $this->_casting = (boolean) $casting;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns a boolean representation of $value
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        $type    = $this->getType();
        $casting = $this->getCasting();

        // STRING YES (Localized)
        if ($type >= self::YES) {
            $type -= self::YES;
            if (is_string($value)) {

                $locales = $this->getLocale();
                foreach ($locales as $locale) {
                    if ($this->_getLocalizedQuestion($value, false, $locale) === false) {
                        return false;
                    }

                    if (!$casting && ($this->_getLocalizedQuestion($value, true, $locale) === true)) {
                        return true;
                    }
                }
            }
        }

        // STRING FALSE ('false')
        if ($type >= self::FALSE_STRING) {
            $type -= self::FALSE_STRING;
            if (is_string($value) && (strtolower($value) == 'false')) {
                return false;
            }

            if ((!$casting) && is_string($value) && (strtolower($value) == 'true')) {
                return true;
            }
        }

        // NULL (null)
        if ($type >= self::NULL) {
            $type -= self::NULL;
            if ($value === null) {
                return false;
            }
        }

        // EMPTY_ARRAY (array())
        if ($type >= self::EMPTY_ARRAY) {
            $type -= self::EMPTY_ARRAY;
            if (is_array($value) && ($value == array())) {
                return false;
            }
        }

        // ZERO ('0')
        if ($type >= self::ZERO) {
            $type -= self::ZERO;
            if (is_string($value) && ($value == '0')) {
                return false;
            }

            if ((!$casting) && (is_string($value)) && ($value == '1')) {
                return true;
            }
        }

        // STRING ('')
        if ($type >= self::STRING) {
            $type -= self::STRING;
            if (is_string($value) && ($value == '')) {
                return false;
            }
        }

        // FLOAT (0.0)
        if ($type >= self::FLOAT) {
            $type -= self::FLOAT;
            if (is_float($value) && ($value == 0.0)) {
                return false;
            }

            if ((!$casting) && is_float($value) && ($value == 1.0)) {
                return true;
            }
        }

        // INTEGER (0)
        if ($type >= self::INTEGER) {
            $type -= self::INTEGER;
            if (is_int($value) && ($value == 0)) {
                return false;
            }

            if ((!$casting) && is_int($value) && ($value == 1)) {
                return true;
            }
        }

        // BOOLEAN (false)
        if ($type >= self::BOOLEAN) {
            $type -= self::BOOLEAN;
            if (is_bool($value)) {
                return $value;
            }
        }

        if ($casting) {
            return true;
        }

        return $value;
    }

    /**
     * Determine the value of a localized string, and compare it to a given value
     *
     * @param  string $value
     * @param  boolean $yes
     * @param  array $locale
     * @return boolean
     */
    protected function _getLocalizedQuestion($value, $yes, $locale)
    {
        if ($yes == true) {
            $question = 'yes';
            $return   = true;
        } else {
            $question = 'no';
            $return   = false;
        }
        $str = Zend_Locale::getTranslation($question, 'question', $locale);
        $str = explode(':', $str);
        if (!empty($str)) {
            foreach($str as $no) {
                if (($no == $value) || (strtolower($no) == strtolower($value))) {
                    return $return;
                }
            }
        }
    }
}


<?php
/**
 * This file is part of the CarteBlanche PHP framework.
 *
 * (c) Pierre Cassat <me@e-piwi.fr> and contributors
 *
 * License Apache-2.0 <http://github.com/php-carteblanche/carteblanche/blob/master/LICENSE>
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CarteBlanche\App;

use \CarteBlanche\CarteBlanche;
use \CarteBlanche\App\Loader;
use \CarteBlanche\App\Locator;
use \CarteBlanche\Exception\ErrorException;
use \Library\Helper\Directory as DirectoryHelper;

/**
 * The global bundle object
 *
 * @author      Piero Wbmstr <me@e-piwi.fr>
 */
class Bundle
{

    protected $shortname;
    protected $namespace;
    protected $directory;
    protected $instance;
    protected $package_name;
    protected $package_data;

    /**
     * Construction of a bundle
     *
     * @param   string  $namespace  The bundle's namespace
     * @param   string  $directory  The bundle's directory in `$bundles_dir`
     * @throws  \CarteBlanche\Exception\ErrorException if the `$bundles_dir` doesn't exist
     * @throws  \CarteBlanche\Exception\ErrorException if the current loaded bundle directory doesn't exist
     */
    public function __construct($namespace, $directory)
    {
        $bundles_dir = CarteBlanche::getFullPath('bundles_dir');
        if (!Locator::locate($bundles_dir)) {
            throw new ErrorException("Bundles directory does not exist!");
        }
        if ($d = Locator::locate($bundles_dir.$directory)) {
            $this->directory = $d;
        } else {
            throw new ErrorException(sprintf("Bundle directory '%s' does not exist!", $directory));
        }
        $this->namespace = $namespace;
        $this->shortname = substr($directory, 0, strpos($directory, '/'));
        $this->package_name = 'carte-blanche/bundle-'.strtolower($namespace);
        $assets = CarteBlanche::getContainer()->get('template_engine')
            ->getAssetsLoader()
            ->getAssets();
        if (!empty($assets) && isset($assets[$this->package_name])) {
            $this->package_data = $assets[$this->package_name];
        }

        $this->init();
    }

    /**
     * Initialize a bundle : register its namespace and load its global `[bundle name]Bundle` file
     */
    protected function init()
    {
        $_bundle_fname = $this->getNamespace().'Bundle';
        $_bundle_f = DirectoryHelper::slashDirname($this->getDirectory()).$_bundle_fname;
        if (@file_exists($_bundle_f.'.php')) {
            $cls_name = '\\'.$this->getNamespace().'\\'.$_bundle_fname;
            $this->instance = new $cls_name;
        } else {
            $_bundle_fname = $this->getNamespace().'Bundle';
            $_bundle_f = DirectoryHelper::slashDirname($this->getDirectory())
                . DirectoryHelper::slashDirname($this->getNamespace())
                . $_bundle_fname;
            if (@file_exists($_bundle_f.'.php')) {
                $cls_name = '\\'.$this->getNamespace().'\\'.$_bundle_fname;
                $this->instance = new $cls_name;
                if (method_exists($this->instance, 'setName')) {
//echo "> calling 'setName' on instance of ".get_class($this->instance).PHP_EOL;
                    call_user_func(array($this->instance, 'setName'), $this->getNamespace());
                }
                if (method_exists($this->instance, 'setPackageName')) {
//echo "> calling 'setPackageName' on instance of ".get_class($this->instance).PHP_EOL;
                    call_user_func(array($this->instance, 'setPackageName'), $this->getPackageName());
                }
                if (method_exists($this->instance, 'init')) {
//echo "> calling 'init' on instance of ".get_class($this->instance).PHP_EOL;
                    call_user_func(array($this->instance, 'init'), $this->getPackageData());
                }
            }
        }
    }

    /**
     * Get bundle's directory
     */
    public function getDirectory()
    {
        return $this->directory;
    }

    /**
     * Get bundle's namespace
     */
    public function getNamespace()
    {
        return $this->namespace;
    }

    /**
     * Get bundle's short name
     */
    public function getShortname()
    {
        return $this->shortname;
    }

    /**
     * Get bundle's package name
     */
    public function getPackageName()
    {
        return $this->package_name;
    }

    /**
     * Get bundle's package's JSON data
     */
    public function getPackageData()
    {
        return $this->package_data;
    }

    /**
     * Get bundle's loader instance
     */
    public function getInstance()
    {
        return $this->instance;
    }

}

// Endfile