<?php

/**
 * Copyright (c) 2010-2016 Romain Cottard
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eureka\Component\Mcrypt;

/**
 * Mcrypt lib class. Based on Mcrypt native php functions
 * Exception code range: [1500-1599]
 *
 * @author  Romain Cottard
 */
class Mcrypt
{
    /**
     * @var integer MODE_CBC Cipher Block Chaining mode
     */
    const MODE_CBC = 1;

    /**
     * @var integer CIPHER_BLOWFISH Cipher name
     */
    const CIPHER_BLOWFISH = 1;

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

    /**
     * @var string $mode Encryption mode.
     */
    private $mode = '';

    /**
     * @var string $cipher Encryption cipher.
     */
    private $cipher = '';

    /**
     * @var string $iv IV for encryption
     */
    private $iv = null;

    /**
     * mcrypt constructor.
     *
     * @param int $cipher
     * @param int $mode
     */
    public function __construct($cipher = self::CIPHER_BLOWFISH, $mode = self::MODE_CBC)
    {
        $this->setCipher($cipher);
        $this->setMode($mode);
        $this->generateIV();
    }

    /**
     * Set encryption key
     *
     * @param  string $key
     * @return self
     * @throws \InvalidArgumentException
     */
    public function setKey($key)
    {
        if (empty($key)) {
            throw new \InvalidArgumentException('Key cannot be empty !', 1500);
        }

        $this->key = $key;

        return $this;
    }

    /**
     * Return the IV.
     *
     * @return string
     */
    public function getIV()
    {
        return $this->iv;
    }

    /**
     * Set encryption iv
     *
     * @param  string $iv
     * @return self
     * @throws \InvalidArgumentException
     */
    public function setIV($iv)
    {
        if (empty($iv)) {
            throw new \InvalidArgumentException('IV cannot be empty !', 1501);
        }

        $this->iv = $iv;

        return $this;
    }

    /**
     * Get Size for the IV (0: not used by the cipher/mode)
     *
     * @return int
     */
    public function getSizeIV()
    {
        return mcrypt_get_iv_size($this->cipher, $this->mode);
    }

    /**
     * Encrypt the data string
     *
     * @param  string $data
     * @return string
     */
    public function encrypt($data)
    {
        if ($this->iv === null) {
            $dataEncrypted = mcrypt_encrypt($this->cipher, $this->key, $data, $this->mode);
        } else {
            $dataEncrypted = mcrypt_encrypt($this->cipher, $this->key, $data, $this->mode, $this->iv);
        }

        return bin2hex($dataEncrypted);
    }

    /**
     * Decrypt the data string
     *
     * @param  string $data
     * @return mixed
     * @throws \InvalidArgumentException
     */
    public function decrypt($data)
    {
        if (!is_string($data) || !preg_match('/^[0-9A-Fa-f]*$/', $data)) {
            throw new \InvalidArgumentException('blowfishDecryptCBC require hex input', 1502);
        }

        $data = pack('H*', $data);

        if ($this->iv === null) {
            $return = mcrypt_decrypt($this->cipher, $this->key, $data, $this->mode);
        } else {
            $return = mcrypt_decrypt($this->cipher, $this->key, $data, $this->mode, $this->iv);
        }

        return rtrim($return, "\0");
    }

    /**
     * Set cipher
     *
     * @param  int $cipher
     * @return self
     * @throws \DomainException
     */
    protected function setCipher($cipher)
    {
        switch ($cipher) {
            case static::CIPHER_BLOWFISH:
                $this->cipher = MCRYPT_BLOWFISH;
                break;
            default:
                throw new \DomainException('Unsupported cipher method !', 1503);
        }

        return $this;
    }

    /**
     * Set mode
     *
     * @param  int $mode
     * @return self
     * @throws \DomainException
     */
    protected function setMode($mode)
    {
        switch ($mode) {
            case static::MODE_CBC:
                $this->mode = MCRYPT_MODE_CBC;
                break;
            default:
                throw new \DomainException('Unsupported encryption method !', 1504);
        }

        return $this;
    }

    /**
     * Generate random IV & set it as property
     *
     * @return self
     */
    protected function generateIV()
    {
        $sizeIV = $this->getSizeIV();

        if ($sizeIV === 0) {
            return $this;
        }

        $this->setIV(mcrypt_create_iv($sizeIV, MCRYPT_RAND));

        return $this;
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\models;

use cascade\components\dataInterface\Status;
use canis\caching\Cacher;
use canis\helpers\Date;
use canis\helpers\StringHelper;
use yii\helpers\Url;

/**
 * DataInterfaceLog is the model class for table "data_interface_log".
 *
 * @property string $id
 * @property string $data_interface_id
 * @property string $status
 * @property string $message
 * @property integer $peak_memory
 * @property string $started
 * @property string $ended
 * @property string $created
 * @property string $modified
 * @property DataInterface $dataInterface
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DataInterfaceLog extends \cascade\components\db\ActiveRecord
{
    /**
     * @var [[@doctodo var_type:_statusLog]] [[@doctodo var_description:_statusLog]]
     */
    protected $_statusLog;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->on(self::EVENT_BEFORE_VALIDATE, [$this, 'updateLastUpdated']);
        $this->on(self::EVENT_BEFORE_VALIDATE, [$this, 'updatePeakMemory']);
        $this->on(self::EVENT_BEFORE_VALIDATE, [$this, 'serializeStatusLog']);
    }

    /**
     * @inheritdoc
     */
    public static function isAccessControlled()
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'data_interface_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['data_interface_id'], 'required'],
            [['message'], 'string'],
            [['peak_memory'], 'integer'],
            [['started', 'ended', 'created', 'modified', 'last_update'], 'safe'],
            [['data_interface_id'], 'string', 'max' => 36],
            [['status'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'data_interface_id' => 'Data Interface ID',
            'status' => 'Status',
            'message' => 'Message',
            'peak_memory' => 'Peak Memory',
            'started' => 'Started',
            'ended' => 'Ended',
        ];
    }

    /**
     * Get data interface.
     *
     * @return \yii\db\ActiveRelation
     */
    public function getDataInterface()
    {
        return $this->hasOne(DataInterface::className(), ['id' => 'data_interface_id']);
    }

    /**
     * [[@doctodo method_description:run]].
     *
     * @param [[@doctodo param_type:interactiveAction]] $interactiveAction [[@doctodo param_description:interactiveAction]] [optional]
     *
     * @return [[@doctodo return_type:run]] [[@doctodo return_description:run]]
     */
    public function run($interactiveAction = null)
    {
        if (empty($this->dataInterface) || !($dataInterfaceItem = $this->dataInterface->dataInterfaceItem)) {
            return false;
        }

        return $dataInterfaceItem->run($this, $interactiveAction);
    }

    /**
     * Get status log.
     *
     * @param boolean $checkRecent [[@doctodo param_description:checkRecent]] [optional]
     *
     * @return [[@doctodo return_type:getStatusLog]] [[@doctodo return_description:getStatusLog]]
     */
    public function getStatusLog($checkRecent = false)
    {
        if (!isset($this->_statusLog)) {
            $this->_statusLog = Cacher::get([get_called_class(), $this->primaryKey, $this->created]);
            if (empty($this->_statusLog)) {
                if (is_null($this->message)) {
                    $this->_statusLog = $this->_startStatus();
                } else {
                    $this->_statusLog = unserialize($this->message);
                }
            } elseif ($checkRecent) {
                $testStatusLog = unserialize($this->message);
                if ($testStatusLog && $testStatusLog->lastUpdate > $this->_statusLog->lastUpdate) {
                    $this->_statusLog = $testStatusLog;
                }
            }
            if (empty($this->_statusLog)) {
                $this->_statusLog = new Status();
            }
        }
        $this->_statusLog->log = $this;

        return $this->_statusLog;
    }

    /**
     * [[@doctodo method_description:saveCache]].
     */
    public function saveCache()
    {
        $this->statusLog->lastUpdate = microtime(true);
        Cacher::set([get_called_class(), $this->primaryKey, $this->created], $this->statusLog, 3600);
    }

    /**
     * [[@doctodo method_description:serializeStatusLog]].
     */
    public function serializeStatusLog()
    {
        $this->statusLog->lastUpdate = microtime(true);
        $this->message = serialize($this->statusLog);
    }

    /**
     * [[@doctodo method_description:updateStatus]].
     *
     * @param [[@doctodo param_type:newStatus]] $newStatus [[@doctodo param_description:newStatus]]
     *
     * @return [[@doctodo return_type:updateStatus]] [[@doctodo return_description:updateStatus]]
     */
    public function updateStatus($newStatus)
    {
        $this->status = $newStatus;

        return $this->save();
    }

    /**
     * [[@doctodo method_description:_startStatus]].
     *
     * @return [[@doctodo return_type:_startStatus]] [[@doctodo return_description:_startStatus]]
     */
    protected function _startStatus()
    {
        $status = new Status($this);

        return $status;
    }

    /**
     * [[@doctodo method_description:start]].
     *
     * @return [[@doctodo return_type:start]] [[@doctodo return_description:start]]
     */
    public function start()
    {
        Cacher::set([get_called_class(), $this->primaryKey, $this->created], false);

        return $this->save();
    }

    /**
     * [[@doctodo method_description:updatePeakMemory]].
     */
    public function updatePeakMemory()
    {
        if (is_null($this->peak_memory)
            || (int) $this->peak_memory < memory_get_peak_usage()) {
            $this->peak_memory = memory_get_peak_usage();
        }
    }

    /**
     * [[@doctodo method_description:updateLastUpdated]].
     */
    public function updateLastUpdated()
    {
        $this->last_update = date("Y-m-d G:i:s");
    }

    /**
     * [[@doctodo method_description:clearStatusLogCache]].
     */
    public function clearStatusLogCache()
    {
        Cacher::set([get_called_class(), $this->primaryKey, $this->created], false, 3600);
    }

    /**
     * [[@doctodo method_description:end]].
     *
     * @param boolean $endInterrupted [[@doctodo param_description:endInterrupted]] [optional]
     * @param boolean $saveAlways     [[@doctodo param_description:saveAlways]] [optional]
     *
     * @return [[@doctodo return_type:end]] [[@doctodo return_description:end]]
     */
    public function end($endInterrupted = false, $saveAlways = true)
    {
        $this->getStatusLog(true);
        if (!is_null($this->ended)) {
            if ($saveAlways) {
                $this->save();
            }

            return true;
        }
        if ($endInterrupted) {
            $lerror = error_get_last();
            if (!empty($lerror)) {
                $this->statusLog->addError("{$lerror['file']}:{$lerror['line']} {$lerror['message']}");
            }
            $this->status = 'interrupted';
        } elseif ($this->statusLog->hasError) {
            $this->status = 'failed';
        } else {
            $this->status = 'success';
        }
        $this->ended = date("Y-m-d G:i:s");

        return $this->save();
    }

    /**
     * Get estimate time remaining.
     *
     * @return [[@doctodo return_type:getEstimateTimeRemaining]] [[@doctodo return_description:getEstimateTimeRemaining]]
     */
    public function getEstimateTimeRemaining()
    {
        $estimatedDuration = $this->dataInterface->estimateDuration();
        if ($estimatedDuration) {
            $startedTime = strtotime($this->started);
            $estimatedEndTime = $startedTime + $estimatedDuration;
            if (time() > $estimatedEndTime) {
                return false;
            }

            return $estimatedEndTime - time();
        }

        return false;
    }

    /**
     * Get duration.
     *
     * @return [[@doctodo return_type:getDuration]] [[@doctodo return_description:getDuration]]
     */
    public function getDuration()
    {
        $ended = microtime(true);
        if ($this->ended) {
            $ended = strtotime($this->ended);
        }
        $started = strtotime($this->started);

        return Date::niceDuration($ended-$started);
    }

    /**
     * Get is most recent.
     *
     * @return [[@doctodo return_type:getIsMostRecent]] [[@doctodo return_description:getIsMostRecent]]
     */
    public function getIsMostRecent()
    {
        return !empty($this->dataInterface) && $this->dataInterface->lastDataInterfaceLog && $this->dataInterface->lastDataInterfaceLog->primaryKey === $this->primaryKey;
    }

    /**
     * Get data package.
     *
     * @return [[@doctodo return_type:getDataPackage]] [[@doctodo return_description:getDataPackage]]
     */
    public function getDataPackage()
    {
        $p = [];
        $p['_'] = [];
        $p['_']['url'] = Url::to(['admin/interface/view-log', 'id' => $this->id, 'package' => 1]);
        $p['_']['id'] = $this->id;
        $p['_']['started'] = isset($this->started) ? date("F d, Y g:i:sa", strtotime($this->started)) : false;
        $p['_']['ended'] = isset($this->ended) ? date("F d, Y g:i:sa", strtotime($this->ended)) : false;
        $p['_']['duration'] = $this->duration;
        $p['_']['status'] = $this->status;
        if ($this->status === 'running' && $this->statusLog->paused) {
            $p['_']['status'] = 'paused';
        }
        $p['_']['estimatedTimeRemaining'] = Date::niceDuration($this->estimateTimeRemaining);
        $p['_']['log_status'] = 'fine';

        $p['_']['menu'] = [];
        $isMostRecent = $this->isMostRecent;
        if ($isMostRecent) {
            if ($this->status === 'success' && !$this->statusLog->cleaned) {
            } elseif ($this->status !== 'running') {
                $p['_']['menu'][] = ['label' => 'Run Again', 'url' => Url::to(['admin/interface/run', 'id' => $this->data_interface_id]), 'attributes' => ['data-handler' => 'background'], 'class' => 'btn-warning'];
            }
        }

        if ($this->statusLog->hasError) {
            $p['_']['log_status'] = 'error';
        } elseif ($this->statusLog->hasWarning) {
            $p['_']['log_status'] = 'warning';
        }
        $p['_']['last_update'] = $this->last_update;
        $p['_']['peak_memory'] = StringHelper::humanFilesize($this->statusLog->peakMemoryUsage);
        $p['progress'] = [
            'total' => $this->statusLog->progressTotal,
            'done' => $this->statusLog->progressDone,
        ];
        if (isset($this->statusLog->ended)) {
            $p['progress']['duration'] = Date::shortDuration($this->statusLog->ended - $this->statusLog->started);
        }
        $p['tasks'] = [];
        foreach ($this->statusLog->tasks as $id => $task) {
            $p['tasks'][$id] = $task->package;
        }
        $p['messages'] = [];
        $lasttime = $started = $this->statusLog->started;
        foreach ($this->statusLog->messages as $key => $message) {
            $key = $key . '-' . substr(md5($key), 0, 5);
            $timestamp = (float) $message['time'];
            $duration = $timestamp - $lasttime;
            $lasttime = $timestamp;
            $fromStart = $timestamp-$started;
            $p['messages'][$key] = [
                'message' => $message['message'],
                'duration' => Date::shortDuration($duration),
                'fromStart' => Date::shortDuration($fromStart),
                'level' => $message['level'],
                'data' => $message['data'],
                'memory' => StringHelper::humanFilesize($message['memory']),
            ];
        }
        $p['output'] = $this->statusLog->commandOutput;

        return $p;
    }

    /**
     * Get is active.
     *
     * @return [[@doctodo return_type:getIsActive]] [[@doctodo return_description:getIsActive]]
     */
    public function getIsActive()
    {
        return in_array($this->status, ['queued', 'running']);
    }

    /**
     * Get bootstrap state.
     *
     * @return [[@doctodo return_type:getBootstrapState]] [[@doctodo return_description:getBootstrapState]]
     */
    public function getBootstrapState()
    {
        switch ($this->status) {
          case 'success':
            return 'success';
          break;
          case 'queued':
          case 'running':
            return 'info';
          break;
          case 'error':
          case 'interrupted':
            return 'danger';
          break;
        }

        return 'warning';
    }
}


<?php

/**
 * Web2All Table ObjectBaseList class
 *
 * This class manages a basic list of Web2All_Table_Object's
 * (or an extension off). It makes use of special hooks exposed
 * in the Object.
 * This class is extended by Web2All_Table_ObjectList and Web2All_Table_ObjectIterator
 *
 *
 * @author Hans Oostendorp
 * @copyright (c) Copyright 2010 Web2All BV
 * @since 2010-04-08
 */
class Web2All_Table_ObjectBaseList extends Web2All_Manager_Plugin {

  /**
   * the object of which to generate a list
   *
   * @var Web2All_Table_IListableObject
   */
  protected $search_obj;

  protected $classname;

  protected $extra;

  protected $limit;

  protected $offset;

  /**
   * Database connection
   *
   * @var ADOConnection
   */
  protected $db;

  /**
   * Recordset with results of DB
   *
   * @var ADORecordSet
   */
  protected $recordSet;

  /**
   * constructor
   * NOTE: Web2All_Table_Object $obj has to implement Web2All_Table_IListableObject
   *
   * @param Web2All_Manager_Main $web2all
   * @param Web2All_Table_Object $obj
   */
  public function __construct(Web2All_Manager_Main $web2all,$obj) {
    parent::__construct($web2all);

    $table_listableobject_interface='Web2All_Table_IListableObject';
    if (!($obj instanceof $table_listableobject_interface)) {
      throw new Exception('Web2All_Table_ObjectBaseList::constructor: requires a Web2All_Table_IListableObject as param');
    }

    $this->search_obj=$obj;

    $this->extra='';

    $this->limit=-1;

    $this->offset=-1;

    $this->db=$this->search_obj->getDB();

    $this->classname=get_class($this->search_obj);

    $this->recordSet = null;

  }

  /**
   * Assign extra sql to append to query (eg order by)
   * Do this before calling fetchData()
   *
   * @param string $extra
   */
  public function setExtra($extra)
  {
    $this->extra=$extra;
  }

  /**
   * Assign a range to fetch from the list.
   * If you do this before calling fetchData() then
   * only results from $offset to $offset+$limit
   * are returned
   *
   * @param int $limit
   * @param int $offset
   */
  public function setRange($limit,$offset)
  {
    $this->limit=$limit;
    $this->offset=$offset;
  }

  /**
   * fetch all data from the database
   *
   * NOTE: whoever extends this method, is responsible for closing the recordSet
   */
  public function fetchData()
  {
    $this->recordSet = $this->search_obj->getRecordsetFromObjectQuery($this->extra,$this->limit,$this->offset);
    // check if recordSet instanceof ADORecordSet, to prevent PHP Fatal error and create a usefull exception with backtrace
    if (!($this->recordSet instanceof ADORecordSet))
    {
      throw new Exception("Web2All_Table_ObjectBaselist->fetchData(): recordSet is not instanceof ADORecordSet",E_USER_ERROR);
    }
  }

}
?>


<?php

namespace ebussola\common\datatype;

/**
 * User: Leonardo Shinagawa
 * Date: 15/08/12
 * Time: 20:05
 *
 * @property $full_address string
 */
class Url
{

    /**
     * @var string
     * The full address
     */
    protected $full_address;

    /**
     * @var string
     * The protocol used on the address
     * http, https, ftp...
     */
    public $scheme;

    /**
     * @var string
     * eg.: www.ebussola.com
     */
    public $host;

    /**
     * @var string
     */
    public $port;

    /**
     * @var string
     */
    public $user;

    /**
     * @var string
     */
    public $pass;

    /**
     * @var string
     */
    public $path;

    /**
     * @var string
     * Fragment is the part after a # used on single-page applications or to make an anchor
     */
    public $fragment;

    /**
     * @var array
     * The query string separated by key=>value in array format
     */
    public $query;

    /**
     * @var string
     * The query string in string format
     */
    public $query_string;

    /**
     * @param String $address
     */
    public function __construct($address = null)
    {
        if ($address !== null) {
            $this->setAddress($address);
        }
    }

    /**
     * @param String $address
     */
    public function setAddress($address)
    {
        $full_address = filter_var($address, FILTER_SANITIZE_URL);
        $info = parse_url($full_address);

        $this->full_address = $full_address;

        $this->scheme = isset($info['scheme']) ? $info['scheme'] : null;
        $this->host = isset($info['host']) ? $info['host'] : null;
        $this->port = isset($info['port']) ? $info['port'] : null;
        $this->user = isset($info['user']) ? $info['user'] : null;
        $this->pass = isset($info['pass']) ? $info['pass'] : null;
        $this->path = isset($info['path']) ? $info['path'] : null;
        $queries = array();
        if (isset($info['query'])) {
            parse_str($info['query'], $queries);
            $this->query = $queries;
            $this->query_string = http_build_query($this->query);
        }
        $this->fragment = isset($info['fragment']) ? $info['fragment'] : null;
    }

    public function __get($name)
    {
        if ($name === 'full_address') {
            $this->assembleUrl();

            return $this->full_address;
        }

        return null;
    }

    /**
     * Assemble the fullAddress from the other properties
     */
    private function assembleUrl()
    {
        $address = '';
        if (!empty($this->scheme)) {
            $address .= $this->scheme . '://';
        }
        if (!empty($this->user)) {
            $address .= $this->user;
        }
        if (!empty($this->pass)) {
            $address .= ':' . $this->pass . '@';
        }
        if (!empty($this->host)) {
            $address .= $this->host;
        }
        if (!empty($this->port)) {
            $address .= ':' . $this->port;
        }
        if (!empty($this->path)) {
            $address .= $this->path;
        }
        if (count($this->query) > 0) {
            $this->query_string = http_build_query($this->query);
            $address .= '?' . $this->query_string;
        }
        if (!empty($this->fragment)) {
            $address .= '#' . $this->fragment;
        }

        $this->full_address = $address;
    }

}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Adapter;

use Dothiv\Bundle\ContentfulBundle\Exception\InvalidArgumentException;
use Dothiv\Bundle\ContentfulBundle\Exception\RuntimeException;
use Dothiv\Bundle\ContentfulBundle\Item\ContentfulAsset;
use Dothiv\Bundle\ContentfulBundle\Logger\LoggerAwareTrait;
use Dothiv\Bundle\ContentfulBundle\Repository\ContentfulAssetRepositoryInterface;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;

class FilesystemAssetAdapter implements ContentfulAssetAdapterInterface
{
    use LoggerAwareTrait;

    /**
     * @var ContentfulAssetRepositoryInterface
     */
    private $assetRepo;

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

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

    /**
     * @param string                    $webPath
     * @param string                    $localPath
     * @param ContentfulAssetRepositoryInterface $assetRepo
     */
    public function __construct($webPath, $localPath, ContentfulAssetRepositoryInterface $assetRepo)
    {
        $this->webPath   = rtrim($webPath, '/');
        $this->localPath = rtrim($localPath, '/');
        $this->assetRepo = $assetRepo;
    }

    /**
     * {@inheritdoc}
     */
    public function getRoute(ContentfulAsset $asset, $locale)
    {
        return $this->getFilename($asset, $this->webPath, $locale);
    }

    protected function getFilename(ContentfulAsset $asset, $prefix, $locale)
    {
        $extension        = $this->getExtension($asset, $locale);
        $originalFilename = $asset->file[$locale]['fileName'];
        list($name,) = explode('.', $originalFilename);
        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
        $name = preg_replace('/[^A-Za-z0-9-_]/', '', $name);
        return sprintf(
            '%s/%s/%s-%s-%s-%d.%s',
            $prefix,
            trim($asset->getSpaceId(), '/'),
            $name,
            $asset->getId(),
            $locale,
            $asset->getRevision(),
            $extension
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getLocalFile(ContentfulAsset $asset, $locale)
    {
        return new \SplFileInfo($this->getFilename($asset, $this->localPath, $locale));
    }

    /**
     * @param ContentfulAsset $asset
     * @param string          $locale
     *
     * @return string|null
     * @throws InvalidArgumentException
     */
    protected function getExtension(ContentfulAsset $asset, $locale)
    {
        $asset   = $this->assetRepo->findNewestById($asset->getSpaceId(), $asset->getId())->getOrCall(function () use ($asset) {
            throw new InvalidArgumentException(
                sprintf(
                    'Cannot find asset with id "%s" in space "%s"!',
                    $asset->getId(),
                    $asset->getSpaceId()
                )
            );
        });
        $guesser = ExtensionGuesser::getInstance();
        return $guesser->guess($asset->file[$locale]['contentType']);
    }

    /**
     * Caches the asset to the local filesystem.
     *
     * @param ContentfulAsset $asset
     *
     * @return void
     * @throws RuntimeException
     */
    public function cache(ContentfulAsset $asset)
    {
        if (!isset($asset->file)) {
            $this->log('Asset %s has no file.', $asset);
            return;
        }
        foreach ($asset->file as $locale => $file) {
            if (!$file) {
                // File not published.
                $this->log('Asset %s contains unpublished file for %s.', $asset, $locale);
                continue;
            }
            $localFile = $this->getLocalFile($asset, $locale);
            if ($localFile->isFile()) {
                continue;
            }
            $this->log(
                'Caching "%s" file for asset "%s" as "%s" ...',
                $locale,
                $asset->getId(),
                $localFile->getPathname()
            );
            $dir = new \SplFileInfo($localFile->getPath());
            if (!$dir->isWritable()) {
                throw new RuntimeException(
                    sprintf(
                        'Target directory "%s" is not writeable!',
                        $localFile->getPath()
                    )
                );
            }
            copy(str_replace('//', 'https://', $file['url']), $localFile->getPathname());
            $size = filesize($localFile->getPathname());
            $this->log(
                '%d bytes saved.',
                $size
            );
        }
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface;

use cascade\models\DataInterface;
use cascade\models\DataInterfaceLog;

/**
 * DeferredAction [[@doctodo class_description:cascade\components\dataInterface\DeferredAction]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
class DeferredAction extends \canis\deferred\components\Action
{
    use ActionTrait;

    /**
     * [[@doctodo method_description:run]].
     *
     * @return [[@doctodo return_type:run]] [[@doctodo return_description:run]]
     */
    public function run()
    {
        $logModel = $this->getLogModel(true);
        if (!$logModel) {
            $this->result->isSuccess = false;
            $this->result->message = 'Log model no longer exists';

            return false;
        }

        if (!$logModel->run($this)) {
            $this->result->isSuccess = false;
            $this->result->message = 'Interface failed to run';
            $this->cancelLog();

            return false;
        }

        $this->result->isSuccess = true;
        $this->result->message = 'Interface ran successfully';

        return true;
    }

    /**
     * @inheritdoc
     */
    public function pauseAction()
    {
        $logModel = $this->getLogModel(true);

        return $logModel->statusLog->pause();
    }

    /**
     * @inheritdoc
     */
    public function resumeAction()
    {
        $logModel = $this->getLogModel(true);

        return $logModel->statusLog->resume();
    }

    /**
     * Get descriptor.
     *
     * @return [[@doctodo return_type:getDescriptor]] [[@doctodo return_description:getDescriptor]]
     */
    public function getDescriptor()
    {
        $logModel = $this->getLogModel(true);
        if (empty($logModel) || !isset($logModel->dataInterface)) {
            return 'Unknown Data Interface';
        }

        return 'Interface: ' . $logModel->dataInterface->name;
    }

    /**
     * @inheritdoc
     */
    public function cancel()
    {
        return $this->cancelLog();
    }

    /**
     * [[@doctodo method_description:cancelLog]].
     *
     * @return [[@doctodo return_type:cancelLog]] [[@doctodo return_description:cancelLog]]
     */
    public function cancelLog()
    {
        $logModel = $this->getLogModel(true);
        if (empty($logModel)) {
            return true;
        }
        if ($logModel->status === 'queued') {
            return $logModel->delete();
        } else {
            return false;
        }
    }

    /**
     * Get log model.
     *
     * @param boolean $refresh [[@doctodo param_description:refresh]] [optional]
     *
     * @return [[@doctodo return_type:getLogModel]] [[@doctodo return_description:getLogModel]]
     */
    public function getLogModel($refresh = false)
    {
        $config = $this->config;
        if (isset($config['logModel'])) {
            if (!is_object($config['logModel'])) {
                if ($refresh) {
                    return DataInterfaceLog::find()->where(['id' => $config['logModel']])->one();
                } else {
                    return DataInterfaceLog::get($config['logModel']);
                }
            }
            if ($refresh) {
                return DataInterfaceLog::find()->where(['id' => $config['logModel']->primaryKey])->one();
            }

            return $config['logModel'];
        }

        return;
    }

    /**
     * @inheritdoc
     */
    public function requiredConfigParams()
    {
        return ['logModel'];
    }

    /**
     * @inheritdoc
     */
    public function getResultConfig()
    {
        return [
            'class' => DeferredResult::className(),
        ];
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\form\fields;

use cascade\components\web\form\FormObjectTrait;
use canis\helpers\Html;
use canis\web\grid\CellContentTrait;

/**
 * Base [[@doctodo class_description:cascade\components\web\form\fields\Base]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class Base extends \canis\base\Object implements \canis\web\grid\CellContentInterface
{
    use FormObjectTrait;
    use CellContentTrait;

    /**
     * @var [[@doctodo var_type:modelField]] [[@doctodo var_description:modelField]]
     */
    public $modelField;
    /**
     * @var [[@doctodo var_type:options]] [[@doctodo var_description:options]]
     */
    public $options;
    /**
     * @var [[@doctodo var_type:smartOptions]] [[@doctodo var_description:smartOptions]]
     */
    public $smartOptions = [];
    /**
     * @var [[@doctodo var_type:htmlOptions]] [[@doctodo var_description:htmlOptions]]
     */
    public $htmlOptions = [];
    /**
     * @var [[@doctodo var_type:default]] [[@doctodo var_description:default]]
     */
    public $default;
    /**
     * @var [[@doctodo var_type:label]] [[@doctodo var_description:label]]
     */
    public $label;
    /**
     * @var [[@doctodo var_type:required]] [[@doctodo var_description:required]]
     */
    public $required; // for selectors
    /**
     * @var [[@doctodo var_type:showLabel]] [[@doctodo var_description:showLabel]]
     */
    public $showLabel = true;
    /**
     * @var [[@doctodo var_type:showError]] [[@doctodo var_description:showError]]
     */
    public $showError = true;

    /**
     * @var [[@doctodo var_type:_type]] [[@doctodo var_description:_type]]
     */
    protected $_type;

    /**
     * [[@doctodo method_description:generate]].
     */
    abstract public function generate();

    /**
     * Get model field name.
     *
     * @param unknown $formSettings (optional)
     *
     * @return unknown
     */
    public function getModelFieldName($formSettings = [])
    {
        return "{$this->model->tabularPrefix}{$this->field}";
    }

    /**
     * [[@doctodo method_description:neightborFieldId]].
     *
     * @param [[@doctodo param_type:field]] $field [[@doctodo param_description:field]]
     *
     * @return [[@doctodo return_type:neightborFieldId]] [[@doctodo return_description:neightborFieldId]]
     */
    public function neightborFieldId($field)
    {
        $modelFields = $this->model->fields;
        if (!isset($modelFields[$field])) {
            return false;
        }

        return $modelFields[$field]->formField->fieldId;
    }

    /**
     * Get field.
     *
     * @return [[@doctodo return_type:getFieldId]] [[@doctodo return_description:getFieldId]]
     */
    public function getFieldId()
    {
        return Html::getInputId($this->model, $this->getModelFieldName());
    }

    /**
     * Get type.
     *
     * @return unknown
     */
    public function getType()
    {
        if (is_null($this->_type)) {
            $this->_type = FieldTypeDetector::detect($this->modelField);
        }

        return $this->_type;
    }

    /**
     * Set type.
     *
     * @param unknown $value
     *
     * @return unknown
     */
    public function setType($value)
    {
        $this->_type = $value;

        return true;
    }

    /**
     * Get model.
     *
     * @return unknown
     */
    public function getModel()
    {
        if (is_null($this->modelField)) {
            return false;
        }

        return $this->modelField->model;
    }

    /**
     * Get field.
     *
     * @return unknown
     */
    public function getField()
    {
        if (is_null($this->modelField)) {
            return false;
        }

        return $this->modelField->field;
    }

    /**
     * Get filter settings.
     *
     * @return [[@doctodo return_type:getFilterSettings]] [[@doctodo return_description:getFilterSettings]]
     */
    public function getFilterSettings()
    {
        $s = [];
        $s['type'] = $this->filterType;
        $s['input'] = $this->filterInputType;
        $selectValues = $this->filterValues;
        if ($selectValues) {
            $s['values'] = $selectValues;
        }

        return $s;
    }

    /**
     * Get filter type.
     *
     * @return [[@doctodo return_type:getFilterType]] [[@doctodo return_description:getFilterType]]
     */
    public function getFilterType()
    {
        switch ($this->type) {
            case 'date':
            case 'time':
            case 'datetime':
                return $this->type;
            break;
            default:
                return 'string';
            break;
        }
    }

    /**
     * Get filter values.
     *
     * @return [[@doctodo return_type:getFilterValues]] [[@doctodo return_description:getFilterValues]]
     */
    public function getFilterValues()
    {
        if ($this->type === 'boolean') {
            return [0 => 'No', 1 => 'Yes'];
        }

        return false;
    }

    /**
     * Get filter input type.
     *
     * @return [[@doctodo return_type:getFilterInputType]] [[@doctodo return_description:getFilterInputType]]
     */
    public function getFilterInputType()
    {
        switch ($this->type) {
            case 'boolean':
                return 'select';
            break;
            default:
                return 'text';
            break;
        }
    }
}


<?php declare(strict_types=1);

namespace Ellipse\Http\Handlers;

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

use Interop\Http\Factory\ResponseFactoryInterface;

use Ellipse\Http\Exceptions\MiddlewareStackExhaustedException;

class NoticeJsonRequestHandler implements RequestHandlerInterface
{
    /**
     * The response factory.
     *
     * @var \Interop\Http\Factory\ResponseFactoryInterface
     */
    private $factory;

    /**
     * Set up a notice json request handler with the given response factory.
     *
     * @param \Interop\Http\Factory\ResponseFactoryInterface $factory
     */
    public function __construct(ResponseFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    /**
     * Return a notice json response.
     *
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $msg = "This is the default request handler. This means no middleware produced a response before hitting it.";

        $contents = json_encode([
            'type' => MiddlewareStackExhaustedException::class,
            'message' => $msg,
        ]);

        $response = $this->factory
            ->createResponse(404)
            ->withHeader('Content-type', 'application/json');

        $response->getBody()->write($contents);

        return $response;
    }
}


<?php

namespace ArtaxServiceBuilder;

class OperationDefinition {

    private $name = null;
    private $httpMethod = null;
    private $needsSigning = null;
    private $responseClass = null;
    private $responseFactory = null;
    private $responseCallable;
    private $permissions = [];
    private $scopes = [];

    /**
     * @var \ArtaxServiceBuilder\Parameter[]
     */
    private $parameters = [];
    private $summary = null;
    private $url = null;

    function __construct() {
    }

    public function extend($newName, $extendDefinition) {
        $instance = clone $this;
        $instance->name = $newName;
        $instance->setOperationParams($extendDefinition);

        return $instance;
    }

    function setName($name) {
        $this->name = $name;
    }

    /**
     * @return array
     */
    public function getPermissions() {
        return $this->permissions;
    }

    /**
     * @return array
     */
    public function getScopes() {
        return $this->scopes;
    }

    /**
     * @return null
     */
    public function getHttpMethod() {
        return $this->httpMethod;
    }

    /**
     * @return null
     */
    public function getName() {
        return $this->name;
    }

    /**
     * @return null
     */
    public function getNeedsSigning() {
        return $this->needsSigning;
    }

    /**
     * @return Parameter[]
     */
    public function getParameters() {
        return $this->parameters;
    }

    /**
     * @return null
     */
    public function getResponseClass() {
        return $this->responseClass;
    }

    /**
     * @return null
     */
    public function getResponseFactory() {
        return $this->responseFactory;
    }

    /**
     *
     */
    public function getResponseCallable() {
        return $this->responseCallable;
    }

    /**
     * @return null
     */
    public function getSummary() {
        return $this->summary;
    }

    /**
     * @return null
     */
    public function getURL() {
        return $this->url;
    }

    /**
     * Get all the params that are either not optional and don't have a default value
     * @return \ArtaxServiceBuilder\Parameter[]
     */
    public function getRequiredParams() {
        $requiredParams = [];

        foreach ($this->parameters as $parameter) {
            if ($parameter->getIsOptional() || $parameter->hasDefault()) {
                continue;
            }
            $requiredParams[]  = $parameter;
        }

        return $requiredParams;
    }

    /**
     * Get all the params that have a default value
     * @return \ArtaxServiceBuilder\Parameter[]
     */
    public function getDefaultParams() {
        $defaultParams = [];
        foreach ($this->parameters as $parameter) {
            if ($parameter->hasDefault()) {
                if ($parameter->getIsAPIParameter() == false) {
                    $defaultParams[] = $parameter;
                }
            }
        }

        return $defaultParams;
    }

    /**
     * @param $baseURL
     */
    function setURL($baseURL) {
        $this->url = $baseURL;
    }

    private function setOperationParams($description) {
        $operationParams = [
            "extends",
            "httpMethod",
            "needsSigning",
            'permissions',
            "responseClass",
            "responseFactory",
            'responseCallable',
            'scopes',
            "summary"
        ];

        foreach ($operationParams as $simpleParam) {
            if (isset($description[$simpleParam])) {
                $this->{$simpleParam} = $description[$simpleParam];
            }
        }
    }

    private function setURI($description, $baseURL){
        //Yep, guzzle switches between baseURL and URI
        //@TODO - allow URL or URI in both.
        if (isset($description['uri'])) {
            if (stripos($description['uri'], 'http') === 0 ||
                (isset($description['uriIsAbsolute']) && $description['uriIsAbsolute'])
            ) {
                //It's an absolute URL
                $this->setURL($description['uri']);
            }
            else {
                //TODO - use \Artax\URI for RFC compliant combining.
                $this->setURL($baseURL.$description['uri']);
            }
        }
    }

    /**
     * @param $description
     */
    private function setParams($description, APIGenerator $api) {
        if (isset($description["parameters"])) {
            foreach ($description["parameters"] as $paramName => $parameterDescription) {

                //DJA - temp hack to remove unsupported multiple params
                // e.g. "question_{index}"
                if (strpos($paramName, '{') !== false) {
                    continue;
                }
                //DJA - temp hack to remove unsupported multiple params

                $isAPIParameter = false;
                if (array_key_exists($paramName, $api->getAPIParameters())) {
                    $isAPIParameter = true;
                }

                $parameter = Parameter::createFromDescription(
                    $paramName,
                    $parameterDescription,
                    $isAPIParameter
                );

                $this->parameters[$paramName] = $parameter;
            }
        }
    }

    /**
     * @param $description
     */
    function setFromServiceDescription($description, $baseURL, APIGenerator $api) {
        $this->setOperationParams($description);
        $this->setURI($description, $baseURL);
        $this->setParams($description, $api);
    }

//    TODO - make the param generation functions be on this class, rather
//    than spread between the api and operation generator.
}


<?php

namespace Weew\HttpBlueprint;

use LogicException;
use Weew\HttpServer\HttpServer;
use Weew\HttpServer\IHttpServer;

class BlueprintServer {
    /**
     * @var IHttpServer
     */
    protected $server;

    /**
     * @param $host
     * @param $port
     * @param $blueprintFile
     */
    public function __construct($host, $port, $blueprintFile) {
        $this->server = $this->createHttpServer($host, $port, $blueprintFile);
    }

    /**
     * Start  server.
     */
    public function start() {
        $this->server->start();
    }

    /**
     * Stop server.
     */
    public function stop() {
        $this->server->stop();
    }

    /**
     * @return bool
     */
    public function isRunning() {
        return $this->server->isRunning();
    }

    /**
     * @param $host
     * @param $port
     * @param $blueprintFile
     *
     * @return HttpServer
     */
    protected function createHttpServer($host, $port, $blueprintFile) {
        if ( ! is_file($blueprintFile)) {
            throw new LogicException(
                s('Blueprint not found at %s.', $blueprintFile)
            );
        }

        $server = new HttpServer($host, $port, $blueprintFile);
        $server->echoMessage(s('Using blueprint file %s', $blueprintFile));

        return $server;
    }
}


<?php
namespace Ecompassaro\Login\Registrar;

use Ecompassaro\Acesso\Controller as AcessoController;
use Ecompassaro\Notificacao\FlashMessagesContainerTrait;
use Ecompassaro\Login\ViewModel as LoginViewModel;

class Controller extends AcessoController
{
    use FlashMessagesContainerTrait;

    protected $resource = 'registrar';
    protected $loginViewModel;

	public function __construct(ViewModel $viewModel, LoginViewModel $loginViewModel) {
        $this->viewModel = $viewModel;
        $this->loginViewModel = $loginViewModel;
	}

    /**
     * Mostra a página de registrar
     *
     * @return RegistrarViewModel
     */
    public function indexAction()
    {
        return $this->getViewModel()->setTemplate('login/new');
    }

    /**
     * Cadastra o usuario e redireciona para a página que for passada por parâmetro ou para
     * a página default
     */
    public function registrarAction()
    {
        $this->getViewModel()->getFormulario()->setData($this->params()->fromPost());
        if ($this->getViewModel()->getFormulario()->isValid() && $this->getViewModel()->save()) {
            $redirect = $this->params()->fromPost('routeRedirect');
            $this->loginViewModel->validaLogin($this->getViewModel()->getFormulario()->getData());
            $this->getViewModel()->getFormulario($redirect?$redirect:'site');
        }

        $mensagens = $this->getViewModel()->getNotificacoes();
        if ($mensagens) {
            $this->setFlashMessagesFromNotificacoes($mensagens);
        } else {
            $this->setFlashMessagesFromNotificacoes($this->getViewModel()->getFormulario()->getMessages());
        }
        return $this->redirect()->toRoute('registrar');
    }
}


<?php

namespace NajiDev\Common\Helper;

use \NajiDev\Common\Exception\InvalidArgumentException;

class StringHelper
{
	/**
	 * Strip a string from the end of a string
	 *
	 * @param string $str      the input string
	 * @param string $remove   string to remove
	 *
	 * @throws \NajiDev\Common\Exception\InvalidArgumentException
	 * @return string the modified string
	 */
	public static function trimStringRight($str, $remove)
	{
		if (!is_string($str))
			throw new InvalidArgumentException('$str has to be a string');

		if (!is_string($remove))
			throw new InvalidArgumentException('$remove has to be a string');

		$len    = strlen($remove);
		$offset = strlen($str) - $len;

		while(0 < $offset && strpos($str, $remove, $offset) === $offset)
		{
			$str    = substr($str, 0, $offset);
			$offset = strlen($str) - $len;
		}

		return $str;
	}
}


<?php
namespace app\manage\controller;

use think\Db;
use think\Url;
use cms\Common;
use think\Request;
use core\manage\logic\MemberLogic;
use core\manage\logic\MenuLogic;
use core\manage\logic\FileLogic;
use core\manage\logic\ConfigLogic;
use app\manage\logic\RuntimeLogic;
use app\manage\logic\LoginLogic;

class Index extends Base
{

    /**
     * 首页
     *
     * @param Request $request
     * @return string
     */
    public function index(Request $request)
    {
        $this->site_title = '后台首页';

        // 基础统计
        $site_info = [
            'member_num' => MemberLogic::model()->count(),
            'menu_num' => MenuLogic::model()->count(),
            'file_num' => FileLogic::model()->count(),
            'config_num' => ConfigLogic::model()->count()
        ];
        $this->assign('site_info', $site_info);

        // 系统信息
        $mysql_version = Db::query('select version() as version');
        $server_info = array(
            'ThinkPHP版本' => 'ThinkPHP ' . THINK_VERSION,
            'CMS信息' => '作者 : 哩呵 , GIT : NewDayCms。',
            '操作系统' => PHP_OS,
            '主机名信息' => $request->server('SERVER_NAME') . ' (' . $request->server('SERVER_ADDR') . ':' . $request->server('SERVER_PORT') . ')',
            '运行环境' => $request->server('SERVER_SOFTWARE'),
            'PHP运行方式' => php_sapi_name(),
            '程序目录' => WEB_PATH,
            'MYSQL版本' => 'MYSQL ' . $mysql_version[0]['version'],
            '上传限制' => ini_get('upload_max_filesize'),
            'POST限制' => ini_get('post_max_size'),
            '最大内存' => ini_get('memory_limit'),
            '执行时间限制' => ini_get('max_execution_time') . "秒",
            '内存使用' => Common::formatBytes(@memory_get_usage()),
            '磁盘使用' => Common::formatBytes(@disk_free_space(".")) . '/' . Common::formatBytes(@disk_total_space(".")),
            'display_errors' => ini_get("display_errors") == "1" ? '√' : '×',
            'register_globals' => get_cfg_var("register_globals") == "1" ? '√' : '×',
            'magic_quotes_gpc' => (1 === get_magic_quotes_gpc()) ? '√' : '×',
            'magic_quotes_runtime' => (1 === get_magic_quotes_runtime()) ? '√' : '×'
        );
        $this->assign('server_info', $server_info);

        // 扩展列表
        $extensions_list = get_loaded_extensions();
        $this->assign('extensions_list', implode(' , ', $extensions_list));

        return $this->fetch();
    }

    /**
     * 账号设置
     *
     * @param Request $request
     * @return string
     */
    public function account(Request $request)
    {
        if ($request->isPost()) {
            $user_nick = $request->param('user_nick');
            if (empty($user_nick)) {
                return $this->error('昵称为空');
            }

            $user_passwd = $request->param('user_passwd');
            $re_passwd = $request->param('re_passwd');
            if (! empty($user_passwd)) {

                // 重复密码
                if ($user_passwd != $re_passwd) {
                    return $this->error('两次密码不一致');
                }

                // 验证原密码
                $old_passwd = $request->param('old_passwd');
                if (empty($old_passwd)) {
                    return $this->error('原密码为空');
                } else {
                    $user = LoginLogic::gteLoginUserInfo();

                    $result = LoginLogic::doLogin($user['user_name'], $old_passwd);
                    if ($result['code'] != 1) {
                        return $this->error('原密码错误');
                    }
                }
            }

            // 保存账号
            $data = [
                'user_nick' => $user_nick
            ];
            $user_passwd && $data['user_passwd'] = $user_passwd;
            MemberLogic::instance()->saveMember($data, $this->user_id);

            return $this->success('修改资料成功', Url::build('index/account'));
        } else {
            $this->site_title = '账号设置';
            return $this->fetch();
        }
    }

    /**
     * 删除缓存
     *
     * @param Request $request
     * @return mixed
     */
    public function delRuntime(Request $request)
    {
        // 路径
        $path = $request->param('path');
        $path = $path ? base64_decode($path) : '/';

        // 是否删除自己
        $self = $request->param('self', 0);

        // 跳转链接
        $url = Url::build('runtime', [
            'path' => base64_encode($self ? RuntimeLogic::dirName($path) : $path)
        ]);

        // 删除缓存
        $res = RuntimeLogic::delRuntime($path, $self);
        if ($res) {
            return $this->success('删除文件成功', $url);
        } else {
            return $this->error('删除文件失败');
        }
    }
}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Renderer;

use Cawa\App\AbstractApp;
use Cawa\Controller\ViewController;
use Cawa\Controller\ViewDataTrait;

class PhtmlTemplate extends ViewController
{
    use PhtmlTrait;
    use ViewDataTrait;
    use AssetTrait;

    /**
     * @param string $templatePath
     */
    private function __construct(string $templatePath)
    {
        $this->setTemplatePath($templatePath);
    }

    /**
     * @param string $templatePath
     * @param array $data
     *
     * @return string
     */
    public static function renderTemplate(string $templatePath, array $data = []) : string
    {
        if (substr($templatePath, 0, 1) != '/') {
            $templatePath = AbstractApp::getAppRoot() . '/' . $templatePath;
        }

        $phtml = new static($templatePath);
        $phtml->addViewDatas($data);

        return $phtml->render();
    }
}


<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Notice.php.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @see      https://github.com/overtrue
 * @see      http://overtrue.me
 */

namespace EasyWeChat\Notice;

use EasyWeChat\Core\AbstractAPI;
use EasyWeChat\Core\AccessToken;
use EasyWeChat\Core\Exceptions\InvalidArgumentException;

/**
 * Class Notice.
 */
class Notice extends AbstractAPI
{
    /**
     * Default color.
     *
     * @var string
     */
    protected $defaultColor = '#173177';

    /**
     * Attributes.
     *
     * @var array
     */
    protected $message = [
        'touser' => '',
        'template_id' => '',
        'url' => '',
        'data' => [],
    ];

    /**
     * Required attributes.
     *
     * @var array
     */
    protected $required = ['touser', 'template_id'];

    /**
     * Message backup.
     *
     * @var array
     */
    protected $messageBackup;

    const API_SEND_NOTICE = 'https://api.weixin.qq.com/cgi-bin/message/template/send';
    const API_SET_INDUSTRY = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry';
    const API_ADD_TEMPLATE = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template';
    const API_GET_INDUSTRY = 'https://api.weixin.qq.com/cgi-bin/template/get_industry';
    const API_GET_ALL_PRIVATE_TEMPLATE = 'https://api.weixin.qq.com/cgi-bin/template/get_all_private_template';
    const API_DEL_PRIVATE_TEMPLATE = 'https://api.weixin.qq.com/cgi-bin/template/del_private_template';
    const API_SEND_SUBSCRIPTION = 'https://api.weixin.qq.com/cgi-bin/message/template/subscribe';

    /**
     * Notice constructor.
     *
     * @param \EasyWeChat\Core\AccessToken $accessToken
     */
    public function __construct(AccessToken $accessToken)
    {
        parent::__construct($accessToken);

        $this->messageBackup = $this->message;
    }

    /**
     * Set default color.
     *
     * @param string $color example: #0f0f0f
     *
     * @return $this
     */
    public function defaultColor($color)
    {
        $this->defaultColor = $color;

        return $this;
    }

    /**
     * Set industry.
     *
     * @param int $industryOne
     * @param int $industryTwo
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function setIndustry($industryOne, $industryTwo)
    {
        $params = [
                   'industry_id1' => $industryOne,
                   'industry_id2' => $industryTwo,
                  ];

        return $this->parseJSON('json', [self::API_SET_INDUSTRY, $params]);
    }

    /**
     * Get industry.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getIndustry()
    {
        return $this->parseJSON('json', [self::API_GET_INDUSTRY]);
    }

    /**
     * Add a template and get template ID.
     *
     * @param string $shortId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function addTemplate($shortId)
    {
        $params = ['template_id_short' => $shortId];

        return $this->parseJSON('json', [self::API_ADD_TEMPLATE, $params]);
    }

    /**
     * Get private templates.
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function getPrivateTemplates()
    {
        return $this->parseJSON('json', [self::API_GET_ALL_PRIVATE_TEMPLATE]);
    }

    /**
     * Delete private template.
     *
     * @param string $templateId
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function deletePrivateTemplate($templateId)
    {
        $params = ['template_id' => $templateId];

        return $this->parseJSON('json', [self::API_DEL_PRIVATE_TEMPLATE, $params]);
    }

    /**
     * Send a notice message.
     *
     * @param $data
     *
     * @return \EasyWeChat\Support\Collection
     *
     * @throws \EasyWeChat\Core\Exceptions\InvalidArgumentException
     */
    public function send($data = [])
    {
        return $this->parseJSON('json', [static::API_SEND_NOTICE, $this->validParams($data)]);
    }

    /**
     * Send template-message for subscription.
     *
     * @param array $data
     *
     * @return \EasyWeChat\Support\Collection
     */
    public function sendSubscription(array $data = [])
    {
        return $this->parseJSON('json', [static::API_SEND_SUBSCRIPTION, $this->validParams($data)]);
    }

    /**
     * @param array $data
     *
     * @return array
     */
    protected function validParams(array $data = [])
    {
        $params = array_merge($this->message, $data);

        foreach ($params as $key => $value) {
            if (in_array($key, $this->required, true) && empty($value) && empty($this->message[$key])) {
                throw new InvalidArgumentException("Attribute '$key' can not be empty!");
            }

            $params[$key] = empty($value) ? $this->message[$key] : $value;
        }

        $params['data'] = $this->formatData($params['data']);

        $this->message = $this->messageBackup;

        return $params;
    }

    /**
     * Magic access..
     *
     * @param string $method
     * @param array  $args
     *
     * @return Notice
     */
    public function __call($method, $args)
    {
        $map = [
                'template' => 'template_id',
                'templateId' => 'template_id',
                'uses' => 'template_id',
                'to' => 'touser',
                'receiver' => 'touser',
                'url' => 'url',
                'link' => 'url',
                'data' => 'data',
                'with' => 'data',
                'formId' => 'form_id',
                'prepayId' => 'form_id',
               ];

        if (0 === stripos($method, 'with') && strlen($method) > 4) {
            $method = lcfirst(substr($method, 4));
        }

        if (0 === stripos($method, 'and')) {
            $method = lcfirst(substr($method, 3));
        }

        if (isset($map[$method])) {
            $this->message[$map[$method]] = array_shift($args);
        }

        return $this;
    }

    /**
     * Format template data.
     *
     * @param array $data
     *
     * @return array
     */
    protected function formatData($data)
    {
        $return = [];

        foreach ($data as $key => $item) {
            if (is_scalar($item)) {
                $value = $item;
                $color = $this->defaultColor;
            } elseif (is_array($item) && !empty($item)) {
                if (isset($item['value'])) {
                    $value = strval($item['value']);
                    $color = empty($item['color']) ? $this->defaultColor : strval($item['color']);
                } elseif (count($item) < 2) {
                    $value = array_shift($item);
                    $color = $this->defaultColor;
                } else {
                    list($value, $color) = $item;
                }
            } else {
                $value = 'error data item.';
                $color = $this->defaultColor;
            }

            $return[$key] = [
                'value' => $value,
                'color' => $color,
            ];
        }

        return $return;
    }
}


<?php

namespace Wookieb\Map;

use Wookieb\Map\Exception\EntryNotFoundException;

/**
 * Standard map implementation where you can store everything you want
 *
 * @author Łukasz Kużyński "wookieb" <lukasz.kuzynski@gmail.com>
 */
class Map implements MapInterface
{
    protected $lastStorageKey;
    protected $storage = array();
    protected $useMapEntries = true;
    private $keyIndex = 0;
    protected $counter = 0;

    public function __construct($useMapEntries = null)
    {
        $isPHP55 = version_compare(PHP_VERSION, '5.5', '>=');
        if ($useMapEntries === null) {
            $useMapEntries = $isPHP55 ? false : true;
        }
        if (!$useMapEntries && !$isPHP55) {
            $msg = 'You cannot iterate through the map without using map entries since current PHP version '.
                'does not support non-scalar keys for iterator.';
            throw new \BadMethodCallException($msg);
        }
        $this->useMapEntries = $useMapEntries;
    }

    protected function createEntryNotFoundException($key)
    {
        $msg = 'Entry not found';
        if (is_scalar($key)) {
            $msg .= vsprintf(' for key "(%s) %s"', array(
                gettype($key),
                var_export($key, true)
            ));
        }
        return new EntryNotFoundException($msg, $key);
    }

    /**
     * Returns current entry value
     *
     * @return mixed|MapEntry MapEntry will be used only for php >= 5.5
     */
    public function current()
    {
        $current = current($this->storage);
        if ($this->useMapEntries) {
            return new MapEntry($current[0], $current[1]);
        }
        return $current[1];
    }

    /**
     * {@inheritDoc}
     */
    public function next()
    {
        next($this->storage);
        $this->keyIndex++;
    }

    /**
     * @return mixed|void
     */
    public function key()
    {
        if ($this->useMapEntries) {
            return $this->keyIndex;
        }
        $current = current($this->storage);
        return $current[0];
    }

    /**
     * {@inheritDoc}
     */
    public function valid()
    {
        return current($this->storage) !== false;
    }

    /**
     * {@inheritDoc}
     */
    public function rewind()
    {
        reset($this->storage);
        $this->keyIndex = 0;
    }

    /**
     * {@inheritDoc}
     */
    public function search($value, $strict = false)
    {
        foreach ($this->storage as &$storageValue) {
            if ($strict) {
                if ($value === $storageValue[1]) {
                    return $storageValue[0];
                }
            } else if ($value == $storageValue[1]) {
                return $storageValue[0];
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public function get($key)
    {
        if (!$this->has($key)) {
            throw $this->createEntryNotFoundException($key);
        }
        return $this->storage[$this->lastStorageKey][1];
    }

    /**
     * {@inheritDoc}
     */
    public function remove($key)
    {
        if (!$this->has($key)) {
            throw $this->createEntryNotFoundException($key);
        }
        unset($this->storage[$this->lastStorageKey]);
        $this->counter--;
    }

    /**
     * {@inheritDoc}
     */
    public function isEmpty()
    {
        return $this->counter === 0;
    }

    /**
     * {@inheritDoc}
     */
    public function count()
    {
        return $this->counter;
    }

    /**
     * {@inheritDoc}
     */
    public function has($key)
    {
        $storageKey = $this->computeStorageKey($key);
        $this->lastStorageKey = $storageKey;
        return isset($this->storage[$storageKey]);
    }

    protected function computeStorageKey($key)
    {
        if (is_object($key)) {
            return spl_object_hash($key);
        } else if (is_array($key)) {
            return md5(serialize($key));
        }
        return gettype($key).$key;
    }

    /**
     * {@inheritDoc}
     */
    public function add($key, $value)
    {
        $storageKey = $this->computeStorageKey($key);
        $this->storage[$storageKey] = array($key, $value);
        $this->counter++;
    }

    /**
     * {@inheritDoc}
     */
    public function isUsingMapEntries()
    {
        return $this->useMapEntries;
    }
}


<?php

namespace Joseki\Forms;

use Kdyby\Replicator\Container as RContainer;
use Joseki\Forms\Controls\SubmitButton;
use Nextras\Forms\Controls\DatePicker;

class Container extends \Nette\Forms\Container
{

    /**
     * @param $name
     * @param null $caption
     * @return SubmitButton|\Nette\Forms\Controls\SubmitButton
     */
    public function addSubmit($name, $caption = null)
    {
        return $this[$name] = new SubmitButton($caption);
    }

    /**
     * Adds DatePicker to enable user-friendly GUI for picking date
     * @param $name
     * @param null $label
     * @return DatePicker
     */
    public function addDatePicker($name, $label = null)
    {
        return $this[$name] = new DatePicker($label);
    }

    /**
     * Adds replicable container
     * @param $name
     * @param $factory
     * @param int $createDefault
     * @param bool $forceDefault
     * @return Container
     */
    public function addDynamic($name, $factory, $createDefault = 0, $forceDefault = false)
    {
        $control = new RContainer($factory, $createDefault, $forceDefault);
        $control->currentGroup = $this->currentGroup;
        return $this[$name] = $control;
    }

    /**
     * @inheritdoc
     */
    public function addContainer($name)
    {
        $control = new Container;
        $control->currentGroup = $this->currentGroup;
        return $this[$name] = $control;
    }
}


<?php
namespace Poirot\Queue\Queue;

use MongoDB;

use Poirot\Queue\Exception\exIOError;
use Poirot\Queue\Exception\exReadError;
use Poirot\Queue\Exception\exWriteError;
use Poirot\Queue\Interfaces\iPayload;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Queue\Payload\QueuedPayload;
use Poirot\Storage\Interchange\SerializeInterchange;

/**
 * These Indexes:
 *
 * 	{
 *    "queue": NumberLong(1)
 * }
 * {
 *   "_id": NumberLong(1),
 *   "queue": NumberLong(1)
 * }
 * {
 *   "pop": NumberLong(1)
 *   "queue": NumberLong(1)
 * }
 */
class MongoQueue
    implements iQueueDriver
{
    /** @var MongoDB\Collection */
    protected $collection;

    private static $typeMap = [
        'root' => 'array',
        'document' => 'array',
        'array' => 'array',
    ];

    /** @var SerializeInterchange */
    protected $_c_interchangable;

    /**
     * MongoQueue constructor.
     *
     * @param MongoDB\Collection $collection
     */
    function __construct(MongoDB\Collection $collection)
    {
        $this->collection = $collection;
    }

    /**
     * Push To Queue
     *
     * @param iPayload $payload Serializable payload
     * @param string   $queue
     *
     * @return iPayloadQueued
     * @throws exIOError
     */
    function push($payload, $queue = null)
    {
        if ( null === $queue && $payload instanceof iPayloadQueued )
            $queue = $payload->getQueue();

        /** @var QueuedPayload $qPayload */
        $qPayload = $payload;

        $time = ($payload instanceof iPayloadQueued)
            ? $time = $payload->getCreatedTimestamp()
            : time();

        if (! $payload instanceof iPayloadQueued ) {
            $qPayload = new QueuedPayload($payload);

            $uid      = new MongoDB\BSON\ObjectID();
            $qPayload = $qPayload
                ->withUID( $uid )
            ;

        } else {

            $uid = new MongoDB\BSON\ObjectID($qPayload->getUID());
        }

        $qPayload = $qPayload->withQueue( $this->_normalizeQueueName($queue) );

        // .............

        $sPayload = $this->_interchangeable()
            ->makeForward($qPayload);

        try {
            $this->collection->insertOne(
                [
                    '_id'     => $uid,
                    'queue'   => $qPayload->getQueue(),
                    'payload' => new MongoDB\BSON\Binary($sPayload, MongoDB\BSON\Binary::TYPE_GENERIC),
                    'payload_humanize' => $sPayload,
                    'created_timestamp' => $time,
                    'pop'     => false, // not yet popped; against race condition
                ]
            );

        } catch (\Exception $e) {
            throw new exWriteError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }

        return $qPayload;
    }

    /**
     * Pop From Queue
     *
     * note: when you pop a message from queue you have to
     *       release it when worker done with it.
     *
     *
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function pop($queue = null)
    {
        try {
            $queued = $this->collection->findOneAndUpdate(
                [
                    'queue' => $this->_normalizeQueueName($queue),
                    'pop'   => false,
                ]
                , [
                    '$set' => ['pop' => true]
                ]
                , [
                    // pick last one in the queue
                    'sort'    => [ '_id' => -1 ],
                    // override typeMap option
                    'typeMap' => self::$typeMap,
                ]
            );
        } catch (\Exception $e) {
            throw new exReadError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }

        if (! $queued )
            return null;

        $payload = $this->_interchangeable()
            ->retrieveBackward($queued['payload']);

        $payload = $payload->withQueue($queue)
            ->withUID( (string) $queued['_id'] );

        return $payload;
    }

    /**
     * Release an Specific From Queue By Removing It
     *
     * @param iPayloadQueued|string $id
     * @param null|string           $queue
     *
     * @return void
     * @throws exIOError
     */
    function release($id, $queue = null)
    {
        if ( $id instanceof iPayloadQueued ) {
            $arg   = $id;
            $id    = $arg->getUID();
            $queue = $arg->getQueue();
        }

        try {
            $this->collection->deleteOne([
                '_id'   => new MongoDB\BSON\ObjectID($id),
                'queue' => $this->_normalizeQueueName($queue),
            ]);
        } catch (\Exception $e) {
            throw new exWriteError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }
    }

    /**
     * Find Queued Payload By Given ID
     *
     * @param string $id
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function findByID($id, $queue = null)
    {
        try {
            $queued = $this->collection->findOne(
                [
                    '_id'   => new MongoDB\BSON\ObjectID( (string) $id),
                    'queue' => $this->_normalizeQueueName($queue),
                ]
                , [
                    // override typeMap option
                    'typeMap' => self::$typeMap,
                ]
            );
        } catch (\Exception $e) {
            throw new exReadError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }

        if (! $queued )
            return null;

        $payload = $this->_interchangeable()
            ->retrieveBackward($queued['payload']);

        $payload = $payload->withQueue($queue)
            ->withUID( (string) $queued['_id'] );

        return $payload;
    }

    /**
     * Get Queue Size
     *
     * @param string $queue
     *
     * @return int
     * @throws exIOError
     */
    function size($queue = null)
    {
        try {
            $count = $this->collection->count(
                [
                    'queue' => $this->_normalizeQueueName($queue),
                ]
            );
        } catch (\Exception $e) {
            throw new exReadError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }

        return $count;
    }

    /**
     * Get Queues List
     *
     * @return string[]
     * @throws exIOError
     */
    function listQueues()
    {
        try {
            $csr = $this->collection->aggregate(
                [
                    [
                        '$group' => [
                            '_id'   => '$queue',
                        ],
                    ],
                ]
                , [
                    // override typeMap option
                    'typeMap' => self::$typeMap,
                ]
            );
        } catch (\Exception $e) {
            throw new exReadError('Error While Write To Mongo Client.', $e->getCode(), $e);
        }

        $list = [];
        foreach ($csr as $item)
            $list[] = $item['_id'];

        return $list;
    }

    // ..

    /**
     * @return SerializeInterchange
     */
    protected function _interchangeable()
    {
        if (! $this->_c_interchangable)
            $this->_c_interchangable = new SerializeInterchange;

        return $this->_c_interchangable;
    }

    /**
     * @param string $queue
     * @return string
     */
    protected function _normalizeQueueName($queue)
    {
        if ($queue === null)
            return $queue = 'general';

        return strtolower( (string) $queue );
    }
}


<?php
namespace Lab123\Odin\Traits;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Lab123\Odin\Entities\Entity;
use Lab123\Odin\Enums\Responses;
use Log;
use App;
use DB;

trait ApiResponse
{

    /**
     * Return HTTP Continue (100)
     *
     * @return \Illuminate\Http\Response
     */
    public function continues()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_CONTINUE);
    }

    /**
     * Return HTTP Success (200)
     *
     * @return \Illuminate\Http\Response
     */
    public function success()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_OK);
    }

    /**
     * Return HTTP Created (201)
     *
     * @return \Illuminate\Http\Response
     */
    public function created()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_CREATED);
    }

    /**
     * Return HTTP Bad Request (400)
     *
     * @return \Illuminate\Http\Response
     */
    public function bad()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_BAD_REQUEST);
    }

    /**
     * Return HTTP Unauthorized (401)
     *
     * @return \Illuminate\Http\Response
     */
    public function unauthorized()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_UNAUTHORIZED);
    }

    /**
     * Return HTTP Not Found (404)
     *
     * @return \Illuminate\Http\Response
     */
    public function notFound()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_NOT_FOUND);
    }

    /**
     * Return HTTP Conflict (409)
     *
     * @return \Illuminate\Http\Response
     */
    public function conflict()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_CONFLICT);
    }

    /**
     * Return HTTP Bad Request (422)
     *
     * @return \Illuminate\Http\Response
     */
    public function unprocessable()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_UNPROCESSABLE_ENTITY);
    }

    /**
     * Return HTTP Internal Error (500)
     *
     * @return \Illuminate\Http\Response
     */
    public function internalError()
    {
        $args = func_get_args();
        return $this->response($this->getData($args), Responses::HTTP_INTERNAL_SERVER_ERROR);
    }

    /**
     * Return HTTP Code
     *
     * @return \Illuminate\Http\Response
     */
    public function response(array $data, $http_code)
    {
        if (config('odin.queryRequest')) {
            $data['queries'] = $this->getQueries();
        }
        return response()->json($data, $http_code);
    }

    /**
     * Return Exception into HTTP Internal Error (500)
     *
     * @return \Illuminate\Http\Response
     */
    public function exception(\Exception $ex)
    {
        $log = [
            'error' => $ex->getMessage(),
            'file' => $ex->getFile(),
            'line' => $ex->getLine()
        ];

        Log::error($log);

        $return = [
            "erro" => "Ocorreu um erro inesperado. Por favor, tente mais tarde."
        ];

        if (App::environment('local', 'staging')) {
            $return['server_error'] = $log;
        }

        return $this->internalError($return);
    }

    /**
     * Return entity data array or array blank
     *
     * @return array
     */
    private function getData($args)
    {
        $data = [];

        /* Sem argumentos, retorna array em branco */
        if (count($args) < 1) {
            return $data;
        }

        /* Enviou um array como parâmetro */
        if (is_array($args[0])) {
            return $args[0];
        }

        /* Enviou um Paginador como parâmetro */
        if (is_a($args[0], LengthAwarePaginator::class)) {
            $paginator = ($args[0]);
            $data = $paginator->toArray();
        }

        /* Enviou uma Coleção como parâmetro */
        if (is_a($args[0], Collection::class)) {
            $collection = ($args[0]);
            $data = $collection->toArray();
        }

        /* Enviou uma Entidade como parâmetro */
        if (is_a($args[0], Entity::class)) {
            $entity = ($args[0]);
            // $entity->autoload();
            // $data['data'] = $entity->toArray();
            $data = $entity->toArray();
        }

        return $data;
    }

    /**
     * Return entity data array or array blank
     *
     * @return array
     */
    private function getQueries()
    {
        return $queries = DB::getQueryLog();

        $formattedQueries = [];
        foreach ($queries as $query) {
            $prep = $query['query'];

            foreach ($query['bindings'] as $binding) {
                $prep = preg_replace("#\?#", $binding, $prep, 1);
            }

            $formattedQueries[] = $prep;
        }

        return $formattedQueries;
    }
}


<?php
namespace eMacros\Runtime\Comparison;

use eMacros\Runtime\GenericFunction;

abstract class ComparisonPredicate extends GenericFunction {
	protected $logicalOr = false;

	/**
	 * Compares various operands
	 * Usage: (== 1 2) (>= 4 3) (=== "1" 1)
	 * Returns: boolean
	 * (non-PHPdoc)
	 * @see \eMacros\Runtime\GenericFunction::execute()
	 */
	public function execute(array $operands) {
		if (empty($operands))
			throw new \BadFunctionCallException(sprintf("%s: No objects to compare.", get_class($this)));
		if (!isset($operands[1]))
			throw new \BadFunctionCallException(sprintf("%s: Cannot compare single object.", get_class($this)));
		$fst = array_shift($operands);
		$or = $this->logicalOr;

		foreach ($operands as $val) {
			if ($or xor !$this->compare($fst, $val)) return $or;
			$fst = $val;
		}

		return !$or;
	}

	abstract protected function compare($a, $b);
}
?>


<?php
/**
 * Created by Marcin.
 * Date: 22.10.2017
 * Time: 22:25
 */

namespace mrcnpdlk\Monolog\Handler;

use mrcnpdlk\Monolog\Helper;

class StreamHandler extends \Monolog\Handler\StreamHandler
{
    /**
     * Write to stream
     *
     * @param resource $stream
     * @param array    $record
     */
    protected function streamWrite($stream, array $record)
    {
        parent::streamWrite($stream, $record);
        if ($record['message_orig']) {
            fwrite($stream, Helper::logSuffix($record['message_orig']));
        }

    }
}


<?php

/**
 * ItePHP: Framework PHP (http://itephp.com)
 * Copyright (c) NewClass (http://newclass.pl)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the file LICENSE
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) NewClass (http://newclass.pl)
 * @link          http://itephp.com ItePHP Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace ItePHP\Migrate;

use ItePHP\Command\CommandInterface;
use ItePHP\Command\CommandConfig;
use ItePHP\Command\InputStream;
use ItePHP\Command\OutputStream;

use ItePHP\Core\Container;
use ItePHP\Core\Environment;

/**
 * Migrate command.
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class MigrateCommand implements CommandInterface{

	/**
	 * @var Container
	 */
	private $container;

	/**
	 * @var Environment
	 */
	private $environment;

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

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

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

    /**
	 *
	 * @param Container $container
	 * @param Environment $environment
	 */
	public function __construct(Container $container, Environment $environment){
		$this->container=$container;
		$this->environment=$environment;
		$this->setPatternPath('/vendor/itephp/framework/pattern/migrate.txt');
		$this->setSavePath('/config/migrate.'.$this->environment->getName().'.txt');
		$this->setStagePath('/src/Migrate');
	}

	/**
	 *
	 * @param string $path
	 */
	public function setPatternPath($path){
		$this->patternPath=$path;
	}

	/**
	 *
	 * @param string $path
	 */
	public function setSavePath($path){
		$this->savePath=$path;
	}

	/**
	 *
	 * @param string $path
	 */
	public function setStagePath($path){
		$this->stagePath=$path;
	}

    /**
     * {@inheritdoc}
     */
	public function doConfig(CommandConfig $config){
		$config->addArgument('-o',1);
	}

    /**
     * {@inheritdoc}
     */
	public function execute(InputStream $in,OutputStream $out){
		$operation=$in->getArgument('-o');
		switch($in->getArgument('-o')){
			case 'create':
				$this->createOperation($out);
			break;
			case 'upgrade':
				$this->upgradeOperation($out);
			break;
			case 'downgrade':
				$this->downgradeOperation($out);
			break;
			default:
				throw new OperationNotSupportedException($operation);
		}
	}

	/**
	 *
	 * @param OutputStream $out
	 */
	public function createOperation(OutputStream $out){
		$now=new \DateTime();

		$template=file_get_contents($this->getPatternPath());
		$template=str_replace('${date}', $now->format('YmdHis'), $template);
		$path=$this->getStagePath().'/Version'.$now->format('YmdHis').'.php';
		file_put_contents($path, $template);
		$out->write('File created: '.$path);
		$out->flush();
	}

	/**
	 *
	 * @param OutputStream $out
	 * @throws \Exception
	 */
	public function upgradeOperation(OutputStream $out){
		$currentVersion=0;
		if(file_exists($this->getSavePath())){
			$currentVersion=file_get_contents($this->getSavePath());
		}

		$migrateFiles=[];
		$handleDir=opendir($this->getStagePath());
		while($file=readdir($handleDir)){
			if($file!="." && $file!=".." && preg_match('/^Version([0-9]+)\.php$/',$file,$match)){
				$migrateFiles[]=$match[1];
			}
		}

		$versionBefore=$currentVersion;
		sort($migrateFiles);
		foreach($migrateFiles as $migrateFile){
			try{
				if($migrateFile>$currentVersion){
				    $versionFile=$this->getStagePath().'/Version'.$migrateFile.'.php';
                    /** @noinspection PhpIncludeInspection */
                    require_once($versionFile);
					$versionClassName='Migrate\Version'.$migrateFile;
                    /**
                     * @var MigrateStage $versionObject
                     */
					$versionObject=new $versionClassName();

					$versionObject->up($this->container);
					$currentVersion=$migrateFile;
					file_put_contents($this->getSavePath(), $currentVersion);

				}

			}
			catch(\Exception $e){
				throw new \Exception("Error in version ".$migrateFile."(".$e->getLine().") [upgrade]: ".$e->getMessage());
			}
		}

		$out->write("Modified version ".$versionBefore." to ".$currentVersion);
		$out->flush();
	}

	/**
	 *
	 * @param OutputStream $out
	 * @throws \Exception
	 */
	public function downgradeOperation(OutputStream $out){
		$currentVersion=0;
		if(file_exists($this->getSavePath())){
			$currentVersion=file_get_contents($this->getSavePath());
		}

		$migrateFiles=array();
		$handleDir=opendir($this->getStagePath());
		while($file=readdir($handleDir)){
			if($file!="." && $file!=".." && preg_match('/^Version([0-9]+)\.php$/',$file,$match)){
				$migrateFiles[]=$match[1];
			}
		}
		$versionBefore=$currentVersion;
		rsort($migrateFiles);
		foreach($migrateFiles as $migrateFile){
			try{
				if($migrateFile<=$currentVersion){
				    $versionFile=$this->getStagePath().'/Version'.$migrateFile.'.php';
                    /** @noinspection PhpIncludeInspection */
                    require_once($versionFile);
					$versionClassName='Migrate\Version'.$migrateFile;
					$versionObject=new $versionClassName();

                    /**
                     * @var MigrateStage $versionObject
                     */
                    $versionObject->down($this->container);
					$currentVersion=$migrateFile;
					file_put_contents($this->getSavePath(), $currentVersion);

				}

			}
			catch(\Exception $e){
				throw new \Exception("Error in version ".$migrateFile."(".$e->getLine().") [downgrade]: ".$e->getMessage());
			}
		}

		$currentVersion=0;
		file_put_contents($this->getSavePath(), $currentVersion);

		$out->write("Modified version ".$versionBefore." to ".$currentVersion);
		$out->flush();
	}

	/**
	 *
	 * @return string
	 */
	private function getSavePath(){
		return $this->environment->getRootPath().$this->savePath;
	}

	/**
	 *
	 * @return string
	 */
	private function getStagePath(){
		return $this->environment->getRootPath().$this->stagePath;
	}

	/**
	 *
	 * @return string
	 */
	private function getPatternPath(){
		return $this->environment->getRootPath().$this->patternPath;
	}

}


<?php namespace Versatile\Support;

use Illuminate\Support\ServiceProvider;
use FormObject\Form;
use Versatile\View\CollectionFactoryChain;

class VersatileServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerFormObjectNamer();
    }

    /**
     * Register any application services.
     *
     * This service provider is a great spot to register your various container
     * bindings with the application. As you can see, we are registering our
     * "Registrar" implementation here. You can add your own bindings too!
     *
     * @return void
     */
    public function register()
    {
        $this->registerSyntaxParser();
        $this->registerPathIntrospector();
        $this->registerTitleIntrospector();
        $this->registerTypeIntrospector();
        $this->registerViewCollectionFactory();
        $this->registerBuilderViewCollectionFactory();
        $this->registerModelPresenter();
        $this->registerCriteriaBuilder();
        $this->registerSearchFactory();
    }

    protected function registerSyntaxParser()
    {

        $this->app->alias(
            'versatile.syntax-parser',
            'Versatile\Query\Contracts\SyntaxParser'
        );

        $this->app->bind('versatile.syntax-parser',function($app){
            return $app->make('Versatile\Query\SyntaxParser');
        });

    }

    protected function registerPathIntrospector()
    {

        $this->app->alias(
            'versatile.path-introspector',
            'Versatile\Introspection\Contracts\PathIntrospector'
        );

        $this->app->singleton('versatile.path-introspector',function($app){
            return $app->make('Versatile\Introspection\EloquentPathIntrospector');
        });

    }

    protected function registerTitleIntrospector()
    {

        $this->app->alias(
            'versatile.title-introspector',
            'Versatile\Introspection\Contracts\TitleIntrospector'
        );

        $this->app->singleton('versatile.title-introspector',function($app){
            return $app->make('Versatile\Introspection\EloquentTitleIntrospector');
        });

    }

    protected function registerTypeIntrospector()
    {

        $this->app->alias(
            'versatile.type-introspector',
            'Versatile\Introspection\Contracts\TypeIntrospector'
        );

        $this->app->singleton('versatile.type-introspector',function($app){
            return $app->make('Versatile\Introspection\EloquentTypeIntrospector');
        });

    }

    protected function registerViewCollectionFactory()
    {

        $this->app->alias(
            'versatile.view-collection-factory',
            'Versatile\View\Contracts\CollectionFactory'
        );

        $this->app->singleton('versatile.view-collection-factory',function($app) {
            return $app->make(CollectionFactoryChain::class);
            });

    }

    protected function registerBuilderViewCollectionFactory()
    {
        $this->app->afterResolving(CollectionFactoryChain::class, function ($factory) {
            $factory->add($this->app->make('Versatile\View\QueryBuilderFactory'));
            $factory->add($this->app->make('Versatile\View\SearchFactory'));
        });
    }

    protected function registerModelPresenter()
    {

        $this->app->alias(
            'versatile.model-presenter',
            'Versatile\View\Contracts\ModelPresenter'
        );

        $this->app->singleton('versatile.model-presenter', function($app) {
            return $app->make('Versatile\View\ModelPresenterRegistry');
        });

        $this->app->resolving('versatile.model-presenter', function($presenter) {

            $presenter->provideId('Illuminate\Database\Eloquent\Model', function($object){
                return $object->getKey();
            });

            $presenter->provideShortName('Illuminate\Database\Eloquent\Model', function($object, $view){

                if (method_exists($object, 'shortName')) {
                    return $object->shortName($view);
                }

                if (isset($object->title)) {
                    return $object->title;
                }

                if (isset($object->name)) {
                    return $object->name;
                }

                return class_basename($object) . ' #' .  $object->getKey();
            });
        });

    }

    protected function registerCriteriaBuilder()
    {
        $this->app->alias(
            'versatile.criteria-builder',
            'Versatile\Search\Contracts\CriteriaBuilder'
        );

        $this->app->singleton('versatile.criteria-builder', function($app) {
            return $app->make('Versatile\Search\FlatCriteriaBuilder');
        });
    }

    protected function registerSearchFactory()
    {
        $this->app->alias(
            'versatile.search-factory',
            'Versatile\Search\Contracts\SearchFactory'
        );

        $this->app->singleton('versatile.search-factory', function($app) {
            return $app->make('Versatile\Search\ProxySearchFactory');
        });

        $this->app->resolving('versatile.search-factory', function($factory) {
            return $factory->forModelClass('Illuminate\Database\Eloquent\Model', function($criteria) {

                $modelClass = $criteria->modelClass();

                $builder = $this->app->make('Versatile\Query\Builder', ['model' => new $modelClass]);

                return $this->app->make('Versatile\Search\BuilderSearch',[
                    'builder' => $builder,
                    'criteria' => $criteria
                ]);
            });
        });

    }

    protected function registerFormObjectNamer()
    {

        if (!class_exists('FormObject\Form', false)) {
            return;
        }

        Form::provideAdditionalNamer(function($chain) {
            $chain->append($this->getTitleIntrospectorNamer());
        });

    }

    protected function getTitleIntrospectorNamer()
    {
        return $this->app->make('Versatile\Support\FormObject\TitleIntrospectorNamer');
    }

}


<?php

namespace OpenOrchestra\ModelBundle\DataFixtures\MongoDB;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use OpenOrchestra\ModelBundle\Document\RouteDocument;
use OpenOrchestra\ModelInterface\DataFixtures\OrchestraFunctionalFixturesInterface;

/**
 * Class LoadRouteDocumentData
 */
class LoadRouteDocumentData implements FixtureInterface, OrchestraFunctionalFixturesInterface
{
    /**
     * Load data fixtures with the passed EntityManager
     *
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $patterns = array(
            'foo',
            'foo/{bar}',
            'foo/bar',
            'baz/bar',
            'foo/{bar}/baz',
            'zero/one/two/three/four/five/six/{seven}/eight/nine/ten/eleven',
            'zero/one/two/three/four/five/six/{seven}/eight/nine/ten/{eleven}/twelve',
            'zero/one/two/three/four/five/six/{seven}/eight/nine/ten/eleven/twelve',
            'zero/one/two/three/four/five/six/{seven}/eight/nine/ten/eleven/{twelve}'
        );

        foreach ($patterns as $pattern) {
            $route = new RouteDocument();
            $route->setName($pattern);
            $route->setPattern($pattern);

            $manager->persist($route);
        }

        $manager->flush();
    }
}


<?php

namespace Monolyth\Disclosure;

use Psr\Container\ContainerInterface;
use Psr\Container\Exception\NotFoundExceptionInterface;
use ReflectionClass;
use ReflectionFunction;

/**
 * Main container class for Disclosure. All instances share a global pool of
 * registered dependencies.
 */
class Container implements ContainerInterface
{
    private static $map = [];
    private $delegate;

    /**
     * Constructor. Optionally pass a delegate container to use. Note that
     * delegates are tried before the default container. IF the delegate lookup
     * fails, Disclosure will try the default before giving up.
     *
     * @param Psr\Container\ContainerInterface $delegate Optional delegate
     *  container to use.
     */
    public function __construct(ContainerInterface $delegate = null)
    {
        if (isset($delegate)) {
            $this->delegate = $delegate;
        }
    }

    /**
     * Resolve the dependency identified by `$key`. Note `$key` is not type
     * hinted as it would violate the `Psr\Container\ContainerInterface`.
     *
     * @param string $key The unique identifier for the dependency.
     * @return mixed Whatever was stored under $key.
     * @throws Disclosure\NotFoundException if no such $key was registered.
     */
    public function get($key)
    {
        if (!array_key_exists($key, static::$map)) {
            throw new NotFoundException($key);
        }
        if (static::$map[$key] instanceof ReflectionFunction) {
            static::$map[$key] = static::$map[$key]->invoke($this);
        }
        return static::$map[$key];
    }

    /**
     * Checks if a dependency exists identified by $key. Note that this also
     * resolves the dependency internally, so any dependencies on $key must also
     * be resolvable for this to return true.
     *
     * Note `$key` is not type hinted as it would violate the
     * `Psr\Container\ContainerInterface`.
     *
     * @param string $key The unique identifier for the dependency.
     * @return bool True if $key identifies a known dependency, else false.
     */
    public function has($key) : bool
    {
        try {
            $this->get($key);
            return true;
        } catch (NotFoundExceptionInterface $e) {
            return false;
        }
    }

    /**
     * Register a group of dependencies defined in the callable. Each referenced
     * argument should be assigned its designated value when invoked. Note that
     * invocation takes place only when a dependency is retrieved.
     *
     * @param callable $inject A callable associating values with keys.
     * @return void
     */
    public function register(callable $inject) : void
    {
        $reflection = new ReflectionFunction($inject);
        $parameters = $reflection->getParameters();
        foreach ($parameters as $parameter) {
            $key = $parameter->name;
            $getter = function ($c) use ($reflection, $parameters, $key) {
                if (isset($c->delegate)) {
                    try {
                        return $c->delegate->get($key);
                    } catch (NotFoundExceptionInterface $e) {
                        // That's fine, we'll try our own container next.
                    }
                }
                $args = [];
                foreach ($parameters as $param) {
                    if (!$param->isPassedByReference()) {
                        $args[] = $c->get($param->name);
                    } else {
                        ${$param->name} = null;
                        $args[$param->name] =& ${$param->name};
                    }
                }
                $reflection->invokeArgs($args);
                foreach ($args as $found => $value) {
                    if (!is_numeric($found) && $found == $key) {
                        $c::$map[$found] = $value;
                    }
                }
                if (array_key_exists($key, $args)) {
                    return $args[$key];
                }
                throw new NotFoundException($key);
            };
            static::$map[$key] = new ReflectionFunction($getter);
        }
    }
}