<?php
namespace Rentgen\Schema;

use Rentgen\Database\Connection\Connection;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

abstract class Command
{
    protected $connection;
    protected $dispatcher;

    /**
     * Execute query.
     *
     * @return integer
     */
    public function execute()
    {
        $this->preExecute();
        $result = $this->connection->execute($this->getSql());
        $this->postExecute();

        return $result;
    }

    /**
     * Set an event dispatcher.
     *
     * @param EventDispatcher $dispatcher EventDispatcher instance.
     *
     * @return Command
     */
    public function setEventDispatcher(EventDispatcherInterface $dispatcher)
    {
        $this->dispatcher = $dispatcher;

        return $this;
    }

    /**
     * Set the connection.
     *
     * @param Connection $connection Connection instance.
     *
     * @return Command
     */
    public function setConnection(Connection $connection)
    {
        $this->connection = $connection;

        return $this;
    }

    /**
     * Execute actions before execute query.
     *
     * @return void
     */
    protected function preExecute()
    {
    }

    /**
     * Execute actions after execute query.
     *
     * @return void
     */
    protected function postExecute()
    {
    }

    /**
     * Get sql query to execute.
     *
     * @return string
     */
    abstract public function getSql();
}


<?php
namespace Rentgen\Schema\Manipulation;

use Rentgen\Schema\Command;
use Rentgen\Database\Constraint\ConstraintInterface;
use Rentgen\Database\Constraint\ForeignKey;
use Rentgen\Database\Constraint\Unique;
use Rentgen\Database\Table;

class AddConstraintCommand extends Command
{
    private $constraint;

    /**
     * Set a constraint.
     *
     * @param ConstraintInterface $constraint A constraint instance.
     *
     * @return AddConstraintCommand
     */
    public function setConstraint(ConstraintInterface $constraint)
    {
        $this->constraint = $constraint;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSql()
    {
        if ($this->constraint instanceof ForeignKey) {
            return sprintf('ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) MATCH SIMPLE ON UPDATE %s ON DELETE %s;'
                , $this->constraint->getTable()->getQualifiedName()
                , $this->constraint->getName()
                , implode(',', $this->constraint->getColumns())
                , $this->constraint->getReferencedTable()->getQualifiedName()
                , implode(',', $this->constraint->getReferencedColumns())
                , $this->constraint->getUpdateAction()
                , $this->constraint->getDeleteAction()
            );
        }
        if ($this->constraint instanceof Unique) {
            return sprintf('ALTER TABLE %s ADD CONSTRAINT %s UNIQUE (%s);'
                , $this->constraint->getTable()->getQualifiedName()
                , $this->constraint->getName()
                , implode(',', $this->constraint->getColumns())
            );
        }
    }
}


<?php
namespace Rentgen\Schema\Manipulation;

use Rentgen\Schema\Command;
use Rentgen\Database\Index;

class CreateIndexCommand extends Command
{
    private $index;

    /**
     * Sets a index
     *
     * @param Index $index The index instance.
     *
     * @return AddColumnCommand
     */
    public function setIndex(Index $index)
    {
        $this->index = $index;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSql()
    {
        $sql = sprintf('CREATE INDEX %s ON %s (%s);'
            , $this->index->getName()
            , $this->index->getTable()->getQualifiedName()
            , implode(',', $this->index->getColumns()));

        return $sql;
    }
}


<?php

namespace Igorwanbarros\BaseLaravel\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class BaseModel extends Model
{
    protected static $informationSchema;

    use SoftDeletes;

    public function __construct(array $attributes = [])
    {
        $schema = $this->_initInformationSchema($this->getTable());

        foreach ($schema as $column) {
            if (isset($column->COLUMN_NAME) && $column->COLUMN_NAME != $this->getDeletedAtColumn()) {
                $this->fillable[] = $column->COLUMN_NAME;
            }
        }

        parent::__construct($attributes);
    }

    public static function getSchema()
    {
        if (env('DB_CONNECTION') != 'mysql') {
            return [];
        }

        if (!isset(static::$informationSchema[get_called_class()])) {
            return static::_initInformationSchema();
        }

        return static::$informationSchema[get_called_class()];
    }

    protected static function _initInformationSchema($table = null)
    {
        if (!$table) {
            $static = new static;
            $table = $static->getTable();
        }

        $schema = DB::table('information_schema.columns')
            ->where('table_name', '=', $table)
            ->where('table_schema', '=', env('DB_DATABASE'))
            ->get();

        static::$informationSchema[get_called_class()] = $schema;

        return $schema;
    }

    /**
     * @param array $data
     *
     * @return $this
     */
    public function saveOrUpdate(array $data = [])
    {
        if (isset($data['id']) && $data['id'] > 0) {
            $model = $this->find($data['id'])->fill($data);
            $model->update();

            return $model;
        }

        return $this->create($data);
    }

    /**
     * @return string
     */
    public function getPrimaryKey()
    {
        return $this->primaryKey;
    }
}


<?php
namespace Rentgen\Schema\Manipulation;

use Rentgen\Database\Index;
use Rentgen\Schema\Command;

class DropIndexCommand extends Command
{
    private $index;

    /**
     * Sets a index
     *
     * @param Index $index The index instance.
     *
     * @return DropColumnCommand
     */
    public function setIndex(Index $index)
    {
        $this->index = $index;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSql()
    {
        $sql = sprintf('DROP INDEX %s.%s;'
            , $this->index->getTable()->getSchema()->getName()
            , $this->index->getName());

        return $sql;
    }
}


<?php

namespace Rentgen\Database;

use Rentgen\Database\Constraint\ConstraintInterface;

/**
 * @author Arek Jaskólski <arek.jaskolski@gmail.com>
 */
class Table implements DatabaseObjectInterface
{
    private $name;
    private $schema;
    private $description;
    protected $columns = array();
    protected $constraints = array();

    /**
     * Constructor.
     *
     * @param string $name  Table name.
     * @param Schema $schem Schema instance.
     */
    public function __construct($name, Schema $schema = null)
    {
        $this->name = $name;
        $this->schema = null === $schema ? new Schema() : $schema;
    }

    /**
     * Get table name.
     *
     * @return string Table name.
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get qualified name (schema name + table name)
     *
     * @return string Qualified name.
     */
    public function getQualifiedName()
    {
        return $this->schema->getName() . '.' .$this->name;
    }

    /**
     * Add column to table.
     *
     * @param Column $column Column instance.
     *
     * @return Table Table instance.
     */
    public function addColumn(Column $column)
    {
        $this->columns[] = $column;

        return $this;
    }

    /**
     * Get columns of table.
     *
     * @return Column[] Array of Column instances.
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * Get column of table.
     *
     * @param string $name Column name.
     *
     * @return Column Column instance.
     */
    public function getColumn($name)
    {
        foreach ($this->columns as $column) {
            if ($column->getName() == $name) {
                return $column;
            }
        }

        return null;
    }

    /**
     * Add contraint to table.
     *
     * @param ConstraintInterface $constraint Instance of class implements ConstraintInterface.
     *
     * @return Table Table instance.
     */
    public function addConstraint(ConstraintInterface $constraint)
    {
        $constraint->setTable($this);
        $this->constraints[] = $constraint;

        return $this;
    }

    /**
     * Get constraints of table.
     *
     * @return ConstraintInterface[] Array of instances implement ConstraintInterface.
     */
    public function getConstraints()
    {
        return $this->constraints;
    }

    /**
     * Set schema name.
     *
     * @param string $name Schama name.
     */
    public function setSchema(Schema $schema)
    {
        $this->schema = $schema;
    }

    public function getSchema()
    {
        return $this->schema;
    }

    /**
     * Set table description.
     *
     * @param string $description Table description.
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * Get table description.
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}


<?php

namespace Rentgen\Database\Connection;

class ConnectionConfig implements ConnectionConfigInterface
{
    private $adapter;
    private $username;
    private $password;

    /**
     * Constructor.
     *
     * @param array $config Array config.
     */
    public function __construct(array $config = array())
    {
        $this->parseConfiguration($config);
    }

    /**
     * {@inheritdoc}
     */
    public function changeEnvironment($environment)
    {
        $this->currentEnvironment = $environment;
    }

    /**
     * {@inheritdoc}
     */
    public function getUsername()
    {
        return $this->username[$this->currentEnvironment];
    }

    /**
     * {@inheritdoc}
     */
    public function getPassword()
    {
        return $this->password[$this->currentEnvironment];
    }

    /**
     * {@inheritdoc}
     */
    public function getDsn()
    {
        return $this->dsn[$this->currentEnvironment];
    }

    /**
     * Get database adapter.
     *
     * @return string
     */
    public function getAdapter()
    {
        return $this->adapter[$this->currentEnvironment];
    }

    /**
     * Parse configuration.
     *
     * @param array $config
     * @return void
     */
    private function parseConfiguration(array $config)
    {
        $this->currentEnvironment = 'dev';
        foreach($config as $environment => $connection) {
            if (isset($connection['dsn'])) {
                $this->dsn[$environment]  = $connection['dsn'];
            } else {
                $this->dsn[$environment]= sprintf('pgsql:host=%s; port=%s; dbname=%s;'
                    , $connection['host']
                    , $connection['port']
                    , $connection['database']);

            }
            //$this->adapter[$environment] = $connection['adapter'];
            $this->username[$environment] = $connection['username'];
            $this->password[$environment] = $connection['password'];
        }
    }
}


<?php
/**
 * Monadic Attributes
 *
 * @author    Ashley Kitson
 * @copyright Ashley Kitson, 2017, UK
 * @license   BSD-3-Clause See LICENSE.md
 */
namespace Chippyash\Attributes;

use Chippyash\Attributes\Exceptions\AttributesException;
use Chippyash\Type\String\StringType;

/**
 * Trait Attribution
 *
 * Trait implementing Attributal interface.
 * Declare the client class to use the Attributal interface if required
 */
trait Attribution
{
    /**
     * @var AttributeMap
     */
    protected $attributes;

    /**
     * Get an attribute
     *
     * @param StringType $name name of attribute
     *
     * @return Attribute
     *
     * @throws AttributesException Thrown if named attribute does not exists
     */
    public function getA(StringType $name)
    {
        if (!$this->hasA($name)) {
            throw new AttributesException("Attribute: {$name} does not exist");
        }

        return $this->attributes[$name()];
    }

    /**
     * @param StringType $name Name of attribute to check for
     *
     * @return bool
     */
    public function hasA(StringType $name)
    {
        return isset($this->attributes[$name()]);
    }
}


<?php
/**
 * Cache system
 */

namespace Datalaere\PHPFilesystem;

class Cache
{
    public $url;
    protected $_dir;
    protected $_time;
    protected $_ext;
    protected $_ignoreList;
    private $_page;
    private $_file;

    /**
     * Directory to cache files in (keep outside web root)
     */
    public function setDir($directory)
    {
        $this->_dir = $directory;
    }

    /**
     * Seconds to cache files for
     */
    public function setTime($time)
    {
        $this->_time = $time;
    }

    /**
     * Extension to give cached files (usually cache, htm, txt)
     */
    public function setExt($extension)
    {
        $this->_ext = $extension;
    }

    /**
     * Ignore list of pages NOT to cache
     */
    public function setIgnore($params = array())
    {
        $this->_ignoreList = $params;
    }

    /**
     * Set the public, current url
     */
    public function setUrl($current_url)
    {
        $this->url = $current_url;
    }

    /**
     * Start caching BEFORE script
     */
    public function start()
    {
        if (!isset($this->_dir)) {
            return false;
        }

        $this->_page = $this->url; // Requested page
        $this->_file = $this->_dir . md5($this->_page) . '.' . $this->_ext; // Cache file to either load or create

        $ignore_page = false;

        for ($i = 0; $i < count($this->_ignoreList); $i++) {
            $ignore_page = (strpos($this->_page, $this->_ignoreList[$i]) !== false) ? true : $ignore_page;
        }

        $cachefile_created = (file_exists($this->_file) && ($ignore_page === false)) ? filemtime($this->_file) : 0;
        clearstatcache();

        // Show file from cache if still valid
        if (time() - $this->_time < $cachefile_created) {
            ob_start('ob_gzhandler');
            readfile($this->_file);
            //$time_end = microtime(true);
            //$time = $time_end - $time_start;
            //echo '<!-- generated in ' . $time . ' cached page - '.date('l jS \of F Y h:i:s A', filemtime($cachefile)).', Page : '.$page.' -->';
            ob_end_flush();
            exit();
        }

        // If we're still here, we need to generate a cache file
        //Turn on output buffering with gzip compression.
        ob_start('ob_gzhandler');
    }

    /**
     * Run stop AFTER script
     */
    public function stop()
    {
        // Now the script has run, generate a new cache file
        $fp = @fopen($this->_file, 'w');

        // save the contents of output buffer to the file
        fwrite($fp, ob_get_contents());
        fclose($fp);

        ob_end_flush();
    }

    public function clear()
    {
        if ($handle = opendir($this->_dir)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != '.' and $file != '..') {
                    echo $file . ' deleted.<br>';
                    unlink($this->_dir . '/' . $file);
                }
            }
            closedir($handle);
        }
        // optional curl
        //curl http://www.your_domain.com/empty_caching.php >/dev/null 2>&1
    }
}


<?php
namespace Igorwanbarros\BaseLaravel\Providers;

use Igorwanbarros\BaseLaravel\Toastr\Toastr;
use Illuminate\Support\ServiceProvider;

class ToastrServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/toastr.php' => base_path('config/toastr.php'),
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('toastr', function ($app) {
            return new Toastr($app->session, $app->config);
        });
    }

    /**
     * Get the services provider by the provider
     *
     * @return array
     */
    public function provides()
    {
        return ['toastr'];
    }
}


<?php

namespace Rentgen\Helper;

class ObjectHelper
{
    /**
     * Gets a class name without a namespace.
     *
     * @param object $object An object.
     *
     * @return string
     */
    public static function getClassNameWithoutNamespace($object)
    {
        $className = get_class($object);
        if (preg_match('@\\\\([\w]+)$@', $className, $matches)) {
            $className = $matches[1];
        }

        return $className;
    }
}


<?php

namespace Rentgen\Database\Constraint;

use Rentgen\Database\Table;

class Unique implements ConstraintInterface
{
    private $columns;
    private $table;

    /**
     * Constructor.
     *
     * @param array|string $columns Column names.
     * @param datatype     $table   Table instance.
     */
    public function __construct($columns, Table $table = null)
    {
        $this->table = $table;
        $this->columns = is_string($columns) ? array($columns) : $columns;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        $tableName = $this->table->getName();
        $columnsAsString = implode('_', $this->columns);

        return $tableName . '_' . $columnsAsString . '_key';
    }

    /**
     * {@inheritdoc}
     */

    public function getTable()
    {
        return $this->table;
    }

    /**
     * Set table instance.
     *
     * @param Table $table Table instance.
     *
     * @return PrimaryKey Self.
     */
    public function setTable(Table $table)
    {
        $this->table = $table;

        return $this;
    }

   /**
     * Get column names.
     *
     * @return array Column names.
     */
    public function getColumns()
    {
        return $this->columns;
    }
}


<?php
namespace Rentgen\Schema\Manipulation;

use Rentgen\Schema\Command;
use Rentgen\Database\Table;
use Rentgen\Database\Column;

class DropColumnCommand extends Command
{
    private $column;

    /**
     * Set column to drop from a table.
     *
     * @param Column $column Column instance.
     *
     * @return DropColumnCommand Self.
     */
    public function setColumn(Column $column)
    {
        $this->column = $column;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSql()
    {
        $sql = sprintf('ALTER TABLE %s DROP COLUMN %s;'
            , $this->column->getTable()->getQualifiedName()
            , $this->column->getName()
        );

        return $sql;
    }
}


<?php
namespace Rentgen\Schema\Manipulation;

use Rentgen\Schema\Command;
use Rentgen\Database\Table;
use Rentgen\Database\Column;
use Rentgen\Database\Column\CustomColumn;
use Rentgen\Database\Constraint\ForeignKey;
use Rentgen\Database\Constraint\PrimaryKey;
use Rentgen\Database\Constraint\Unique;
use Rentgen\Event\TableEvent;
use Rentgen\Schema\ColumnTypeMapper;
use Rentgen\Schema\Escapement;

class CreateTableCommand extends Command
{
    private $table;

    /**
     * Sets a table.
     *
     * @param Table $table The table instance.
     *
     * @return CreateTableCommand
     */
    public function setTable(Table $table)
    {
        $this->table = $table;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSql()
    {
        $escapement = new Escapement();

        $sql = sprintf('CREATE TABLE %s(%s);'
            , $escapement->escape($this->table->getQualifiedName())
            , $this->getColumnsSql() . $this->getConstraintsSql());

        $tableDescription = $this->table->getDescription();
        if (!empty($tableDescription)) {
        $sql .= sprintf("COMMENT ON TABLE %s IS '%s';",
            $escapement->escape($this->table->getQualifiedName()), $tableDescription);
        }
        $sql .= $this->getColumnComments();

        return $sql;
    }

    /**
     * Gets constraints query.
     *
     * @return string
     */
    private function getConstraintsSql()
    {
        $sql = '';
        foreach ($this->table->getConstraints() as $constraint) {
            $sql .= ',';
            if ($constraint instanceof PrimaryKey) {
                $sql .= (string) $constraint ;
            } elseif ($constraint instanceof ForeignKey) {
                $sql .= sprintf('CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) MATCH SIMPLE ON UPDATE %s ON DELETE %s'
                    , $constraint->getName()
                    , implode(',', $constraint->getColumns())
                    , $constraint->getReferencedTable()->getQualifiedName()
                    , implode(',', $constraint->getReferencedColumns())
                    , $constraint->getUpdateAction()
                    , $constraint->getDeleteAction());
            } elseif ($constraint instanceof Unique) {
                $sql .= sprintf('CONSTRAINT %s UNIQUE (%s)'
                    , $constraint->getName()
                    , implode(',', $constraint->getColumns()));
            }
        }

        return rtrim($sql, ',');
    }

    /**
     * Gets columns query.
     *
     * @return string
     */
    private function getColumnsSql()
    {
        $columnTypeMapper = new ColumnTypeMapper();

        foreach ($this->table->getConstraints() as $constraint) {
            if ($constraint instanceof PrimaryKey) {
                $primaryKey = $constraint;
            }
        }
        if (!isset($primaryKey)) { // TODO find better solution
            $primaryKey = new PrimaryKey();
            $primaryKey->setTable($this->table);
            $this->table->addConstraint($primaryKey);
        }

        $sql = '';
        if (!$primaryKey->isMulti() && $primaryKey->isAutoCreateColumn()) {
            $sql = sprintf('%s %s NOT NULL,', $primaryKey->getColumns(), $primaryKey->isAutoIncrement() ? 'serial' : 'integer');
        }
        foreach ($this->table->getColumns() as $column) {
            if ($column instanceof CustomColumn) {
                $columnType = $column->getType();
            } else {
                $columnType = $columnTypeMapper->getNative($column->getType());
            }

            $sql .= sprintf('%s %s%s %s %s,'
                , $column->getName()
                , $columnType
                , $this->getTypeConstraints($column)
                , $column->isNotNull() ? 'NOT NULL' : ''
                , null === $column->getDefault() ? '' : 'DEFAULT'. ' ' . $this->addQuotesIfNeeded($column, $column->getDefault())
            );
        }

        return rtrim($sql, ',');
    }

    /**
     * Gets comments for columns.
     *
     * @return string
     */
    private function getColumnComments()
    {
        $escapement = new Escapement();
        $comments = '';
        foreach ($this->table->getColumns() as $column) {
             $columnDescription = $column->getDescription();
             if (!empty($columnDescription)) {
                $comments .= sprintf("COMMENT ON COLUMN %s.%s IS '%s';",
                    $escapement->escape($this->table->getQualifiedName()),
                    $escapement->escape($column->getName()),
                    $columnDescription);
             }
        }

        return $comments;
    }

    /**
     * {@inheritdoc}
     */
    protected function preExecute()
    {
        $this->dispatcher->dispatch('table.create', new TableEvent($this->table, $this->getSql()));
    }

    private function addQuotesIfNeeded(Column $column, $value)
    {
        return in_array($column->getType(), ['string', 'text']) ? sprintf("'%s'", $value) : $value;
    }

    private function getTypeConstraints(Column $column)
    {
        $typeConstraints = '';
        switch ($column->getType()) {
            case 'string':
                if ($column->getLimit()) {
                    $typeConstraints = sprintf('(%s)', $column->getLimit());
                }
                break;
            case 'decimal':
                if ($column->getPrecision()) {
                    $typeConstraints = sprintf('(%s, %s)', $column->getPrecision(), $column->getScale());
                }
                break;
        }

        return $typeConstraints;
    }
}


<?php
namespace Omnipay\Ecopayz\Message;

use Omnipay\Common\Exception\InvalidRequestException;
use Omnipay\Common\Exception\InvalidResponseException;

/**
 * Ecopayz Fetch Transaction Request
 *
 * @author    Alexander Fedra <contact@dercoder.at>
 * @copyright 2015 DerCoder
 * @license   http://opensource.org/licenses/mit-license.php MIT
 * @version   2.0.3 Ecopayz API Specification
 */
class FetchTransactionRequest extends AbstractRequest
{
    /**
     * Get the data for this request.
     *
     * @throws InvalidRequestException
     * @return string                  request data
     */
    public function getData()
    {
        $this->validate(
            'merchantId',
            'merchantPassword'
        );

        $document = new \DOMDocument('1.0', 'utf-8');
        $document->formatOutput = false;

        $envelope = $document->appendChild(
            $document->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'soapenv:Envelope')
        );

        $envelope->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $envelope->setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
        $envelope->setAttribute('xmlns:q0', 'http://www.ecocard.com/merchantAPI/');

        $body = $envelope->appendChild(
            $document->createElement('soapenv:Body')
        );

        if ($transactionReference = $this->getTransactionReference()) {

            $query = $body->appendChild(
                $document->createElement('q0:QueryBySVSTransactionID')
            );

            $request = $query->appendChild(
                $document->createElement('q0:QueryBySVSTransactionIDRequest')
            );

            $request->appendChild(
                $document->createElement('q0:MerchantID', $this->getMerchantId())
            );

            $request->appendChild(
                $document->createElement('q0:MerchantPassword', $this->getMerchantPassword())
            );

            $request->appendChild(
                $document->createElement('q0:SVSTxID', $transactionReference)
            );

        } elseif ($transactionId = $this->getTransactionId()) {

            $query = $body->appendChild(
                $document->createElement('q0:QueryByCustomerTransactionID')
            );

            $request = $query->appendChild(
                $document->createElement('q0:QueryByCustomerTransactionIDRequest')
            );

            $request->appendChild(
                $document->createElement('q0:MerchantID', $this->getMerchantId())
            );

            $request->appendChild(
                $document->createElement('q0:MerchantPassword', $this->getMerchantPassword())
            );

            $request->appendChild(
                $document->createElement('q0:TxID', $transactionId)
            );

        } else {

            throw new InvalidRequestException('The transactionId or transactionReference parameter is required');

        }

        return $document->saveXML();
    }

    /**
     * Send the request with specified data
     *
     * @param  mixed                    $data The data to send
     * @throws InvalidResponseException
     * @throws InvalidRequestException
     * @return FetchTransactionResponse
     */
    public function sendData($data)
    {
        if (strpos($data, 'QueryBySVSTransactionID') !== false) {

            $headers = array(
                'Content-Type' => 'text/xml; charset=utf-8',
                'SOAPAction' => 'http://www.ecocard.com/merchantAPI/QueryBySVSTransactionID'
            );

            $httpRequest = $this->httpClient->createRequest('POST', $this->getEndpoint(), $headers, $data);
            $httpResponse = $httpRequest->send();
            $xmlResponse = $httpResponse->xml()
                ->children('http://schemas.xmlsoap.org/soap/envelope/')
                ->children('http://www.ecocard.com/merchantAPI/');

            if (!isset($xmlResponse->QueryBySVSTransactionIDResponse)) {
                throw new InvalidResponseException('Missing element in XML response');
            }

            if (!isset($xmlResponse->QueryBySVSTransactionIDResponse->TransactionResponse)) {
                throw new InvalidResponseException('Missing element in XML response');
            }

            return new FetchTransactionResponse(
                $this,
                $xmlResponse
                    ->QueryBySVSTransactionIDResponse
                    ->TransactionResponse
            );

        } elseif (strpos($data, 'QueryByCustomerTransactionID') !== false) {

            $headers = array(
                'Content-Type' => 'text/xml; charset=utf-8',
                'SOAPAction' => 'http://www.ecocard.com/merchantAPI/QueryByCustomerTransactionID'
            );

            $httpRequest = $this->httpClient->createRequest('POST', $this->getEndpoint(), $headers, $data);
            $httpResponse = $httpRequest->send();
            $xmlResponse = $httpResponse->xml()
                ->children('http://schemas.xmlsoap.org/soap/envelope/')
                ->children('http://www.ecocard.com/merchantAPI/');

            if (!isset($xmlResponse->QueryByCustomerTransactionIDResponse)) {
                throw new InvalidResponseException('Missing element in XML response');
            }

            if (!isset($xmlResponse->QueryByCustomerTransactionIDResponse->TransactionResponse)) {
                throw new InvalidResponseException('Missing element in XML response');
            }

            return new FetchTransactionResponse(
                $this,
                $xmlResponse
                    ->QueryByCustomerTransactionIDResponse
                    ->TransactionResponse
            );

        } else {

            throw new InvalidRequestException('The transactionId or transactionReference parameter is required');

        }
    }
}


<?php
namespace Samurai\Project\Composer;

use Balloon\Balloon;
use Balloon\Factory\BalloonFactory;
use InvalidArgumentException;
use Samurai\Project\Project;
use TRex\Cli\Executor;

/**
 * Class Composer
 * @package Samurai\Project\Composer
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class Composer
{
    /**
     * @var Balloon[]
     */
    private $composerConfigManager = [];

    /**
     * @var Executor
     */
    private $executor;

    /**
     * @var BalloonFactory
     */
    private $balloonFactory;

    /**
     * @param Executor $executor
     * @param BalloonFactory $balloonFactory
     */
    public function __construct(Executor $executor, BalloonFactory $balloonFactory)
    {
        $this->setExecutor($executor);
        $this->setBalloonFactory($balloonFactory);
    }

    /**
     * @param Project $project
     * @param array $options
     * @return int
     */
    public function createProject(Project $project, array $options = array())
    {
        if(!$project->getBootstrap()){
            throw new InvalidArgumentException('The bootstrap of the project is not defined');
        }

        return $this->execute(
            trim(
                sprintf(
                    'composer create-project --prefer-dist %s %s %s',
                    $project->getBootstrap()->getPackage(),
                    $project->getDirectoryPath() ? '"' . $project->getDirectoryPath() .'"' : '',
                    $project->getBootstrap()->getVersion()
                )
            )
            .$this->mapOptions($options)
        );
    }

    /**
     * @param string $name
     * @param string $version
     * @param bool $isGlobal
     * @param array $options
     * @return int
     */
    public function requirePackage($name, $version = '', $isGlobal = false, array $options = array())
    {
        $global = $isGlobal ? 'global ' : '';
        return $this->execute(
            trim(sprintf('composer %srequire %s %s', $global, $name, $version))
            . $this->mapOptions($options)
        );
    }

    /**
     * @param $name
     * @param bool $isGlobal
     * @param array $options
     * @return int
     */
    public function updatePackage($name, $isGlobal = false, array $options = array())
    {
        $global = $isGlobal ? 'global ' : '';
        return $this->execute(
            trim(sprintf('composer %supdate %s', $global, $name))
            . $this->mapOptions($options)
        );
    }

    /**
     * @param string $name
     * @param bool $isGlobal
     * @param array $options
     * @return int
     */
    public function removePackage($name, $isGlobal = false, array $options = array())
    {
        $global = $isGlobal ? 'global ' : '';
        return $this->execute(
            trim(sprintf('composer %sremove %s', $global, $name))
            . $this->mapOptions($options)
        );
    }

    /**
     * @return string
     */
    public function getHomePath()
    {
        return $this->getExecutor()->read('composer config home --global --absolute');
    }

    /**
     * @param $cwd
     * @return string
     */
    public function getConfigPath($cwd = '')
    {
        if($cwd){
            $cwd = rtrim($cwd, '/') . '/';
        }
        return  $cwd . 'composer.json';
    }

    /**
     * @param string $cwd
     * @return array
     */
    public function getConfig($cwd = '')
    {
        return $this->getComposerConfigManager($cwd)->getAll();
    }

    /**
     * @param array $config
     * @param string $cwd
     * @return int
     */
    public function setConfig(array $config, $cwd = '')
    {
        return $this->getComposerConfigManager($cwd)->set($config);
    }

    /**
     * @param string $cwd
     * @return int
     */
    public function flushConfig($cwd = '')
    {
        return $this->getComposerConfigManager($cwd)->flush();
    }

    /**
     * @param string $cwd
     * @return int
     */
    public function validateConfig($cwd = '')
    {
        return $this->execute('composer validate', $cwd);
    }

    /**
     * @param string $cwd
     * @return int
     */
    public function dumpAutoload($cwd = '')
    {
        return $this->execute('composer dump-autoload', $cwd);
    }

    /**
     * @param array $options
     * @return string
     */
    private function mapOptions(array $options)
    {
        $result = '';
        foreach($options as $option => $value){
            $result .= ' --' . $option . '=' . $value;
        }
        return $result;
    }

    /**
     * Getter of $composerConfigManager
     *
     * @param $cwd
     * @return Balloon
     */
    public function getComposerConfigManager($cwd)
    {
        if(empty($this->composerConfigManager[$cwd])){
            $this->composerConfigManager[$cwd] = $this->getBalloonFactory()->create($this->getConfigPath($cwd));
        }
        return $this->composerConfigManager[$cwd];
    }

    /**
     * Getter of $executor
     *
     * @return Executor
     */
    private function getExecutor()
    {
        return $this->executor;
    }

    /**
     * Setter of $executor
     *
     * @param Executor $executor
     */
    private function setExecutor(Executor $executor)
    {
        $this->executor = $executor;
    }

    /**
     * Getter of $balloonFactory
     *
     * @return BalloonFactory
     */
    private function getBalloonFactory()
    {
        return $this->balloonFactory;
    }

    /**
     * Setter of $balloonFactory
     *
     * @param BalloonFactory $balloonFactory
     */
    private function setBalloonFactory(BalloonFactory $balloonFactory)
    {
        $this->balloonFactory = $balloonFactory;
    }

    /**
     * @param string $command
     * @param string $cwd
     * @return int
     */
    private function execute($command, $cwd = null)
    {
        $pipes = [];
        return $this->getExecutor()->flush($command, [STDIN, STDOUT, STDERR], $pipes, $cwd);
    }
}


<?php
namespace Omnipay\Ecopayz\Message;

use Omnipay\Common\Exception\InvalidResponseException;

/**
 * Ecopayz Payout Request
 *
 * @author    Alexander Fedra <contact@dercoder.at>
 * @copyright 2015 DerCoder
 * @license   http://opensource.org/licenses/mit-license.php MIT
 * @version   2.0.3 Ecopayz API Specification
 */
class PayoutRequest extends AbstractRequest
{
    /**
     * Get the Client Account Number
     *
     * Client account number (who receive funds) in the ecoPayz system.
     *
     * @return string client account number
     */
    public function getClientAccountNumber()
    {
        return $this->getParameter('clientAccountNumber');
    }

    /**
     * Set the Client Account Number
     *
     * Client account number (who receive funds) in the ecoPayz system.
     *
     * @param  string $value client account number
     * @return self
     */
    public function setClientAccountNumber($value)
    {
        return $this->setParameter('clientAccountNumber', $value);
    }

    /**
     * Get the Client Account Number at Merchant
     *
     * Client account number at merchant.
     *
     * @return string client account number at merchant
     */
    public function getClientAccountNumberAtMerchant()
    {
        return $this->getParameter('clientAccountNumberAtMerchant');
    }

    /**
     * Set the Client Account Number at Merchant
     *
     * Client account number at merchant.
     *
     * @param  string $value client account number at merchant
     * @return self
     */
    public function setClientAccountNumberAtMerchant($value)
    {
        return $this->setParameter('clientAccountNumberAtMerchant', $value);
    }

    /**
     * Get the data for this request.
     *
     * @return \DOMDocument request data
     */
    public function getData()
    {
        $this->validate(
            'merchantId',
            'merchantPassword',
            'merchantAccountNumber',
            'clientAccountNumber',
            'transactionId',
            'amount',
            'currency'
        );

        $document = new \DOMDocument('1.0', 'utf-8');
        $document->formatOutput = false;

        $envelope = $document->appendChild(
            $document->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'soapenv:Envelope')
        );
        $envelope->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $envelope->setAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
        $envelope->setAttribute('xmlns:q0', 'http://www.ecocard.com/merchantAPI/');

        $body = $envelope->appendChild(
            $document->createElement('soapenv:Body')
        );

        $payout = $body->appendChild(
            $document->createElement('q0:Payout')
        );

        $request = $payout->appendChild(
            $document->createElement('q0:PayoutRequest')
        );

        $request->appendChild(
            $document->createElement('q0:MerchantID', $this->getMerchantId())
        );

        $request->appendChild(
            $document->createElement('q0:MerchantPassword', $this->getMerchantPassword())
        );

        $request->appendChild(
            $document->createElement('q0:MerchantAccountNumber', $this->getMerchantAccountNumber())
        );

        $request->appendChild(
            $document->createElement('q0:ClientAccountNumber', $this->getClientAccountNumber())
        );

        $request->appendChild(
            $document->createElement('q0:Amount', $this->getAmountInteger())
        );

        $request->appendChild(
            $document->createElement('q0:TxID', $this->getTransactionId())
        );

        $request->appendChild(
            $document->createElement('q0:Currency', strtoupper($this->getCurrency()))
        );

        if ($clientAccountNumberAtMerchant = $this->getClientAccountNumberAtMerchant()) {
            $request->appendChild(
                $document->createElement('q0:ClientAccountNumberAtMerchant', $clientAccountNumberAtMerchant)
            );
        }

        if ($description = $this->getDescription()) {
            $request->appendChild(
                $document->createElement('q0:TransactionDescription', $description)
            );
        }

        return $document->saveXML();
    }

    /**
     * Send the request with specified data
     *
     * @param  mixed                    $data The data to send
     * @throws InvalidResponseException
     * @return FetchTransactionResponse
     */
    public function sendData($data)
    {
        $headers = array(
            'Content-Type' => 'text/xml; charset=utf-8',
            'SOAPAction' => 'http://www.ecocard.com/merchantAPI/Payout'
        );

        $httpRequest = $this->httpClient->createRequest('POST', $this->getEndpoint(), $headers, $data);
        $httpResponse = $httpRequest->send();
        $xmlResponse = $httpResponse->xml()
            ->children('http://schemas.xmlsoap.org/soap/envelope/')
            ->children('http://www.ecocard.com/merchantAPI/');

        if (!isset($xmlResponse->PayoutResponse)) {
            throw new InvalidResponseException('Missing element in XML response');
        }

        if (!isset($xmlResponse->PayoutResponse->TransactionResponse)) {
            throw new InvalidResponseException('Missing element in XML response');
        }

        return new FetchTransactionResponse($this, $xmlResponse->PayoutResponse->TransactionResponse);
    }
}


<?php
namespace Omnipay\Ecopayz\Message;

/**
 * Ecopayz Purchase Request
 *
 * When a client connects to the merchant's WEB store and chooses something to purchase,
 * the merchant's application needs to obtain the money amount of this purchase operation,
 * so it offers various payment methods to the client (for example, ecoPayz).
 * When the client chooses ecoPayz, the next step can be executed.
 *
 * @author Alexander Fedra <contact@dercoder.at>
 * @copyright 2015 DerCoder
 * @license http://opensource.org/licenses/mit-license.php MIT
 * @version 2.0.6 Ecopayz API Specification
 */
class PurchaseRequest extends AbstractRequest
{
    /**
     * Get the Customer ID at Merchant
     *
     * The client's account number at the merchant site.
     *
     * @return string customer id at merchant
     */
    public function getCustomerIdAtMerchant()
    {
        return $this->getParameter('customerIdAtMerchant');
    }

    /**
     * Set the Customer ID at Merchant
     *
     * The client's account number at the merchant site.
     *
     * @param  string $value customer id at merchant
     * @return self
     */
    public function setCustomerIdAtMerchant($value)
    {
        return $this->setParameter('customerIdAtMerchant', $value);
    }

    /**
     * Get the data for this request.
     *
     * @return array request data
     */
    public function getData()
    {
        $this->validate(
            'merchantId',
            'merchantAccountNumber',
            'customerIdAtMerchant',
            'transactionId',
            'amount',
            'currency'
        );

        $data = array();
        $data['PaymentPageID'] = $this->getMerchantId();
        $data['MerchantAccountNumber'] = $this->getMerchantAccountNumber();
        $data['CustomerIdAtMerchant'] = $this->getCustomerIdAtMerchant();
        $data['TxID'] = $this->getTransactionId();
        $data['Amount'] = $this->getAmount();
        $data['Currency'] = $this->getCurrency();
        $data['MerchantFreeText'] = $this->getDescription();

        if ($returnUrl = $this->getReturnUrl()) {
            $data['OnSuccessUrl'] = $returnUrl;
        }

        if ($cancelUrl = $this->getCancelUrl()) {
            $data['OnFailureUrl'] = $cancelUrl;
        }

        if ($notifyUrl = $this->getNotifyUrl()) {
            $data['TransferUrl'] = $notifyUrl;
        }

        $data['Checksum'] = $this->calculateArrayChecksum($data);
        return $data;
    }

    /**
     * Send the request with specified data
     *
     * @param  mixed            $data The data to send
     * @return PurchaseResponse
     */
    public function sendData($data)
    {
        return new PurchaseResponse($this, $data);
    }
}


<?php
namespace Samurai\Project;

/**
 * Class Author
 * @package Samurai\Project
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class Author
{
    /**
     * @var string
     */
    private $name;

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

    /**
     * $author must be formatted like an email of the RFC 822
     * ex: name <mail@mail.com>
     * @param string $author
     */
    public function __construct($author)
    {
        if (preg_match('/^(?P<name>[- \.,\p{L}\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
            $this->setName($match['name']);
            $this->setEmail($match['email']);
        }else{
            throw new \InvalidArgumentException(sprintf(
                'Invalid author "%s".  Must be in the format: "name <mail@mail.com>"',
                $author
            ));
        }
    }

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

    /**
     * Setter of $name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = (string)$name;
    }

    /**
     * Getter of $email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Setter of $email
     *
     * @param string $email
     */
    public function setEmail($email)
    {
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
            throw new \InvalidArgumentException(sprintf('Invalid email "%s"', $email));
        }
        $this->email = (string)$email;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return[
            'name' => $this->getName(),
            'email' => $this->getEmail(),
        ];
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getName() . ' <' . $this->getEmail() . '>';
    }
}


<?php

namespace LireinCore\ImgCache;

use LireinCore\Image\Effect;
use LireinCore\Image\Effects\Flip;
use LireinCore\Image\Effects\Rotate;
use LireinCore\Image\Effects\Resize;
use LireinCore\Image\Effects\Crop;
use LireinCore\Image\Effects\Scale;
use LireinCore\Image\Effects\ScaleUp;
use LireinCore\Image\Effects\ScaleDown;
use LireinCore\Image\Effects\Fit;
use LireinCore\Image\Effects\Cover;
use LireinCore\Image\Effects\Negative;
use LireinCore\Image\Effects\Grayscale;
use LireinCore\Image\Effects\Gamma;
use LireinCore\Image\Effects\Blur;
use LireinCore\Image\Effects\Overlay;
use LireinCore\Image\Effects\Text;
use LireinCore\Image\PostProcessor;
use LireinCore\Image\PostProcessors\JpegOptim;
use LireinCore\Image\PostProcessors\OptiPng;
//use LireinCore\Image\PostProcessors\MozJpeg;
use LireinCore\Image\PostProcessors\PngQuant;
use LireinCore\Image\ImageHelper;
use LireinCore\Image\Manipulator;
use LireinCore\Image\Manipulators\Imagine;
use LireinCore\ImgCache\Exception\ConfigException;

final class Config
{
    private const DEFAULT_IMAGE_CLASS = Imagine::class;
    private const DEFAULT_JPEG_QUALITY = 75;
    private const DEFAULT_PNG_COMPRESSION_LEVEL = 7;
    private const DEFAULT_PNG_COMPRESSION_FILTER = 5;
    private const DEFAULT_PROCESS_PLUG = false;

    /**
     * @var string graphic library for all presets: 'gd', 'imagick', 'gmagick'
     * (by default, tries to use: imagick->gd->gmagick)
     */
    private $driver;

    /**
     * @var string image class for all presets (which implements \LireinCore\Image\Manipulator interface)
     */
    private $imageClass;

    /**
     * @var string original images source directory for all presets
     */
    private $srcDir;

    /**
     * @var string thumbs destination directory for all presets
     * (to access the thumbs from the web they should be in a directory accessible from the web)
     */
    private $destDir;

    /**
     * @var string web directory for all presets
     */
    private $webDir;

    /**
     * @var string base url for all presets
     */
    private $baseUrl;

    /**
     * @var int quality of save jpeg images for all presets: 0-100
     */
    private $jpegQuality;

    /**
     * @var int compression level of save png images for all presets: 0-9
     */
    private $pngCompressionLevel;

    /**
     * @var int compression filter of save png images for all presets: 0-9
     */
    private $pngCompressionFilter;

    /**
     * @var string absolute path to plug for all presets (used if original image is not available)
     */
    private $plugPath;

    /**
     * @var bool apply preset effects and postprocessors to plug?
     */
    private $processPlug;

    /**
     * @var string url to get the plug from a third-party service (used if original image is not available)
     */
    private $plugUrl;

    /**
     * @var array formats convert map for all presets
     */
    private $convertMap = [
        'jpeg' => 'jpeg',
        'png'  => 'png',
        'gif'  => 'gif',
        'wbmp' => 'wbmp',
        'xbm'  => 'xbm',
        '*'    => 'png'
    ];

    /**
     * @var array effects map
     */
    private $effectsMap = [
        'flip'       => Flip::class,
        'rotate'     => Rotate::class,
        'resize'     => Resize::class,
        'crop'       => Crop::class,
        'scale'      => Scale::class,
        'scale_up'   => ScaleUp::class,
        'scale_down' => ScaleDown::class,
        'fit'        => Fit::class,
        'cover'      => Cover::class,
        'negative'   => Negative::class,
        'grayscale'  => Grayscale::class,
        'gamma'      => Gamma::class,
        'blur'       => Blur::class,
        'overlay'    => Overlay::class,
        'text'       => Text::class
    ];

    /**
     * @var array postprocessors map
     */
    private $postProcessorsMap = [
        'jpegoptim' => JpegOptim::class,
        'optipng'   => OptiPng::class,
        //'mozjpeg'   => MozJpeg::class,
        'pngquant'  => PngQuant::class,
    ];

    /**
     * @var array
     */
    private $postProcessorsConfig = [];

    /**
     * Config constructor.
     *
     * @param array $config
     * @throws ConfigException
     */
    public function __construct($config)
    {
        if (isset($config['destdir'])) {
            $this->setDestDir($config['destdir']);
        } else {
            throw new ConfigException('Destination directory is required');
        }

        if (isset($config['driver'])) {
            $this->setDriver($config['driver']);
        } else {
            $driver = ImgHelper::availableDriver();
            if ($driver === null) {
                throw new ConfigException("No graphic libraries installed or higher versions is required. Please, install one of the following: '" . \implode("', '", ImageHelper::supportedDrivers()) . "'");
            }
            $this->setDriver($driver);
        }

        if (isset($config['image_class'])) {
            $this->setImageClass($config['image_class']);
        } else {
            $this->setImageClass(static::DEFAULT_IMAGE_CLASS);
        }

        if (isset($config['srcdir'])) {
            $this->setSrcDir($config['srcdir']);
        }

        if (isset($config['webdir'])) {
            $this->setWebDir($config['webdir']);
        }

        if (isset($config['baseurl'])) {
            $this->setBaseUrl($config['baseurl']);
        }

        if (isset($config['jpeg_quality'])) {
            $this->setJpegQuality($config['jpeg_quality']);
        } else {
            $this->setJpegQuality(static::DEFAULT_JPEG_QUALITY);
        }

        if (isset($config['png_compression_level'])) {
            $this->setPngCompressionLevel($config['png_compression_level']);
        } else {
            $this->setPngCompressionLevel(static::DEFAULT_PNG_COMPRESSION_LEVEL);
        }

        if (isset($config['png_compression_filter'])) {
            $this->setPngCompressionFilter($config['png_compression_filter']);
        } else {
            $this->setPngCompressionFilter(static::DEFAULT_PNG_COMPRESSION_FILTER);
        }

        if (isset($config['convert_map'])) {
            if (\is_array($config['convert_map'])) {
                foreach ($config['convert_map'] as $srcFormats => $destFormat) {
                    $this->registerConvert($srcFormats, $destFormat);
                }
            } else {
                throw new ConfigException('Incorrect config format');
            }
        }

        if (isset($config['plug']['path'])) {
            $this->setPlugPath($config['plug']['path']);
        }

        if (isset($config['plug']['process'])) {
            $this->setProcessPlug($config['plug']['process']);
        } else {
            $this->setProcessPlug(static::DEFAULT_PROCESS_PLUG);
        }

        if (isset($config['plug']['url'])) {
            $this->setPlugUrl($config['plug']['url']);
        }

        if (isset($config['effects_map'])) {
            if (\is_array($config['effects_map'])) {
                foreach ($config['effects_map'] as $type => $class) {
                    $this->registerEffect($type, $class);
                }
            } else {
                throw new ConfigException('Incorrect config format');
            }
        }

        if (isset($config['postprocessors_map'])) {
            if (\is_array($config['postprocessors_map'])) {
                foreach ($config['postprocessors_map'] as $type => $class) {
                    $this->registerPostProcessor($type, $class);
                }
            } else {
                throw new ConfigException('Incorrect config format');
            }
        }

        if (isset($config['postprocessors'])) {
            if (\is_array($config['postprocessors'])) {
                foreach ($config['postprocessors'] as $postProcessorConfig) {
                    if (!isset($postProcessorConfig['type'])) {
                        throw new ConfigException('Incorrect config format. Postprocessor type not specified');
                    }
                    $class = $this->postProcessorClassName($postProcessorConfig['type']);
                    if (null === $class) {
                        throw new ConfigException("Incorrect config format. Unknown postprocessor type '{$postProcessorConfig['type']}'");
                    }
                    $this->postProcessorsConfig[] = $postProcessorConfig;
                }
            } else {
                throw new ConfigException('Incorrect config format');
            }
        }
    }

    /**
     * @param string $driver
     * @throws ConfigException
     */
    private function setDriver(string $driver) : void
    {
        if (\in_array($driver, ImageHelper::supportedDrivers(), true)) {
            $this->driver = $driver;
        } else {
            throw new ConfigException("Incorrect driver value. Should be one of the following: '" . implode("', '", ImageHelper::supportedDrivers()) . "'");
        }
    }

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

    /**
     * @param null|string $srcDir
     * @throws ConfigException
     */
    private function setSrcDir(?string $srcDir) : void
    {
        if ($srcDir === null) {
            $this->srcDir = null;
        } elseif (\is_dir($srcDir)) {
            $this->srcDir = \rtrim($srcDir, "\\/");
        } else {
            throw new ConfigException("Source directory {$srcDir} not found");
        }
    }

    /**
     * @return null|string
     */
    public function srcDir() : ?string
    {
        return $this->srcDir;
    }

    /**
     * @param string $destDir
     * @throws ConfigException
     */
    private function setDestDir(string $destDir) : void
    {
        $destDir = \rtrim($destDir, "\\/");
        if (!\is_dir($destDir)) {
            try {
                ImageHelper::rmkdir($destDir);
            } catch (\RuntimeException $e) {
                throw new ConfigException("Destination directory {$destDir} does not exist", 0, $e);
            }
        }

        $this->destDir = $destDir;
    }

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

    /**
     * @param null|string $webDir
     * @throws ConfigException
     */
    private function setWebDir(?string $webDir) : void
    {
        if ($webDir === null || \is_dir($webDir)) {
            $this->webDir = $webDir;
        } else {
            throw new ConfigException("Web directory {$webDir} not found");
        }
    }

    /**
     * @return null|string
     */
    public function webDir() : ?string
    {
        return $this->webDir;
    }

    /**
     * @param null|string $baseUrl
     */
    private function setBaseUrl(?string $baseUrl) : void
    {
        $this->baseUrl = $baseUrl;
    }

    /**
     * @return null|string
     */
    public function baseUrl() : ?string
    {
        return $this->baseUrl;
    }

    /**
     * @param int $jpegQuality
     * @throws ConfigException
     */
    private function setJpegQuality(int $jpegQuality) : void
    {
        if ($jpegQuality < 0 || $jpegQuality > 100) {
            throw new ConfigException('Incorrect jpeg_quality value');
        }
        $this->jpegQuality = $jpegQuality;
    }

    /**
     * @return int
     */
    public function jpegQuality() : int
    {
        return $this->jpegQuality;
    }

    /**
     * @param int $pngCompressionLevel
     * @throws ConfigException
     */
    private function setPngCompressionLevel(int $pngCompressionLevel) : void
    {
        if ($pngCompressionLevel < 0 || $pngCompressionLevel > 9) {
            throw new ConfigException('Incorrect png_compression_level value');
        }
        $this->pngCompressionLevel = $pngCompressionLevel;
    }

    /**
     * @return int
     */
    public function pngCompressionLevel() : int
    {
        return $this->pngCompressionLevel;
    }

    /**
     * @param int $pngCompressionFilter
     * @throws ConfigException
     */
    private function setPngCompressionFilter(int $pngCompressionFilter) : void
    {
        if ($pngCompressionFilter < 0 || $pngCompressionFilter > 9) {
            throw new ConfigException('Incorrect png_compression_filter value');
        }
        $this->pngCompressionFilter = $pngCompressionFilter;
    }

    /**
     * @return int
     */
    public function pngCompressionFilter() : int
    {
        return $this->pngCompressionFilter;
    }

    /**
     * @param string $srcFormats
     * @param string $destFormat
     * @throws ConfigException
     */
    private function registerConvert(string $srcFormats, string $destFormat) : void
    {
        if (\in_array($destFormat, ImageHelper::supportedDestinationFormats(), true)) {
            $formats = ImageHelper::formats();
            foreach (\explode(',', $srcFormats) as $srcFormat) {
                if ($srcFormat === '*' || isset($formats[$srcFormat])) {
                    $this->convertMap[$srcFormat] = $destFormat;
                } else {
                    throw new ConfigException("Incorrect convert value. Unsupported source image format {$srcFormat}");
                }
            }
        } else {
            throw new ConfigException("Incorrect convert value. Unsupported destination image format {$destFormat}");
        }
    }

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

    /**
     * @param null|string $plugPath
     * @throws ConfigException
     */
    private function setPlugPath(?string $plugPath) : void
    {
        if ($plugPath === null || \is_file($plugPath)) {
            $this->plugPath = $plugPath;
        } else {
            throw new ConfigException("Plug file {$plugPath} not found");
        }
    }

    /**
     * @return null|string
     */
    public function plugPath() : ?string
    {
        return $this->plugPath;
    }

    /**
     * @param bool $processPlug
     */
    private function setProcessPlug(bool $processPlug) : void
    {
        $this->processPlug = $processPlug;
    }

    /**
     * @return bool
     */
    public function isPlugProcessed() : bool
    {
        return $this->processPlug;
    }

    /**
     * @param null|string $plugUrl
     */
    private function setPlugUrl(?string $plugUrl) : void
    {
        $this->plugUrl = $plugUrl;
    }

    /**
     * @return null|string
     */
    public function plugUrl() : ?string
    {
        return $this->plugUrl;
    }

    /**
     * @param string $imageClass
     * @throws ConfigException
     */
    private function setImageClass(string $imageClass) : void
    {
        if (\class_exists($imageClass)) {
            $interfaces = \class_implements($imageClass);
            if (\in_array(Manipulator::class, $interfaces, true)) {
                $this->imageClass = $imageClass;
            } else {
                throw new ConfigException("Class {$imageClass} don't implement interface " . Manipulator::class);
            }
        } else {
            throw new ConfigException("Class {$imageClass} not found");
        }
    }

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

    /**
     * @return bool
     */
    public function hasPostProcessors() : bool
    {
        return !empty($this->postProcessorsConfig);
    }

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

    /**
     * Register custom effects or override default effects
     *
     * @param string $type
     * @param string $class class which implements \LireinCore\Image\Effect interface
     * @throws ConfigException
     */
    private function registerEffect(string $type, string $class) : void
    {
        if (\class_exists($class)) {
            $interfaces = \class_implements($class);
            if (\in_array(Effect::class, $interfaces, true)) {
                $this->effectsMap[$type] = $class;
            } else {
                throw new ConfigException("Class {$class} don't implement interface " . Effect::class);
            }
        } else {
            throw new ConfigException("Class {$class} not found");
        }
    }

    /**
     * @return string[]
     */
    public function effectsMap() : array
    {
        return $this->effectsMap;
    }

    /**
     * @param string $type
     * @return null|string
     */
    public function effectClassName(string $type) : ?string
    {
        return $this->effectsMap[$type] ?? null;
    }

    /**
     * Register custom postprocessor or override default postprocessors
     *
     * @param string $type
     * @param string $class class which implements \LireinCore\Image\PostProcessor interface
     * @throws ConfigException
     */
    private function registerPostProcessor(string $type, string $class) : void
    {
        if (\class_exists($class)) {
            $interfaces = \class_implements($class);
            if (\in_array(PostProcessor::class, $interfaces, true)) {
                $this->postProcessorsMap[$type] = $class;
            } else {
                throw new ConfigException("Class {$class} don't implement interface " . PostProcessor::class);
            }
        } else {
            throw new ConfigException("Class {$class} not found");
        }
    }

    /**
     * @return string[]
     */
    public function postProcessorsMap() : array
    {
        return $this->postProcessorsMap;
    }

    /**
     * @param string $type
     * @return null|string
     */
    public function postProcessorClassName(string $type) : ?string
    {
        return $this->postProcessorsMap[$type] ?? null;
    }
}


<?php
namespace Samurai\Module;

use Samurai\Alias\Alias;

/**
 * Class Module
 * @package Samurai\module
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class Module extends Alias
{
    /**
     * @var bool
     */
    private $isEnable;

    /**
     * modules which must be executed before the current module.
     *
     * @var Modules
     */
    private $dependencies = [];

    /**
     * commands to run for the current module.
     *
     * @var array
     */
    private $tasks = [];

    /**
     * constructor
     */
    public function __construct()
    {
        $this->setDependencies(new Modules());
    }

    /**
     * Getter of $isEnable
     *
     * @return boolean
     */
    public function isEnable()
    {
        return $this->isEnable;
    }

    /**
     * Getter of $isEnable
     *
     * @return boolean
     */
    public function getIsEnable()
    {
        return $this->isEnable;
    }

    /**
     * Setter of $isEnable
     *
     * @param boolean $isEnable
     */
    public function setIsEnable($isEnable)
    {
        $this->isEnable = (boolean)$isEnable;
    }
    /**
     * Getter of $dependencyNames
     *
     * @return Modules
     */
    public function getDependencies()
    {
        return $this->dependencies;
    }

    /**
     * Setter of $dependencyNames
     *
     * @param Modules $dependencies
     */
    public function setDependencies($dependencies)
    {
        if(is_array($dependencies)){//todo should not be allowed + unit test with the ModuleManager!
            $dependencies = $this->buildModulesFromData($dependencies);
        }
        $this->dependencies = $dependencies;
    }

    /**
     * @param Modules $modules
     * @return Modules
     */
    public function retrieveDependents(Modules $modules)
    {
        $dependents = new Modules();
        /**
         * @var Module[] $modules
         */
        foreach($modules as $key => $module) {
            foreach($module->getDependencies() as $dependency){
                if($dependency->getPackage() === $this->getPackage()){
                    $dependents[$key] = $module;
                }
            }
        }
        return $dependents;
    }

    /**
     * Getter of $tasks
     *
     * @return array
     */
    public function getTasks()
    {
        return $this->tasks;
    }

    /**
     * Setter of $tasks
     *
     * @param array $tasks
     */
    public function setTasks(array $tasks)
    {
        $this->tasks = $tasks;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return array_merge(
            parent::toArray(),
            [
                'isEnable' => $this->isEnable(),
                'tasks' => $this->getTasks(),
                'dependencies' => $this->getDependencies()->toArray()
            ]
        );
    }

    /**
     * @param array $dependenciesData
     * @return Modules
     */
    private function buildModulesFromData(array $dependenciesData)
    {
        $modules = new Modules();
        foreach ($dependenciesData as $key => $dependencyData) {
            $modules[$key] = $this->buildModuleFromData($dependencyData);
        }
        return $modules;
    }

    /**
     * @param array $data
     * @return Module
     */
    private function buildModuleFromData(array $data)
    {
        $module = new Module();
        $module->setName(!empty($data['name']) ? $data['name'] : null);
        $module->setPackage(!empty($data['package']) ? $data['package'] : null);
        $module->setVersion(!empty($data['version']) ? $data['version'] : null);
        $module->setDescription(!empty($data['description']) ? $data['description'] : null);
        $module->setSource(!empty($data['source']) ? $data['source'] : null);
        $module->setIsEnable(true);
        return $module;
    }
}


<?php
namespace Samurai\Module\Planner;

use Samurai\Task\ITask;
use Samurai\Task\Planner;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

/**
 * Class PlannerAdapter
 * @package Samurai\Module\Planner
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class PlannerAdapter implements ITask
{
    /**
     * @var Planner
     */
    private $planner;

    /**
     * @var IPlannerBuilder
     */
    private $plannerBuilder;

    /**
     * @var QuestionHelper
     */
    private $questionHelper;

    /**
     * @param IPlannerBuilder $plannerBuilder
     * @param QuestionHelper $questionHelper
     */
    public function __construct(IPlannerBuilder $plannerBuilder, QuestionHelper $questionHelper)
    {
        $this->plannerBuilder = $plannerBuilder;
        $this->questionHelper = $questionHelper;
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|null
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        if(!$this->questionHelper->ask($input, $output, $this->buildQuestion())){
            return ITask::NO_ERROR_CODE;
        }
        if(!$this->plannerBuilder->count()){
            $output->writeln('<error>Nothing to run</error>');
            return ITask::NON_BLOCKING_ERROR_CODE;
        }
        return $this->getPlanner()->execute($input, $output);
    }

    /**
     * Getter of $planner
     *
     * @return Planner
     */
    private function getPlanner()
    {
        if($this->planner == null){
            $this->setPlanner($this->plannerBuilder->create());
        }
        return $this->planner;
    }

    /**
     * Setter of $planner
     *
     * @param Planner $planner
     */
    private function setPlanner(Planner $planner)
    {
        $this->planner = $planner;
    }

    /**
     * @return ConfirmationQuestion
     */
    private function buildQuestion()
    {
        if($this->plannerBuilder->getName()){
            return new ConfirmationQuestion('<question>Do you want to execute the module "' . $this->plannerBuilder->getName() . '"?[y]</question>');
        }
        return new ConfirmationQuestion('<question>Do you want to execute the modules?[y]</question>');
    }
}


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Translation\Factory;

use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Sylius\Component\Resource\Factory\FactoryInterface;
use Sylius\Component\Translation\Model\TranslatableInterface;
use Sylius\Component\Translation\Provider\LocaleProviderInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class TranslatableFactory implements TranslatableFactoryInterface
{
    /**
     * @var FactoryInterface
     */
    private $factory;

    /**
     * @var LocaleProviderInterface
     */
    private $localeProvider;

    /**
     * @param FactoryInterface $factory
     * @param LocaleProviderInterface $localeProvider
     */
    public function __construct(FactoryInterface $factory, LocaleProviderInterface $localeProvider)
    {
        $this->factory = $factory;
        $this->localeProvider = $localeProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function createNew()
    {
        $resource = $this->factory->createNew();

        if (!$resource instanceof TranslatableInterface) {
            throw new UnexpectedTypeException($resource, TranslatableInterface::class);
        }

        $resource->setCurrentLocale($this->localeProvider->getCurrentLocale());
        $resource->setFallbackLocale($this->localeProvider->getFallbackLocale());

        return $resource;
    }
}


<?php
namespace Omnipay\Ecopayz\Message;

use Omnipay\Common\Exception\InvalidRequestException;

/**
 * Ecopayz Complete Purchase Request
 *
 * @author    Alexander Fedra <contact@dercoder.at>
 * @copyright 2015 DerCoder
 * @license   http://opensource.org/licenses/mit-license.php MIT
 * @version   2.0.3 Ecopayz API Specification
 */
class CompletePurchaseRequest extends FetchTransactionRequest
{
    /**
     * Get the data for this request.
     *
     * @throws InvalidRequestException
     * @return string                  request data
     */
    public function getData()
    {
        $this->validate(
            'merchantId',
            'merchantPassword'
        );

        if ($xml = $this->httpRequest->request->get('XML')) {

            if (!$this->validateChecksum($xml)) {
                throw new InvalidRequestException('Invalid XML checksum');
            }

            return new \SimpleXMLElement($xml);

        } elseif ($xml = $this->httpRequest->getContent()) {
            return new \SimpleXMLElement($xml);

        } else {

            throw new InvalidRequestException('Missing XML');

        }
    }

    /**
     * Send the request with specified data
     *
     * @param  mixed                    $data The data to send
     * @return FetchTransactionResponse
     */
    public function sendData($data)
    {
        if (isset($data->StatusReport)) {

            if (in_array($data->StatusReport->Status, array(1, 2, 3))) {
                $response = $this->createResponse('OK', 0, 'OK');
            } elseif (in_array($data->StatusReport->Status, array(4, 5))) {
                $response = $this->createResponse('Confirmed', 0, 'Confirmed');
            } else {
                $response = $this->createResponse('InvalidRequest', 99, 'Invalid StatusReport/Status');
            }

            header('Content-Type: text/xml; charset=utf-8');
            echo $response;
            die();

        } else {
            return new CompletePurchaseResponse($this, $data);
        }
    }

    /**
     * Respond to Ecopayz confirming or rejecting the payment.
     *
     * One of the following status codes:
     * - InvalidRequest
     * - OK
     * - Confirmed
     * - Cancelled
     *
     * @param  string $status           The ecopayz status code
     * @param  int    $errorCode        The merchant error code
     * @param  string $errorDescription The merchant error description
     * @return string response
     */
    public function createResponse($status, $errorCode, $errorDescription)
    {
        $document = new \DOMDocument('1.0', 'utf-8');
        $document->formatOutput = false;

        $response = $document->appendChild(
            $document->createElement('SVSPurchaseStatusNotificationResponse')
        );

        $result = $response->appendChild(
            $document->createElement('TransactionResult')
        );

        $result->appendChild(
            $document->createElement('Description', $errorDescription)
        );

        $result->appendChild(
            $document->createElement('Code', $errorCode)
        );

        $response->appendChild(
            $document->createElement('Status', $status)
        );

        $authentication = $response->appendChild(
            $document->createElement('Authentication')
        );

        $checksum = $authentication->appendChild(
            $document->createElement('Checksum', $this->getMerchantPassword())
        );

        $checksum->nodeValue = $this->calculateXmlChecksum($document->saveXML());

        return $document->saveXML();
    }

    /**
     * Validate Ecopayz XML message
     *
     * @param  string $string The xml string to validate
     * @return bool   result
     */
    public function validateChecksum($string)
    {
        $xml = new \SimpleXMLElement($string);
        $checksum = (string) $xml->Authentication->Checksum;
        $original = str_replace($checksum, $this->getMerchantPassword(), $string);

        return md5($original) == $checksum;
    }
}


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sylius\Component\Translation\Model;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 */
trait TranslatableTrait
{
    /**
     * @var TranslationInterface[]
     */
    protected $translations;

    /**
     * @var string
     */
    protected $currentLocale;

    /**
     * Cache current translation. Useful in Doctrine 2.4+
     *
     * @var TranslationInterface
     */
    protected $currentTranslation;

    /**
     * @var string
     */
    protected $fallbackLocale;

    public function __construct()
    {
        $this->translations = new ArrayCollection();
    }

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

    /**
     * {@inheritdoc}
     */
    public function addTranslation(TranslationInterface $translation)
    {
        if (!$this->translations->containsKey($translation->getLocale())) {
            $this->translations->set($translation->getLocale(), $translation);
            $translation->setTranslatable($this);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeTranslation(TranslationInterface $translation)
    {
        if ($this->translations->removeElement($translation)) {
            $translation->setTranslatable(null);
        }
    }

    /**
     * @param TranslationInterface $translation
     *
     * @return bool
     */
    public function hasTranslation(TranslationInterface $translation)
    {
        return $this->translations->containsKey($translation->getLocale());
    }

    /**
     * {@inheritdoc}
     */
    public function setCurrentLocale($currentLocale)
    {
        $this->currentLocale = $currentLocale;
    }

    /**
     * @return string
     */
    public function getCurrentLocale()
    {
        return $this->currentLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function setFallbackLocale($fallbackLocale)
    {
        $this->fallbackLocale = $fallbackLocale;
    }

    /**
     * @return string
     */
    public function getFallbackLocale()
    {
        return $this->fallbackLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function translate($locale = null)
    {
        $locale = $locale ?: $this->currentLocale;
        if (null === $locale) {
            throw new \RuntimeException('No locale has been set and current locale is undefined.');
        }

        if ($this->currentTranslation && $locale === $this->currentTranslation->getLocale()) {
            return $this->currentTranslation;
        }

        if (!$translation = $this->translations->get($locale)) {
            if (null === $this->fallbackLocale) {
                throw new \RuntimeException('No fallback locale has been set.');
            }

            if (!$fallbackTranslation = $this->translations->get($this->getFallbackLocale())) {
                $className = $this->getTranslationClass();

                /** @var TranslationInterface $translation */
                $translation = new $className();
                $translation->setLocale($locale);

                $this->addTranslation($translation);
            } else {
                $translation = clone $fallbackTranslation;
            }
        }

        $this->currentTranslation = $translation;

        return $translation;
    }

    /**
     * Return translation model class.
     *
     * @return string
     */
    public static function getTranslationClass()
    {
        return get_called_class().'Translation';
    }
}


<?php
/*
 * This file is part of the runopencode/sax, an RunOpenCode project.
 *
 * (c) 2017 RunOpenCode
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace RunOpenCode\Sax\StreamAdapter;

use RunOpenCode\Sax\Contract\StreamAdapterInterface;
use RunOpenCode\Sax\Exception\StreamAdapterException;

/**
 * Class SimpleXmlAdapter
 *
 * SimpleXml adapter
 *
 * @package RunOpenCode\Sax\StreamAdapter
 */
class SimpleXmlAdapter implements StreamAdapterInterface
{
    /**
     * @var string
     */
    private $streamClass;

    /**
     * @var array
     */
    private $options;

    /**
     * SimpleXmlAdapter constructor.
     *
     * @param string $streamClass FQCN of StreamInterface implementation, GuzzleHttp\Psr7\Stream is used by default.
     * @param array $options Adapter options.
     */
    public function __construct($streamClass = 'GuzzleHttp\\Psr7\\Stream', array $options = array())
    {
        $this->streamClass = $streamClass;
        $this->options = array_merge(array(
            'stream' => 'php://memory',
        ), $options);
    }

    /**
     * {@inheritdoc}
     */
    public function supports($xmlDocument)
    {
        return $xmlDocument instanceof \SimpleXMLElement;
    }

    /**
     * {@inheritdoc}
     */
    public function convert($xmlDocument)
    {
        $stream = @fopen($this->options['stream'], 'r+b');

        if (false === $stream) {
            throw new StreamAdapterException(sprintf('Unable to acquire resource handler on "%s".', $this->options['stream']));
        }

        fwrite($stream, $xmlDocument->asXML());

        if (false === @rewind($stream)) {
            throw new StreamAdapterException('Unable to to rewind stream.');
        }

        return new $this->streamClass($stream);
    }
}


<?php
/*
 * This file is part of the runopencode/sax, an RunOpenCode project.
 *
 * (c) 2017 RunOpenCode
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace RunOpenCode\Sax\Handler;

/**
 * Class AbstractStackedSaxHandler
 *
 * Sax handler prototype with implemented elements stack.
 *
 * @package RunOpenCode\Sax\Handler
 */
abstract class AbstractStackedSaxHandler extends AbstractSaxHandler
{
    /**
     * @var array Elements stack
     */
    private $stack = [];

    /**
     * {@inheritdoc}
     */
    protected function onElementStart($parser, $name, $attributes)
    {
        array_push($this->stack, $name);
        $this->handleOnElementStart($parser, $name, $attributes);
    }

    /**
     * {@inheritdoc}
     */
    protected function onElementEnd($parser, $name)
    {
        array_pop($this->stack);
        $this->handleOnElementEnd($parser, $name);
    }

    /**
     * Get current processing element name (uppercase), or null, if there is no element on stack
     * (processing didn't started or it is ended)
     *
     * @return string|null
     */
    protected function getCurrentElementName()
    {
        return (($count = count($this->stack)) > 0) ? $this->stack[$count-1] : null;
    }

    /**
     * Get current element stack size
     *
     * @return int
     */
    protected function getStackSize()
    {
        return count($this->stack);
    }

    /**
     * Element start handler, executed when XML tag is entered.
     *
     * @param resource $parser Parser handler.
     * @param string $name Tag name.
     * @param array $attributes Element attributes.
     */
    abstract protected function handleOnElementStart($parser, $name, $attributes);

    /**
     * Element end handler, executed when XML tag is leaved.
     *
     * @param resource $parser Parser handler.
     * @param string $name Tag name.
     */
    abstract protected function handleOnElementEnd($parser, $name);
}


<?php
/*
 * This file is part of the runopencode/sax, an RunOpenCode project.
 *
 * (c) 2017 RunOpenCode
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace RunOpenCode\Sax\Handler;

use Psr\Http\Message\StreamInterface;
use RunOpenCode\Sax\Contract\SaxHandlerInterface;

/**
 * Class AbstractSaxHandler
 *
 * Sax handler prototype.
 *
 * @package RunOpenCode\Sax
 */
abstract class AbstractSaxHandler implements SaxHandlerInterface
{
    /**
     * @var array
     */
    protected $options;

    /**
     * @var string|null
     */
    private $currentElement = null;

    /**
     * @var int
     */
    private $stackSize = 0;

    /**
     * @var string|null
     */
    private $dataBuffer = null;

    /**
     * @var array
     */
    private $namespaces = [];

    /**
     * AbstractSaxHandler constructor.
     *
     * @param array $options
     */
    public function __construct(array $options = array())
    {
        $this->options = array_merge(array(
            'buffer_size'   => 4096,
            'case_folding'  => true,
            'separator'     => ':',
            'encoding'      => 'UTF-8',
            'skip_tagstart' => null,
            'skip_white'    => null,
        ), $options);
    }

    /**
     * {@inheritdoc}
     */
    final public function parse(StreamInterface $stream)
    {
        $parser = xml_parser_create_ns($this->options['encoding'], $this->options['separator']);

        if (false === $this->options['case_folding']) {
            xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        }

        if (null === $this->options['skip_tagstart']) {
            xml_parser_set_option($parser, XML_OPTION_SKIP_TAGSTART, $this->options['skip_tagstart']);
        }

        if (null === $this->options['skip_white']) {
            xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $this->options['skip_white']);
        }

        $this->onDocumentStart($parser, $stream);

        $this->attachHandlers($parser);

        $this->process($parser, $stream);

        $this->onDocumentEnd($parser, $stream);

        xml_parser_free($parser);

        $stream->close();

        return $this->getResult();
    }

    /**
     * Document start handler, executed when parsing process started.
     *
     * @param resource $parser Parser handler.
     * @param StreamInterface $stream XML stream.
     */
    abstract protected function onDocumentStart($parser, $stream);

    /**
     * Element start handler, executed when XML tag is entered.
     *
     * @param resource $parser Parser handler.
     * @param string $name Tag name.
     * @param array $attributes Element attributes.
     */
    abstract protected function onElementStart($parser, $name, $attributes);

    /**
     * Element CDATA handler, executed when XML tag CDATA is parsed.
     *
     * @param resource $parser Parser handler.
     * @param string $data Element CDATA.
     */
    abstract protected function onElementData($parser, $data);

    /**
     * Element end handler, executed when XML tag is leaved.
     *
     * @param resource $parser Parser handler.
     * @param string $name Tag name.
     */
    abstract protected function onElementEnd($parser, $name);

    /**
     * Document end handler, executed when parsing process ended.
     *
     * @param resource $parser Parser handler.
     * @param StreamInterface $stream XML stream.
     */
    abstract protected function onDocumentEnd($parser, $stream);

    /**
     * Parsing error handler.
     *
     * @param string $message Parsing error message.
     * @param int $code Error code.
     * @param int $lineno XML line number which caused error.
     */
    abstract protected function onParseError($message, $code, $lineno);

    /**
     * Get parsing result.
     *
     * Considering that your handler processed XML document, this method will collect
     * parsing result. This method is called last and it will provide parsing result to invoker.
     *
     * @return mixed Parsing result
     */
    abstract protected function getResult();

    /**
     * Start namespace declaration handler, executed when namespace declaration started.
     *
     * @param resource $parser Parser handler.
     * @param string $prefix Namespace reference within an XML object.
     * @param string $uri Uniform Resource Identifier (URI) of namespace.
     */
    protected function onNamespaceDeclarationStart($parser, $prefix, $uri)
    {
        // noop
    }

    /**
     * End namespace declaration handler, executed when namespace declaration ended.
     *
     * @param resource $parser Parser handler.
     * @param string $prefix Namespace reference within an XML object.
     */
    protected function onNamespaceDeclarationEnd($parser, $prefix)
    {
        // noop
    }

    /**
     * Get declared namespaces.
     *
     * Retrieve declared namespaces as associative array where keys are
     * used prefixes within XML document. Note that only processed namespace
     * declarations will be provided.
     *
     * @return array
     */
    final protected function getDeclaredNamespaces()
    {
        return $this->namespaces;
    }

    /**
     * Parse path to XML document/string content.
     *
     * @param resource $parser Parser.
     * @param StreamInterface $stream XML document stream.
     * @return AbstractSaxHandler $this Fluent interface.
     *
     * @throws \RuntimeException
     */
    private function process($parser, StreamInterface $stream)
    {
        if ($stream->eof()) {
            $stream->rewind();
        }

        while ($data = $stream->read($this->options['buffer_size'])) {
            xml_parse($parser, $data, $stream->eof()) || $this->onParseError(xml_error_string(xml_get_error_code($parser)), xml_get_error_code($parser), xml_get_current_line_number($parser));
        }

        return $this;
    }

    /**
     * Attach handlers.
     *
     * @param resource $parser XML parser.
     * @return AbstractSaxHandler $this Fluent interface.
     */
    private function attachHandlers($parser)
    {
        $onElementStart = \Closure::bind(function ($parser, $name, $attributes) {
            $name                 = $this->normalize($name);
            $this->currentElement = $name;
            $this->dataBuffer     = null;

            $this->stackSize++;

            $this->onElementStart($parser, $name, $attributes);
        }, $this);

        $onElementEnd   = \Closure::bind(function ($parser, $name) {
            $name                 = $this->normalize($name);
            $this->currentElement = null;

            $this->stackSize--;

            if (null !== $this->dataBuffer) {
                $this->onElementData($parser, $this->dataBuffer);
            }

            $this->dataBuffer = null;

            $this->onElementEnd($parser, $name);
        }, $this);

        $onElementData  =  \Closure::bind(function ($parser, $data) {
            $this->dataBuffer .= $data;
        }, $this);

        $onNamespaceDeclarationStart = \Closure::bind(function ($parser, $prefix, $uri) {
            $this->namespaces[$prefix] = rtrim($uri, '/');
            $this->onNamespaceDeclarationStart($parser, $prefix, $uri);
        }, $this);

        $onNamespaceDeclarationEnd = \Closure::bind(function ($parser, $prefix) {
            $this->onNamespaceDeclarationEnd($parser, $prefix);
        }, $this);

        xml_set_element_handler($parser, $onElementStart, $onElementEnd);

        xml_set_character_data_handler($parser, $onElementData);

        xml_set_start_namespace_decl_handler($parser, $onNamespaceDeclarationStart);

        xml_set_end_namespace_decl_handler($parser, $onNamespaceDeclarationEnd);

        return $this;
    }

    /**
     * Normalize namespaced tag name.
     *
     * @param $name
     *
     * @return string
     */
    private function normalize($name)
    {
        return str_replace('/:', ':', $name);
    }
}


<?php

namespace Gtk\FlashMessage;

class Flash
{
    /**
     * The session writer.
     *
     * @var SessionStore
     */
    private $session;

    /**
     * Create a new flash instance.
     *
     * @param SessionStore $session
     */
    public function __construct(SessionStore $session)
    {
        $this->session = $session;
    }

    /**
     * Create a flash message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function create($title, $message, $level = 'info', $key = 'flash_message')
    {
        $this->session->flash($key, [
            'title'   => $title,
            'message' => $message,
            'level'   => $level,
        ]);

        return $this;
    }

    /**
     * Flash a success message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function success($title, $message, $key = 'flash_message')
    {
        return $this->create($title, $message, 'success', $key);
    }

    /**
     * Flash an info message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function info($title, $message, $key = 'flash_message')
    {
        return $this->create($title, $message, 'info', $key);
    }

    /**
     * Flash an error message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function error($title, $message, $key = 'flash_message')
    {
        return $this->create($title, $message, 'error', $key);
    }

    /**
     * Flash an danger message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function danger($title, $message, $key = 'flash_message')
    {
        return $this->create($title, $message, 'danger', $key);
    }

    /**
     * Flash a warning message.
     *
     * @param string $title
     * @param string $message
     * @param string $key
     *
     * @return $this
     */
    public function warning($title, $message, $key = 'flash_message')
    {
        return $this->create($title, $message, 'warning', $key);
    }

    /**
     * Flash an overlay modal.
     *
     * @param string $title
     * @param string $message
     * @param string $level
     * @param string $key
     *
     * @return $this
     */
    public function overlay($title, $message, $level = 'info', $key = 'flash_message')
    {
        return $this->create($title, $message, $level, $key.'_overlay');
    }
}


<?php
/*
 * This file is part of the runopencode/sax, an RunOpenCode project.
 *
 * (c) 2017 RunOpenCode
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace RunOpenCode\Sax;

use Psr\Http\Message\StreamInterface;
use RunOpenCode\Sax\Contract\SaxHandlerInterface;
use RunOpenCode\Sax\Contract\StreamAdapterInterface;
use RunOpenCode\Sax\Exception\RuntimeException;
use RunOpenCode\Sax\StreamAdapter\DomDocumentAdapter;
use RunOpenCode\Sax\StreamAdapter\ResourceAdapter;
use RunOpenCode\Sax\StreamAdapter\SimpleXmlAdapter;
use RunOpenCode\Sax\StreamAdapter\StringAdapter;

/**
 * Class SaxParser
 *
 * Utility class for working with SAX handler and XML document.
 *
 * @package RunOpenCode\Sax
 */
class SaxParser
{
    /**
     * @var StreamAdapterInterface[]
     */
    private $streamAdapters;

    /**
     * SaxParser constructor.
     *
     * @param StreamAdapterInterface[] $streamAdapters Stream adapters to register to parser.
     */
    public function __construct(array $streamAdapters = array())
    {
        $this->streamAdapters = array();

        foreach ($streamAdapters as $streamAdapter) {
            $this->addStreamAdapter($streamAdapter);
        }
    }

    /**
     * Register stream adapter to parser.
     *
     * @param StreamAdapterInterface $streamAdapter Stream adapter to register.
     * @return SaxParser $this Fluent interface.
     */
    public function addStreamAdapter(StreamAdapterInterface $streamAdapter)
    {
        $this->streamAdapters[] = $streamAdapter;
        return $this;
    }

    /**
     * Parse XML document using provided SAX handler.
     *
     * @param SaxHandlerInterface $saxHandler Handler to user for parsing document.
     * @param mixed $xmlDocument XML document source.
     *
     * @return mixed Parsing result.
     */
    public function parse(SaxHandlerInterface $saxHandler, $xmlDocument)
    {
        $xmlDocument = ($xmlDocument instanceof StreamInterface) ? $xmlDocument : $this->getDocumentStream($xmlDocument);
        return $saxHandler->parse($xmlDocument);
    }

    /**
     * Default SAX parser factory.
     *
     * @param string $streamClass FQCN to use when converting to XML document source to stream.
     * @return SaxParser New SAX parser instance.
     */
    public static function factory($streamClass = 'GuzzleHttp\\Psr7\\Stream')
    {
        return new static([
            new ResourceAdapter($streamClass),
            new DomDocumentAdapter($streamClass),
            new SimpleXmlAdapter($streamClass),
            new StringAdapter($streamClass),
        ]);
    }

    /**
     * Convert XML document to stream source.
     *
     * @param mixed $xmlDocument XML document source.
     * @return StreamInterface Converted XML document to stream.
     *
     * @throws \RuntimeException
     */
    private function getDocumentStream($xmlDocument)
    {
        /**
         * @var StreamAdapterInterface $streamAdapter
         */
        foreach ($this->streamAdapters as $streamAdapter) {

            if ($streamAdapter->supports($xmlDocument)) {
                return $streamAdapter->convert($xmlDocument);
            }
        }

        throw new RuntimeException(sprintf('Suitable XML document stream adapter is not registered for XML document of type "%s".', is_object($xmlDocument) ? get_class($xmlDocument) : gettype($xmlDocument)));
    }
}