<?php

namespace ArjanWestdorp\Imaginary;

use ArjanWestdorp\Imaginary\Exceptions\InvalidConfigurationException;
use ArjanWestdorp\Imaginary\Exceptions\UndefinedDefinitionException;
use Closure;

class Client
{
    /**
     * @var Builder
     */
    protected $builder;
    /**
     * @var array;
     */
    protected $definitions = [];
    /**
     * @var array
     */
    private $config;
    /**
     * @var array
     */
    protected $defaults = [];

    /**
     * Client constructor.
     *
     * @param $config
     */
    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * Check if we can call a method on the manipulations builder.
     * Else check if a predefined manipulation set need to be called.
     *
     * @param string $method
     * @param array $arguments
     * @return $this
     * @throws UndefinedDefinitionException
     */
    public function __call($method, $arguments)
    {
        if (method_exists($this->builder, $method)) {
            call_user_func_array([$this->builder, $method], $arguments);

            return $this;
        } elseif (isset($this->definitions[$method]) && is_callable($this->definitions[$method])) {
            array_unshift($arguments, $this->builder);

            call_user_func_array($this->definitions[$method], $arguments);

            return $this;
        }

        throw UndefinedDefinitionException::definitionNotDefined($method);
    }

    /**
     * Define a predefined set of manipulations.
     *
     * @param string $key
     * @param Closure $callback
     * @return $this
     */
    public function define($key, Closure $callback)
    {
        $this->definitions[$key] = $callback;

        return $this;
    }

    /**
     * Let the client fetch the given url as image.
     *
     * @param string $url
     * @return $this
     */
    public function fetch($url)
    {
        $this->builder = new Builder(urlencode($url));

        foreach ($this->defaults as $key => $value) {
            if (method_exists($this->builder, $key)) {
                call_user_func([$this->builder, $key], $value);
            }
        }

        return $this;
    }

    /**
     * Set the default dpr.
     *
     * @param string $key
     * @param mixed $value
     * @return $this
     */
    public function setDefault($key, $value)
    {
        $this->defaults[$key] = $value;

        return $this;
    }

    /**
     * Retrieve the imaginary url.
     *
     * @return string
     */
    public function url()
    {
        if (!isset($this->config['url'])) {
            throw InvalidConfigurationException::urlNotDefined();
        }

        if (!isset($this->config['client'])) {
            throw InvalidConfigurationException::clientNotDefined();
        }

        return implode('/', array_filter([
            $this->config['url'],
            $this->config['client'],
            $this->getResourceKey(),
            $this->getTypeKey(),
            $this->builder->getManipulations(),
            $this->builder->getKey(),
        ]));
    }

    /**
     * Get the resource key.
     * We currently only support image.
     *
     * @return string
     */
    protected function getResourceKey()
    {
        return 'images';
    }

    /**
     * Get the type key.
     * We only support fetch at the moment.
     *
     * @return string
     */
    protected function getTypeKey()
    {
        return 'fetch';
    }

    /**
     * Return the url for this image.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->url();
    }
}


<?php

namespace Nobox\LazyStrings;

use Exception;
use Nobox\LazyStrings\Str;
use Nobox\LazyStrings\Validator;

class LazyStrings
{
    const VERSION = '5.0.1';

    /**
     * Google doc url.
     *
     * @var string
     */
    private $csvUrl;

    /**
     * Tabs of doc spreadsheet.
     *
     * @var array
     */
    private $sheets;

    /**
     * Path where the strings array file will be stored.
     * Separated by locale.
     *
     * @var string
     */
    private $target;

    /**
     * Path where the strings in json format will be stored.
     *
     * @var string
     */
    private $backup;

    /**
     * Filename for the generated language file.
     *
     * @var string
     */
    private $languageFilename = 'lazy';

    /**
     * Some basic data when strings are generated.
     *
     * @var array
     */
    private $metadata = [];

    /**
     * String helper.
     *
     * @var Nobox\LazyStrings\Str
     */
    private $str;

    /**
     * Lazy validator.
     *
     * @var Nobox\LazyStrings\Validator
     */
    private $validator;

    /**
     * Initial setup.
     *
     * @param array $settings
     *
     * @return void
     */
    public function __construct(array $settings)
    {
        $this->csvUrl = $settings['url'];
        $this->sheets = $settings['sheets'];
        $this->target = $settings['target'];
        $this->backup = $settings['backup'];
        $this->nested = $settings['nested'];
        $this->str = new Str();
        $this->validator = new Validator();
        $this->metadata['refreshedBy'] = $_SERVER['DOCUMENT_ROOT'];
        $this->metadata['refreshedOn'] = date(DATE_RFC822, time());
    }

    /**
     * Generates the copy from the sheets.
     * Language files and JSON for storage.
     *
     * @return array
     */
    public function generate()
    {
        // validate doc url and sheets
        if (!$this->validator->validateDocUrl($this->csvUrl)) {
            throw new Exception('Provided doc url is not valid.');
        }

        $this->validator->validateSheets($this->sheets);

        $strings = [];

        foreach ($this->sheets as $locale => $csvId) {
            // create locale directories
            $this->createDirectory($this->target . '/' . $locale);

            $localized = $this->localize($csvId);
            $strings[$locale] = $localized;

            // create strings in language file
            $stringsFile = $this->target . '/' . $locale . '/' . $this->languageFilename . '.php';
            $phpFormatted = '<?php return ' . var_export($localized, true) . ';';

            file_put_contents($stringsFile, $phpFormatted);

            // save strings in json format
            $this->backup($localized, $this->backup, $locale . '.json');
        }

        return $strings;
    }

    /**
     * Parse provided csv document.
     *
     * @param string $csvUrl Url of google doc.
     *
     * @return array
     */
    private function parse($csvUrl)
    {
        $csvFile = fopen($csvUrl, 'r');
        $strings = [];

        if ($csvFile !== false) {
            while (($row = fgetcsv($csvFile, 1000, ',')) !== false) {
                if ($row[0] !== '' && $row[0] !== 'id') {
                    $id = $this->str->strip($row[0]);
                    $value = $row[1];

                    if ($this->nested) {
                        if ($this->str->hasDots($id)) {
                            $strings = array_replace_recursive($strings, $this->str->convertToArray($id, $value));
                        } else {
                            $strings[$id] = $value;
                        }
                    } else {
                        $strings[$id] = $value;
                    }
                }
            }

            fclose($csvFile);
        }

        return $strings;
    }

    /**
     * Append sheet array by locale.
     * If array is provided append the sheets to the same locale.
     *
     * @param string/array $csvId Id of csv doc.
     *
     * @return array
     */
    private function localize($csvId)
    {
        $strings = [];
        $urlPart = '&single=true&gid=';

        if (is_array($csvId)) {
            foreach ($csvId as $id) {
                $parsed = $this->parse($this->csvUrl . $urlPart . $id);
                $strings = array_merge($strings, $parsed);
            }
        } else {
            $strings = $this->parse($this->csvUrl . $urlPart . $csvId);
        }

        return $strings;
    }

    /**
     * Save backup strings in JSON format
     *
     * @param array $strings
     * @param string $path
     * @param string $filename
     *
     * @return void
     */
    private function backup(array $strings, $path, $filename)
    {
        $stringsFile = $path . '/' . $filename;
        $jsonStrings = json_encode($strings, JSON_PRETTY_PRINT);

        $this->createDirectory($path);

        file_put_contents($stringsFile, $jsonStrings);
    }

    /**
     * Create the specified directory.
     * Check if it exists first.
     *
     * @param string $path
     *
     * @return void
     */
    private function createDirectory($path)
    {
        if (!file_exists($path)) {
            mkdir($path, 0777);
        }
    }

    /**
     * Get string generation metadata.
     *
     * @return array
     */
    public function getMetadata()
    {
        return $this->metadata;
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\Accounting\Repo\Dao;

use Praxigento\Accounting\Config as Cfg;
use Praxigento\Accounting\Repo\Data\Account as Entity;
use Praxigento\Accounting\Repo\Data\Type\Asset as TypeAsset;

class Account
    extends \Praxigento\Core\App\Repo\Dao
{
    const BIND_CODE = 'code';
    /**
     * Cache for ID of the system customer.
     * @var int
     */
    private $cachedSysCustId;
    /** @var \Praxigento\Accounting\Repo\Dao\Type\Asset */
    private $daoTypeAsset;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Core\Api\App\Repo\Generic $daoGeneric,
        \Praxigento\Accounting\Repo\Dao\Type\Asset $daoTypeAsset
    )
    {
        parent::__construct($resource, $daoGeneric, Entity::class);
        $this->daoTypeAsset = $daoTypeAsset;
    }

    /**
     * @param \Praxigento\Accounting\Repo\Data\Account|array $data
     * @return int
     */
    public function create($data)
    {
        $result = parent::create($data);
        return $result;
    }

    /**
     * Get all accounts by asset type code.
     *
     * @param string $assetTypeCode
     * @return \Praxigento\Accounting\Repo\Data\Account[]|null
     *
     * SELECT
     * paa.*
     * FROM prxgt_acc_type_asset pata
     * LEFT JOIN prxgt_acc_account paa
     * ON pata.id = paa.asset_type_id
     * WHERE pata.code = "PV";
     */
    public function getAllByAssetTypeCode($assetTypeCode)
    {
        /* aliases and tables */
        $asType = 'at';
        $asAcc = 'acc';
        /* SELECT FROM prxgt_acc_type_asset */
        $query = $this->conn->select();
        $tbl = $this->resource->getTableName(TypeAsset::ENTITY_NAME);
        $cols = [];
        $query->from([$asType => $tbl], $cols);
        /* LEFT JOIN prxgt_acc_account */
        $tbl = $this->resource->getTableName(Entity::ENTITY_NAME);
        $on = $asAcc . '.' . Entity::A_ASSET_TYPE_ID . '=' . $asType . '.' . TypeAsset::A_ID;
        $cols = [
            Entity::A_ID,
            Entity::A_ASSET_TYPE_ID,
            Entity::A_BALANCE,
            Entity::A_CUST_ID
        ];
        $query->joinLeft([$asAcc => $tbl], $on, $cols);
        /* WHERE */
        $where = $asType . '.' . TypeAsset::A_CODE . '=:' . self::BIND_CODE;
        $query->where($where);
        /* bind vars and fetch results */
        $bind = [self::BIND_CODE => $assetTypeCode];
        $rs = $this->conn->fetchAll($query, $bind);
        $result = [];
        foreach ($rs as $one) {
            $item = new Entity($one);
            $result[$item->getId()] = $item;
        }
        return $result;
    }

    /**
     * Get asset type ID for the given account.
     *
     * @param int $accountId
     * @return int
     */
    public function getAssetTypeId($accountId)
    {
        $result = null;
        /** @var Entity $entity */
        $entity = $this->getById($accountId);
        if ($entity) {
            $result = $entity->getAssetTypeId();
        }
        return $result;
    }

    /**
     * Get account data for the $customerId by $assetTypeId. Create new one if there is no account for this
     * customer/asset.
     *
     * @param int $customerId
     * @param int $assetTypeId
     * @return \Praxigento\Accounting\Repo\Data\Account|null
     */
    public function getByCustomerId($customerId, $assetTypeId)
    {
        $result = null;
        $where = '(' . Entity::A_CUST_ID . '=' . (int)$customerId . ')';
        $where = "$where AND (" . Entity::A_ASSET_TYPE_ID . '=' . (int)$assetTypeId . ')';
        $found = $this->get($where);
        if ($found && count($found)) {
            $result = reset($found);
        } else {
            /* there is no account for this customer/asset */
            $entity = new Entity();
            $entity->setCustomerId($customerId);
            $entity->setAssetTypeId($assetTypeId);
            $accId = $this->create($entity);
            $result = $this->getById($accId);
        }
        return $result;
    }

    /**
     * @param int $id
     * @return \Praxigento\Accounting\Repo\Data\Account|bool
     */
    public function getById($id)
    {
        $result = parent::getById($id);
        return $result;
    }

    /**
     * Get account data by customer ID & asset type code.
     *
     * @param int $customerId
     * @param string $assetTypeCode
     * @return Entity account ID
     */
    public function getCustomerAccByAssetCode($customerId, $assetTypeCode)
    {
        $assetTypeId = $this->daoTypeAsset->getIdByCode($assetTypeCode);
        $result = $this->getByCustomerId($customerId, $assetTypeId);
        return $result;
    }

    /**
     * Return system account ID for given asset type. Create new account if there is no yet system
     * account for this asset type.
     *
     * @param int $assetTypeId
     * @return int|null
     * @throws \Exception
     */
    public function getSystemAccountId($assetTypeId)
    {
        /* TODO: add cache for accounts ids */
        $result = null;
        $custId = $this->getSystemCustomerId();
        if ($custId) {
            $found = $this->getByCustomerId($custId, $assetTypeId);
            if ($found) {
                $result = $found->getId();
            } else {
                /* there is no yet system account for this asset type */
                $account = new Entity();
                $account->setAssetTypeId($assetTypeId);
                $account->setCustomerId($custId);
                $result = $this->create($account);
            }
        }
        return $result;
    }

    /**
     * Return system account ID for given asset type. Create new account if there is no yet system
     * account for this asset type.
     *
     * TODO: should we use this method or "\Praxigento\Accounting\Api\Service\Account\Get" service?
     *
     * @param string $assetTypeCode
     * @return int|null
     * @throws \Exception
     */
    public function getSystemAccountIdByAssetCode($assetTypeCode)
    {
        $assetTypeId = $this->daoTypeAsset->getIdByCode($assetTypeCode);
        $result = $this->getSystemAccountId($assetTypeId);
        return $result;
    }

    /**
     * Return MageID for customer that represents store owner in accounting. Create new system customer
     *if it is not exist yet.
     *
     * @return int
     */
    public function getSystemCustomerId()
    {
        if (is_null($this->cachedSysCustId)) {
            $conn = $this->conn;
            /* there is no cached value for the customer ID, select data from DB */
            $where = Cfg::E_CUSTOMER_A_EMAIL . '=' . $conn->quote(Cfg::SYS_CUSTOMER_EMAIL);
            $data = $this->daoGeneric->getEntities(Cfg::ENTITY_MAGE_CUSTOMER, Cfg::E_CUSTOMER_A_ENTITY_ID,
                $where);
            if (count($data) == 0) {
                $bind = [
                    Cfg::E_CUSTOMER_A_WEBSITE_ID => Cfg::DEF_WEBSITE_ID_ADMIN,
                    Cfg::E_CUSTOMER_A_EMAIL => Cfg::SYS_CUSTOMER_EMAIL
                ];
                $id = $this->daoGeneric->addEntity(Cfg::ENTITY_MAGE_CUSTOMER, $bind);
                if ($id > 0) {
                    $this->cachedSysCustId = $id;
                }
            } else {
                $first = reset($data);
                $this->cachedSysCustId = $first[Cfg::E_CUSTOMER_A_ENTITY_ID];
            }
        }
        return $this->cachedSysCustId;
    }

    /**
     * Add/subtract value to/from account current balance.
     *
     * @param int $accountId
     * @param float $delta change value (negative or positive)
     * @return int number of updated rows in DB
     */
    public function updateBalance($accountId, $delta)
    {
        if ($delta < 0) {
            $exp = '(`' . Entity::A_BALANCE . '`-' . abs($delta) . ')';
        } else {
            $exp = '(`' . Entity::A_BALANCE . '`+' . abs($delta) . ')';
        }
        $exp = new \Praxigento\Core\App\Repo\Query\Expression($exp);
        $bind = [Entity::A_BALANCE => $exp];
        $rowsUpdated = $this->updateById($accountId, $bind);
        return $rowsUpdated;
    }
}


<?php
/**
 * User: makhovdmitrii@inbox.ru
 */

namespace Praxigento\Accounting\Service\Transaction;

use Praxigento\Accounting\Config as Cfg;
use Praxigento\Accounting\Repo\Data\Transaction as ETransaction;
use Praxigento\Accounting\Service\Transaction\Create\Request as ARequest;
use Praxigento\Accounting\Service\Transaction\Create\Response as AResponse;

class Create
{
    /** @var  \Praxigento\Accounting\Repo\Dao\Account */
    private $daoAcc;
    /** @var  \Praxigento\Accounting\Repo\Dao\Transaction */
    private $daoTrans;

    public function __construct(
        \Praxigento\Accounting\Repo\Dao\Account $daoAcc,
        \Praxigento\Accounting\Repo\Dao\Transaction $daoTrans
    ) {
        $this->daoAcc = $daoAcc;
        $this->daoTrans = $daoTrans;
    }

    /**
     * Add new transaction and update current balances.
     * @param ARequest $request
     * @return AResponse
     * @throws \Exception
     */
    public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();
        $debitAccId = $request->getDebitAccId();
        $creditAccId = $request->getCreditAccId();
        $operationId = $request->getOperationId();
        $dateApplied = $request->getDateApplied();
        $value = $request->getValue();
        $note = $request->getNote();

        /* limit amount by MIN & MAX */
        if (
            ($value > Cfg::LIMIT_AMOUNT_MAX) ||
            ($value < Cfg::LIMIT_AMOUNT_MIN)
        ) {
            throw new \Exception("Illegal value for amount transaction: $value.");
        }

        /* get account type for debit account */
        $debitAcc = $this->daoAcc->getById($debitAccId);
        $debitAssetTypeId = $debitAcc->getAssetTypeId();
        /* get account type for credit account */
        $creditAcc = $this->daoAcc->getById($creditAccId);
        $creditAssetTypeId = $creditAcc->getAssetTypeId();
        /* asset types should be equals */
        if (
            !is_null($debitAssetTypeId) &&
            ($debitAssetTypeId == $creditAssetTypeId)
        ) {
            /* add transaction */
            $toAdd = [
                ETransaction::A_OPERATION_ID => $operationId,
                ETransaction::A_DEBIT_ACC_ID => $debitAccId,
                ETransaction::A_CREDIT_ACC_ID => $creditAccId,
                ETransaction::A_VALUE => $value,
                ETransaction::A_DATE_APPLIED => $dateApplied
            ];
            if (!is_null($note)) {
                $toAdd[ETransaction::A_NOTE] = $note;
            }
            $idCreated = $this->daoTrans->create($toAdd);
            $result->setTransactionId($idCreated);
        } else {
            throw new \Exception("Asset type (#$debitAssetTypeId) for debit account #$debitAccId is not equal to "
                . "asset type (#$creditAssetTypeId) for credit account $creditAccId.");
        }
        $result->markSucceed();
        return $result;
    }

}


<?php

namespace DCS\OpauthBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class DCSOpauthExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('dcs_opauth.call_params', array(
            'debug_mode' => $config['debug_mode'],
            'callback_transport' => $config['callback_transport'],
            'security_iteration' => $config['security_iteration'],
            'security_timeout' => $config['security_timeout'],
        ));
        $container->setParameter('dcs_opauth.authentication_roles', $config['authentication_roles']);
        $container->setParameter('dcs_opauth.redirect_after_response', $config['redirect_after_response']);
        $container->setParameter('dcs_opauth.error_view', $config['error_view']);

        $container->setAlias('dcs_opauth.strategy_parser', $config['logic']['strategy_parser']);
        $container->setAlias('dcs_opauth.response_parser', $config['logic']['response_parser']);
        $container->setAlias('dcs_opauth.authenticator', $config['logic']['authenticator']);

        $strategies = $this->buildStrategiesKey($config['strategies']);
        $container->setParameter('dcs_opauth.strategies', $strategies);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }

    /**
     * Converts the key id and secret in the keys suitable for every strategy
     *
     * @param $strategies
     * @return array
     */
    private function buildStrategiesKey($strategies)
    {
        foreach ($strategies as $name => $config) {
            switch ($config['strategy_class']) {
                case 'Basecamp':
                case 'Behance':
                case 'Bitly':
                case 'Do':
                case 'Dropbox':
                case 'Evernote':
                case 'Foursquare':
                case 'GitHub':
                case 'Google':
                case 'Harvest':
                case 'Instagram':
                case 'Live':
                case 'Mixi':
                case 'Strava':
                case 'Yahoojp':
                case 'Yammer':
                case 'ResourceGuru':
                    $config['client_id'] = $config['id'];
                    $config['client_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Bitbucket':
                case 'Flickr':
                case 'SinaWeibo':
                case 'Twitter':
                case 'Vimeo':
                    $config['key'] = $config['id'];
                    unset($config['id']);
                    break;
                case 'Disqus':
                    $config['api_key'] = $config['id'];
                    $config['api_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'LinkedIn':
                    $config['api_key'] = $config['id'];
                    $config['secret_key'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Facebook':
                case 'PayPal':
                case 'VKontakte':
                    $config['app_id'] = $config['id'];
                    $config['app_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Tumblr':
                    $config['consumer_key'] = $config['id'];
                    $config['consumer_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
            }
            // Set new configuration
            $strategies[$name] = $config;
        }

        return $strategies;
    }
}


<?php

namespace Interpro\ImageAggr\Db;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Extractor\Contracts\Selection\SelectionUnit;
use Interpro\Extractor\Db\QueryBuilder;

class ImageQuerier
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param string $table
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    private function selectByRef($table, ARef $ref)
    {
        $type  = $ref->getType();
        $type_name = $type->getName();
        $id = $ref->getId();

        $query = new QueryBuilder(DB::table($table));
        $query->where($table.'.entity_name', '=', $type_name);

        if($id > 0)
        {
            $query->where($table.'.entity_id', '=', $id);
        }

        return $query;
    }

    /**
     * @param SelectionUnit $selectionUnit
     * @param string $table
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectByUnit($table, SelectionUnit $selectionUnit)
    {
        $type  = $selectionUnit->getType();
        $entity_name    = $type->getName();

        //В главном запросе можно пользоваться биндингом, а в подзапросах нельзя, так как порядок параметров будет сбиваться параметрами подзапросов
        $query = new QueryBuilder(DB::table($table));
        $query->where($table.'.entity_name', '=', $entity_name);

        if($selectionUnit->closeToIdSet())
        {
            $query->whereIn($table.'.entity_id', $selectionUnit->getIdSet());
        }

        return $query;
    }

    /**
     * @param SelectionUnit $selectionUnit
     * @param string $table
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectImagesByUnit(SelectionUnit $selectionUnit)
    {
        return $this->selectByUnit('images', $selectionUnit);
    }

    /**
     * @param SelectionUnit $selectionUnit
     * @param string $table
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectResizesByUnit(SelectionUnit $selectionUnit)
    {
        return $this->selectByUnit('resizes', $selectionUnit);
    }

    /**
     * @param SelectionUnit $selectionUnit
     * @param string $table
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectCropsByUnit(SelectionUnit $selectionUnit)
    {
        return $this->selectByUnit('crops', $selectionUnit);
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectImagesByRef(ARef $ref)
    {
        return $this->selectByRef('images', $ref);
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectResizesByRef(ARef $ref)
    {
        return $this->selectByRef('resizes', $ref);
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function selectCropsByRef(ARef $ref)
    {
        return $this->selectByRef('crops', $ref);
    }

}


<?php

namespace Interpro\ImageAggr\Executors;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Executor\ADestructor;
use Interpro\Core\Contracts\Mediator\DestructMediator;
use Interpro\Core\Contracts\Mediator\RefConsistMediator;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\ImageAggr\Exception\ImageAggrException;

class ModImagesDestructor implements ADestructor
{
    private $refConsistMediator;
    private $destructMediator;

    public function __construct(RefConsistMediator $refConsistMediator, DestructMediator $destructMediator)
    {
        $this->refConsistMediator = $refConsistMediator;
        $this->destructMediator = $destructMediator;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'modimages';
    }

    private function deleteOwns(ARef $ref)
    {
        $type = $ref->getType();

        //Внешние поля
        $families = [];
        $owns = $type->getOwns();

        foreach($owns as $ownField)
        {
            $own_f_f = $ownField->getFieldTypeFamily();

            if(!in_array($own_f_f, $families))
            {
                continue;
            }

            $families[] = $own_f_f;

            if($ownField->getMode() === TypeMode::MODE_B)
            {
                $destructor = $this->destructMediator->getBDestructor($own_f_f);
                $destructor->delete($ref);
            }
            elseif($ownField->getMode() === TypeMode::MODE_C)
            {
                $destructor = $this->destructMediator->getCDestructor($own_f_f);
                $destructor->delete($ref);
            }
        }
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return void
     */
    public function delete(ARef $ref)
    {
        $type = $ref->getType();
        $name = $type->getName();
        $mode = $type->getMode();

        if($name !== 'modimages' or $mode !== TypeMode::MODE_A)
        {
            throw new ImageAggrException('Деструктор предназначен для удаления блока modimages(A), передано: '.$name.'('.$mode.')!');
        }

        //[[[
        DB::beginTransaction();

        //Удаление внешних собственных полей
        $this->deleteOwns($ref);

        //У блока modimages нет своей записи, так что просто удаляем поля
        //Сообщение ссылающимся, об удалении сущности
        $this->refConsistMediator->notify($ref);

        DB::commit();
        //]]]
    }
}


<?php
/**
 *
 */

namespace Praxigento\Accounting\Service\Account\Asset;

use Praxigento\Accounting\Service\Account\Asset\Get\Db\Query\GetAssets as QBGetAssets;
use Praxigento\Accounting\Service\Account\Asset\Get\Request as ARequest;
use Praxigento\Accounting\Service\Account\Asset\Get\Response as AResponse;
use Praxigento\Accounting\Service\Account\Asset\Get\Response\Item as DResponseItem;

/**
 * Internal service to get asset data for a customer (available asset types, existing accounts & balances).
 *
 * This service is not used outside this module.
 */
class Get
{
    /** @var \Praxigento\Accounting\Service\Account\Asset\Get\Db\Query\GetAssets */
    private $qbGetAssets;

    public function __construct(
        QBGetAssets $qbGetAssets
    ) {
        $this->qbGetAssets = $qbGetAssets;
    }

    /**
     * Get asset data for a customer (available asset types, existing accounts & balances).
     *
     * @param ARequest $request
     * @return AResponse
     */
    public function exec($request) {
        assert($request instanceof ARequest);
        /** define local working data */
        $customerId = $request->getCustomerId();

        /** perform processing */
        $items = $this->loadAssetsData($customerId);

        /** compose result */
        $result = new AResponse();
        $result->setItems($items);
        return $result;
    }

    /**
     * @param int $custId
     * @return array
     */
    private function loadAssetsData($custId) {
        $query = $this->qbGetAssets->build();
        $conn = $query->getConnection();
        $bind = [
            QBGetAssets::BND_CUST_ID => $custId
        ];
        $rs = $conn->fetchAll($query, $bind);

        $result = [];
        foreach ($rs as $db) {
            /* extract DB data */
            $accBalance = $db[QBGetAssets::A_ACC_BALANCE];
            $accId = $db[QBGetAssets::A_ACC_ID];
            $assetCode = $db[QBGetAssets::A_ASSET_CODE];
            $assetId = $db[QBGetAssets::A_ASSET_ID];
            $isVisible = $db[QBGetAssets::A_IS_VISIBLE];

            /* compose API data for visible items */
            if ($isVisible) {
                $api = new DResponseItem();
                $api->setAccBalance($accBalance);
                $api->setAccId($accId);
                $api->setAssetCode($assetCode);
                $api->setAssetId($assetId);
                $result[] = $api;
            }
        }
        return $result;
    }
}


<?php

namespace Onoi\Tesa\Tokenizer;

use RuntimeException;

/**
 * PHP Version of the TinySegmenter as a super compact Japanese tokenizer.
 * - https://github.com/setchi/codeute/blob/71c09c86cd1ce1cf9c8ca4d20b1db60b3784227a/fuel/app/classes/model/lib/tiny_segmenter.php
 *
 * TinySegmenter was originally developed by Taku Kudo <taku(at)chasen.org>.
 * Pulished under the BSD license http://chasen.org/~taku/software/TinySegmenter/LICENCE.txt
 *
 * PHP Version was developed by xnights <programming.magic(at)gmail.com>.
 * For details, see http://programming-magic.com/?id=172
 *
 * The model is based on the http://research.nii.ac.jp/src/list.html corpus
 * together with an optimized L1-norm regularization.
 *
 * - https://github.com/shogo82148/TinySegmenterMaker
 *
 * @since 0.1
 */
class JaTinySegmenterTokenizer implements Tokenizer {

	private $patterns_ = array(
		"[一二三四五六七八九十百千万億兆]"=>"M", // numbers (japanese)
		"[一-龠々〆ヵヶ]"=>"H", // kanji & misc characters
		"[ぁ-ん]"=>"I", // hiragana
		"[ァ-ヴーｱ-ﾝﾞｰ]"=>"K", // katakana
		"[a-zA-Zａ-ｚＡ-Ｚ]"=>"A", // ascii / romaji letters
		"[0-9０-９]"=>"N", // ascii / romaji numbers
	);

	/**
	 * @var Tokenizer
	 */
	private $tokenizer;

	/**
	 * This is kept static on purpose.
	 * @var array
	 */
	private static $model;

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

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer $tokenizer
	 */
	public function __construct( Tokenizer $tokenizer = null ) {
		$this->tokenizer = $tokenizer;
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function setOption( $name, $value ) {
		if ( $this->tokenizer !== null ) {
			$this->tokenizer->setOption( $name, $value );
		}
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function isWordTokenizer() {
		return false;
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function tokenize( $string ) {

		if ( $this->tokenizer !== null ) {
			$string = implode( " ", $this->tokenizer->tokenize( $string ) );
		}

		return $this->loadModel()->segment( $string );
	}

	private function loadModel() {

		if ( self::$model !== null ) {
			return $this;
		}

		$contents = null;
		$file = __DIR__ . '/model/rwcp.model.json';

		if ( ( $contents = @file_get_contents( $file ) ) !== false ) {
			self::$model = json_decode( $contents, true );
		}

		if ( $contents === false || json_last_error() !== JSON_ERROR_NONE ) {
			throw new RuntimeException( "Couldn't read the model from {$file}." );
		}

		return $this;
	}

	protected function segment( $input, $encoding = null ) {

		if ( !$input ) {
			return array();
		}

		if ( !$encoding ) {
			$encoding = mb_detect_encoding( $input );
		}

		if ( $encoding !== 'UTF-8' ) {
			$input = mb_convert_encoding( $input, 'UTF-8', $encoding );
		}

		$result = array();
		$seg = array( "B3", "B2", "B1" );

		$ctype = array( "O", "O", "O" );
		$o = $this->mb_string_to_array_( $input );

		for ( $i = 0; $i<count($o); ++$i ) {
			$seg[] = $o[$i];
			$ctype[] = $this->ctype_( $o[$i] );
		}

		$seg[] = "E1";
		$seg[] = "E2";
		$seg[] = "E3";
		$ctype[] = "O";
		$ctype[] = "O";
		$ctype[] = "O";
		$word = $seg[3];
		$p1 = "U";
		$p2 = "U";
		$p3 = "U";

		for($i = 4; $i<count($seg)-3; ++$i){
			$score = self::$model["BIAS"];
			$w1 = $seg[$i-3];
			$w2 = $seg[$i-2];
			$w3 = $seg[$i-1];
			$w4 = $seg[$i];
			$w5 = $seg[$i+1];
			$w6 = $seg[$i+2];
			$c1 = $ctype[$i-3];
			$c2 = $ctype[$i-2];
			$c3 = $ctype[$i-1];
			$c4 = $ctype[$i];
			$c5 = $ctype[$i+1];
			$c6 = $ctype[$i+2];
			$score += $this->ts_(@self::$model["UP1"][$p1]);
			$score += $this->ts_(@self::$model["UP2"][$p2]);
			$score += $this->ts_(@self::$model["UP3"][$p3]);
			$score += $this->ts_(@self::$model["BP1"][$p1 . $p2]);
			$score += $this->ts_(@self::$model["BP2"][$p2 . $p3]);
			$score += $this->ts_(@self::$model["UW1"][$w1]);
			$score += $this->ts_(@self::$model["UW2"][$w2]);
			$score += $this->ts_(@self::$model["UW3"][$w3]);
			$score += $this->ts_(@self::$model["UW4"][$w4]);
			$score += $this->ts_(@self::$model["UW5"][$w5]);
			$score += $this->ts_(@self::$model["UW6"][$w6]);
			$score += $this->ts_(@self::$model["BW1"][$w2 . $w3]);
			$score += $this->ts_(@self::$model["BW2"][$w3 . $w4]);
			$score += $this->ts_(@self::$model["BW3"][$w4 . $w5]);
			$score += $this->ts_(@self::$model["TW1"][$w1 . $w2 . $w3]);
			$score += $this->ts_(@self::$model["TW2"][$w2 . $w3 . $w4]);
			$score += $this->ts_(@self::$model["TW3"][$w3 . $w4 . $w5]);
			$score += $this->ts_(@self::$model["TW4"][$w4 . $w5 . $w6]);
			$score += $this->ts_(@self::$model["UC1"][$c1]);
			$score += $this->ts_(@self::$model["UC2"][$c2]);
			$score += $this->ts_(@self::$model["UC3"][$c3]);
			$score += $this->ts_(@self::$model["UC4"][$c4]);
			$score += $this->ts_(@self::$model["UC5"][$c5]);
			$score += $this->ts_(@self::$model["UC6"][$c6]);
			$score += $this->ts_(@self::$model["BC1"][$c2 . $c3]);
			$score += $this->ts_(@self::$model["BC2"][$c3 . $c4]);
			$score += $this->ts_(@self::$model["BC3"][$c4 . $c5]);
			$score += $this->ts_(@self::$model["TC1"][$c1 . $c2 . $c3]);
			$score += $this->ts_(@self::$model["TC2"][$c2 . $c3 . $c4]);
			$score += $this->ts_(@self::$model["TC3"][$c3 . $c4 . $c5]);
			$score += $this->ts_(@self::$model["TC4"][$c4 . $c5 . $c6]);
			//  $score += $this->ts_(@self::$model["TC5"][$c4 . $c5 . $c6]);
			$score += $this->ts_(@self::$model["UQ1"][$p1 . $c1]);
			$score += $this->ts_(@self::$model["UQ2"][$p2 . $c2]);
			$score += $this->ts_(@self::$model["UQ1"][$p3 . $c3]);
			$score += $this->ts_(@self::$model["BQ1"][$p2 . $c2 . $c3]);
			$score += $this->ts_(@self::$model["BQ2"][$p2 . $c3 . $c4]);
			$score += $this->ts_(@self::$model["BQ3"][$p3 . $c2 . $c3]);
			$score += $this->ts_(@self::$model["BQ4"][$p3 . $c3 . $c4]);
			$score += $this->ts_(@self::$model["TQ1"][$p2 . $c1 . $c2 . $c3]);
			$score += $this->ts_(@self::$model["TQ2"][$p2 . $c2 . $c3 . $c4]);
			$score += $this->ts_(@self::$model["TQ3"][$p3 . $c1 . $c2 . $c3]);
			$score += $this->ts_(@self::$model["TQ4"][$p3 . $c2 . $c3 . $c4]);

			$p = "O";

			if ( $score > 0 ) {

				if ( $word !== '' && $word !== ' ' ) {
					$result[] = $word;
				}

				$word = "";
				$p = "B";
			}

			$p1 = $p2;
			$p2 = $p3;
			$p3 = $p;

			if ( $seg[$i] !== '' && $seg[$i] !== ' ' ) {
				$word .= $seg[$i];
			}
		}

		$result[] = $word;

		if ( $encoding !== 'UTF-8') {
			foreach( $result as &$str ) {
				$str = mb_convert_encoding( $str, $encoding, 'UTF-8' );
			}
		}

		return $result;
	}

	private function ctype_( $str ) {

		foreach( $this->patterns_ as $pattern => $type ) {
			if( preg_match( '/'.$pattern.'/u', $str ) ) {
				return $type;
			}
		}

		return "O";
	}

	private function ts_( $v ) {
		return $v ? $v : 0;
	}

	private function mb_string_to_array_( $str, $encoding = 'UTF-8' ) {

		$result = array();
		$length = mb_strlen( $str, $encoding );

		for ( $i=0; $i < $length; ++$i ) {
			$result[] = mb_substr( $str, $i, 1, $encoding );
		}

		return $result;
	}

}


<?php

namespace Interpro\ImageAggr\Executors;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Executor\AInitializer;
use Interpro\Core\Contracts\Mediator\InitMediator;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\ImageAggr\Exception\ImageAggrException;

class ModImagesInitializer implements AInitializer
{
    private $initMediator;

    public function __construct(InitMediator $initMediator)
    {
        $this->initMediator = $initMediator;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'modimages';
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\AType $type
     * @param array $defaults
     *
     * @return \Interpro\Core\Contracts\Ref\ARef
     */
    public function init(AType $type, array $defaults = [])
    {
        $type_name = $type->getName();
        $mode = $type->getMode();

        if($type_name !== 'modimages' or $mode !== TypeMode::MODE_A)
        {
            throw new ImageAggrException('Инициализатор предназначен для инициализации блока modimages(A), передано: '.$type_name.'('.$mode.')!');
        }

        //[[[
        //У блока modimages нет своей записи с предопределенными полями и нет полей ссылок, инициализируем только собственные поля

        DB::beginTransaction();

        $Aref = new ARef($type, 0);
        //----------------------------------------------------------------------
        $owns = $type->getOwns();

        foreach($owns as $own_name => $own)
        {
            $family = $own->getFieldTypeFamily();
            $mode = $own->getMode();

            if(array_key_exists($own_name, $defaults))
            {
                $value = $defaults[$own_name];
            }
            else
            {
                $value = null;
            }

            if($mode === TypeMode::MODE_B)
            {
                $initializer = $this->initMediator->getBInitializer($family);
                $initializer->init($Aref, $own, $value);
            }
            elseif($mode === TypeMode::MODE_C)
            {
                $initializer = $this->initMediator->getCInitializer($family);
                $initializer->init($Aref, $own, $value);
            }
        }

        DB::commit();
        //]]]

        return $Aref;
    }
}


<?php

namespace DCS\OpauthBundle\DependencyInjection;

use DCS\OpauthBundle\Configuration\Factory;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    private $strategies = array(
        'Basecamp',
        'Behance',
        'Bitbucket',
        'Bitly',
        'Disqus',
        'Do',
        'Dropbox',
        'Evernote',
        'Facebook',
        'Flickr',
        'Foursquare',
        'GitHub',
        'Google',
        'Harvest',
        'Instagram',
        'LinkedIn',
        'Live',
        'Mixi',
        'OpenID',
        'PayPal',
        'SinaWeibo',
        'Strava',
        'Tumblr',
        'Twitter',
        'Vimeo',
        'VKontakte',
        'Yahoojp',
        'Yammer',
        'ResourceGuru',
    );

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('dcs_opauth');

        $rootNode
            ->children()
                ->booleanNode('debug_mode')
                    ->defaultFalse()
                ->end()
                ->scalarNode('callback_transport')
                    ->defaultValue('session')
                    ->validate()
                    ->ifNotInArray(array('session','post','get'))
                        ->thenInvalid('Value "%s" is not a valid callback_transport')
                    ->end()
                ->end()
                ->integerNode('security_iteration')
                    ->defaultValue(300)
                ->end()
                ->scalarNode('security_timeout')
                    ->defaultValue('2 minutes')
                ->end()
                ->arrayNode('authentication_roles')
                    ->defaultValue(array('ROLE_USER'))
                    ->prototype('scalar')->end()
                ->end()
                ->scalarNode('redirect_after_response')
                    ->defaultNull()
                ->end()
                ->scalarNode('error_view')
                    ->cannotBeEmpty()
                    ->defaultValue('DCSOpauthBundle:Response:error.html.twig')
                ->end()
                ->arrayNode('logic')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('strategy_parser')
                            ->cannotBeEmpty()
                            ->defaultValue('dcs_opauth.configuration.strategy_parser.default')
                        ->end()
                        ->scalarNode('response_parser')
                            ->cannotBeEmpty()
                            ->defaultValue('dcs_opauth.response.response_parser.default')
                        ->end()
                        ->scalarNode('authenticator')
                            ->cannotBeEmpty()
                            ->defaultValue('dcs_opauth.security.authenticator.default')
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('strategies')
                    ->useAttributeAsKey('name')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('id')
                                ->isRequired()
                                ->cannotBeEmpty()
                            ->end()
                            ->scalarNode('secret')
                                ->isRequired()
                                ->cannotBeEmpty()
                            ->end()
                            ->scalarNode('strategy_class')
                                ->isRequired()
                                ->validate()
                                ->ifNotInArray($this->strategies)
                                    ->thenInvalid('Value "%s" is not a valid strategy')
                                ->end()
                            ->end()
                            ->variableNode('options')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


<?php

namespace Onoi\Tesa\Tokenizer;

use Onoi\Tesa\CharacterExaminer;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class JaCompoundGroupTokenizer implements Tokenizer {

	/**
	 * @var array
	 */
	private $compound = array(
		"あっ",
		"あり",
		"ある",
		"い",
		"いう",
		"いる",
		"う",
		"うち",
		"お",
		"および",
		"おり",
		"か",
		"かつて",
		"から",
		"が",
		"き",
		"ここ",
		"こと",
		"この",
		"これ",
		"これら",
		"さ",
		"さらに",
		"し",
		"しかし",
		"する",
		"ず",
		"せ",
		"せる",
		"そして",
		"その",
		"その他",
		"その後",
		"それ",
		"それぞれ",
		"た",
		"ただし",
		"たち",
		"ため",
		"たり",
		"だ",
		"だっ",
		"つ",
		"て",
		"で",
		"でき",
		"できる",
		"です",
		"では",
		"でも",
		"と",
		"という",
		"といった",
		"とき",
		"ところ",
		"として",
		"とともに",
		"とも",
		"と共に",
		"な",
		"ない",
		"なお",
		"なかっ",
		"ながら",
		"なく",
		"なっ",
		"など",
		"なら",
		"なり",
		"なる",
		"に",
		"において",
		"における",
		"について",
		"にて",
		"によって",
		"により",
		"による",
		"に対して",
		"に対する",
		"に関する",
		"の",
		"ので",
		"のみ",
		"は",
		"ば",
		"へ",
		"ほか",
		"ほとんど",
		"ほど",
		"ます",
		"また",
		"または",
		"まで",
		"も",
		"もの",
		"ものの",
		"や",
		"よう",
		"より",
		"ら",
		"られ",
		"られる",
		"れ",
		"れる",
		"を",
		"ん",
		"及び",
		"特に",
		"、",
		"。",
		"「",
		"」"
	);

	/**
	 * @var Tokenizer
	 */
	private $tokenizer;

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer $tokenizer
	 */
	public function __construct( Tokenizer $tokenizer = null ) {
		$this->tokenizer = $tokenizer;
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function setOption( $name, $value ) {
		if ( $this->tokenizer !== null ) {
			$this->tokenizer->setOption( $name, $value );
		}
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function isWordTokenizer() {
		return false;
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function tokenize( $string ) {

		if ( $this->tokenizer !== null ) {
			$string = implode( " ", $this->tokenizer->tokenize( $string ) );
		}

		$result = explode( " " , $this->splitByCharacterGroup(
			str_replace( $this->compound, ' ', $string ) )
		);

		foreach ( $result as $key => $value ) {
			if ( $value === '' ) {
				unset( $result[$key] );
			}

			// Single katakana/hiragana are exempted
			if ( mb_strlen( $value ) === 1 && CharacterExaminer::contains( CharacterExaminer::HIRAGANA_KATAKANA, $value ) ) {
				unset( $result[$key] );
			}
		}

		if ( $result !== false ) {
			return array_values( $result );
		}

		return array();
	}

	/**
	 * @see MediaWiki LanguageJa::segmentByWord
	 *
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function splitByCharacterGroup( $string ) {

		// Space strings of like hiragana/katakana/kanji
		$hiragana = '(?:\xe3(?:\x81[\x80-\xbf]|\x82[\x80-\x9f]))'; # U3040-309f
		$katakana = '(?:\xe3(?:\x82[\xa0-\xbf]|\x83[\x80-\xbf]))'; # U30a0-30ff
		$kanji = '(?:\xe3[\x88-\xbf][\x80-\xbf]'
			. '|[\xe4-\xe8][\x80-\xbf]{2}'
			. '|\xe9[\x80-\xa5][\x80-\xbf]'
			. '|\xe9\xa6[\x80-\x99])';
			# U3200-9999 = \xe3\x88\x80-\xe9\xa6\x99

		$reg = "/({$hiragana}+|{$katakana}+|{$kanji}+)/";

		return $this->insertSpace( $string, $reg );
	}

	private function insertSpace( $string, $pattern ) {
		return preg_replace( '/ +/', ' ', preg_replace( $pattern, " $1 ", $string ) );
	}

}


<?php

namespace Interpro\ImageAggr\Service;

use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet;
use Interpro\ImageAggr\Contracts\Settings\PathResolver;
use Interpro\ImageAggr\Model\Crop;
use Interpro\ImageAggr\Model\Image;
use Interpro\ImageAggr\Model\Resize;
use Interpro\Service\Contracts\Cleaner as CleanerInterface;
use Interpro\Service\Enum\Artefact;

class FileCleaner implements CleanerInterface
{
    private $settingsSet;
    private $pathResolver;
    private $consoleOutput;

    public function __construct(ImageSettingsSet $settingsSet, PathResolver $pathResolver)
    {
        $this->settingsSet = $settingsSet;
        $this->pathResolver = $pathResolver;
        $this->consoleOutput = new \Symfony\Component\Console\Output\ConsoleOutput();
    }

    /**
     * @param callable $action
     *
     * @return bool
     */
    private function strategy(callable $action)
    {
        $image_links = [];
        $resize_links = [];
        $crop_links = [];

        $image_links_finded = [];
        $resize_links_finded = [];
        $crop_links_finded = [];

        $originals = Image::all();

        foreach($originals as $model)
        {
            $image_links[] = public_path().$model->link;
        }

        $resizes = Resize::all();

        foreach($resizes as $model)
        {
            $resize_links[] = public_path().$model->link;
        }

        $crops = Crop::all();

        foreach($crops as $model)
        {
            $crop_links[] = public_path().$model->link;
        }

        $image_dir = $this->pathResolver->getImageDir();
        $resize_dir = $this->pathResolver->getResizeDir();
        $crop_dir = $this->pathResolver->getCropDir();

        foreach (glob($image_dir.'/*.*') as $file)
        {
            if(is_dir($file))
            {
                continue;
            }

            $image_links_finded[] = $file;
        }

        foreach (glob($resize_dir.'/*.*') as $file)
        {
            if(is_dir($file))
            {
                continue;
            }

            $resize_links_finded[] = $file;
        }

        foreach (glob($crop_dir.'/*.*') as $file)
        {
            if(is_dir($file))
            {
                continue;
            }

            $crop_links_finded[] = $file;
        }

        $report = false;

        $image_diff  = array_diff($image_links_finded, $image_links);
        $resize_diff = array_diff($resize_links_finded, $resize_links);
        $crop_diff   = array_diff($crop_links_finded, $crop_links);

        if((count($image_diff) + count($resize_diff) + count($crop_diff)) > 0)
        {
            $report = true;
        }

        foreach($image_diff as $image_link)
        {
            $action(1, $image_link);
        }

        foreach($resize_diff as $resize_link)
        {
            $action(2, $resize_link);
        }

        foreach($crop_diff as $crop_link)
        {
            $action(3, $crop_link);
        }

        return $report;
    }

    /**
     * @return bool
     */
    public function inspect()
    {
        $action = function($flag, $link)
        {
            if($flag === 1)
            {
                $this->consoleOutput->writeln('ImageAggr: обнаружен файл '.$link.' в папке картинок, ссылки на который отсутствуют в базе данных.');
            }
            elseif($flag === 2)
            {
                $this->consoleOutput->writeln('ImageAggr: обнаружен файл '.$link.' в папке ресайзов, ссылки на который отсутствуют в базе данных.');
            }
            elseif($flag === 3)
            {
                $this->consoleOutput->writeln('ImageAggr: обнаружен файл '.$link.' в папке кропов, ссылки на который отсутствуют в базе данных.');
            }
            else
            {
                return;
            }
        };

        $report = $this->strategy($action);

        return $report;
    }

    /**
     * @return void
     */
    public function clean()
    {
        $action = function($flag, $link)
        {
            if($flag === 1)
            {
                unlink($link);
                $this->consoleOutput->writeln('ImageAggr: удалён файл '.$link.' в папке картинок, ссылки на который отсутствуют в базе данных.');
            }
            elseif($flag === 2)
            {
                unlink($link);
                $this->consoleOutput->writeln('ImageAggr: удалён файл '.$link.' в папке ресайзов, ссылки на который отсутствуют в базе данных.');
            }
            elseif($flag === 3)
            {
                unlink($link);
                $this->consoleOutput->writeln('ImageAggr: удалён файл '.$link.' в папке кропов, ссылки на который отсутствуют в базе данных.');
            }
            else
            {
                return;
            }
        };

        $this->strategy($action);
    }

    /**
     * @return string
     */
    public function getArtefact()
    {
        return Artefact::FILE;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'imageaggr';
    }
}


<?php

namespace DCS\OpauthBundle\Response;

use DCS\OpauthBundle\Exception\UnsupportedCallbackException;

class ResponseParser implements ResponseParserInterface
{
    /**
     * Parse response of the Opauth object
     *
     * @param \Opauth $opauth
     * @return array
     * @throws \DCS\OpauthBundle\Exception\UnsupportedCallbackException
     */
    public function parse(\Opauth $opauth)
    {
        $callbackTransport = $opauth->env['callback_transport'];

        switch($callbackTransport) {
            case 'session':
                $response = $_SESSION['opauth'];
                unset($_SESSION['opauth']);
                break;
            case 'post':
                $response = unserialize(base64_decode($_POST['opauth']));
                break;
            case 'get':
                $response = unserialize(base64_decode($_GET['opauth']));
                break;
            default:
                throw new UnsupportedCallbackException(sprintf('Callback transport "%s" is not supported. Are only supported: session, post, get', $callbackTransport));
                break;
        }

        return $response;
    }
}


<?php

namespace Interpro\ImageAggr\Db;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Taxonomy\Fields\Field;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Extractor\Contracts\Db\Joiner;
use Interpro\Extractor\Db\QueryBuilder;
use Interpro\ImageAggr\Exception\ImageAggrException;

class ImageJoiner implements Joiner
{
    /**
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\Field $field
     * @param array $join_array
     *
     * @return \Interpro\Extractor\Db\QueryBuilder
     */
    public function joinByField(Field $field, $join_array)
    {
        $fieldType = $field->getFieldType();
        $type_name = $fieldType->getName();
        $field_name = $field->getName();
        $mode = $fieldType->getMode();

        $image_table_fields = ['id', 'name', 'entity_name', 'entity_id', 'link', 'alt', 'cache_index', 'width', 'height'];

        if($type_name !== 'image' or $mode !== TypeMode::MODE_B)
        {
            throw new ImageAggrException('Соединитель предназначен для соединения с основным запросом поля типа images(B), передано: '.$type_name.'('.$mode.')!');
        }

        $join_q = new QueryBuilder(DB::table('images'));

        $join_q->addSelect('images.entity_name');
        $join_q->addSelect('images.entity_id');
        $join_q->whereRaw('images.name = "'.$field_name.'"');

        //Если в продолжения пути нет, то $field_name и есть нужное поле
        foreach($join_array['sub_levels'] as $levelx_field_name => $sub_array)
        {
            if(in_array($levelx_field_name, $image_table_fields))
            {
                $join_q->addSelect('images.'.$levelx_field_name.' as '.$sub_array['full_field_names'][0]);//Законцовка - в массиве только одно поле x_..x_id
            }
            elseif($levelx_field_name === 'crops' or $levelx_field_name === 'resizes')
            {
                foreach($sub_array['sub_levels'] as $gen_name => $crop_array)
                {
                    $sub_q = $this->joinByGen($levelx_field_name, $gen_name, $crop_array);

                    $join_q->leftJoin(DB::raw('('.$sub_q->toSql().') AS '.$gen_name.'_table'), function($join) use ($gen_name)
                    {
                        $join->on('images.entity_name', '=', $gen_name.'_table.entity_name');
                        $join->on('images.entity_id',   '=', $gen_name.'_table.entity_id');
                    });

                    foreach($crop_array['full_field_names'] as $full_field_name)
                    {
                        $join_q->addSelect($full_field_name);//Из $sub_q пришли поля с именами, добавляем все в текущую выборку
                    }
                }
            }
            else
            {
                throw new ImageAggrException('Соединение в целях сортировки или отбора возможно только по следующим полям картинки: '.implode(',', $image_table_fields).', генерациям crops или resizes, передано '.$levelx_field_name.'!');
            }
        }

        return $join_q;
    }

    private function joinByGen($table, $resize_name, $join_array)
    {
        $join_q = new QueryBuilder(DB::table($table));

        $join_q->addSelect($table.'.entity_name');
        $join_q->addSelect($table.'.entity_id');
        $join_q->whereRaw($table.'.image_name = "'.$resize_name.'"');

        $table_fields = ['id', 'name', 'entity_name', 'entity_id', 'image_name', 'man_name', 'target_name', 'link', 'alt', 'cache_index', 'width', 'height', 'x', 'y'];

        foreach($join_array['sub_levels'] as $levelx_field_name => $sub_array)
        {
            if(in_array($levelx_field_name, $table_fields))
            {
                $join_q->addSelect($table.'.'.$levelx_field_name.' as '.$sub_array['full_field_names'][0]);
            }
        }

        return $join_q;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'imageaggr';
    }

}


<?php

namespace DCS\OpauthBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ConnectController extends Controller
{
    /**
     * Call the provider for the authentication
     */
    public function loginAction($strategy)
    {
        $config = $this->get('dcs_opauth.strategy_parser')->get($strategy);
        $opauth = new \Opauth($config);
    }
}


<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\Accounting\Service\Operation\Create\A;

use Praxigento\Accounting\Repo\Data\Transaction as ETrans;
use Praxigento\Accounting\Service\Transaction\Create\Request as ARequest;
use Praxigento\Accounting\Service\Transaction\Create\Response as AResponse;

class Add
{
    /**
     * @var \Praxigento\Accounting\Service\Transaction\Create
     */
    private $srvTrans;

    public function __construct(
        \Praxigento\Accounting\Service\Transaction\Create $srvTrans
    ) {
        $this->srvTrans = $srvTrans;
    }

    /**
     * Add operation's transaction and bind transactions ids to references (orders or customers ids).
     *
     * @param $operId
     * @param $trans
     * @param $datePerformed
     * @param $asRef
     *
     * @return array
     * @throws \Exception
     */
    public function exec($operId, $trans, $datePerformed, $asRef = null)
    {
        $result = [];
        foreach ($trans as $one) {
            if (!$one instanceof ETrans) {
                $one = new ETrans($one);
            }
            $dateApplied = $one->getDateApplied();
            $dateApplied = $dateApplied ? $dateApplied : $datePerformed;
            $req = new ARequest();
            $req->setOperationId($operId);
            $req->setDebitAccId($one->getDebitAccId());
            $req->setCreditAccId($one->getCreditAccId());
            $req->setValue($one->getValue());
            $req->setNote($one->getNote());
            $req->setDateApplied($dateApplied);
            /** @var  $resp AResponse */
            $resp = $this->srvTrans->exec($req);
            if (!$resp->isSucceed()) {
                throw new \Exception("Transaction (debit acc. #{$req->getDebitAccId()}, credit acc. "
                    . "#{$req->getCreditAccId()}) cannot be inserted . ");
            }
            $tranId = $resp->getTransactionId();
            $ref = $one->get($asRef);
            if (
                !is_null($asRef) &&
                isset($ref)
            ) {
                /* bind new transaction ID to the reference from request */
                $result[$tranId] = $ref;
            } else {
                /* new transaction ID is bound by 'add transaction' requests order */
                $result[] = $resp->getTransactionId();
            }
        }
        return $result;
    }
}


<?php

namespace ByTIC\Omnipay\Common\Library\View;

use ArrayAccess;

/**
 * Class View
 */
class View implements ArrayAccess
{

    /**
     * The path to the view file.
     *
     * @var string
     */
    protected $path;
    protected $basePath = null;
    /**
     * View data
     * @var array
     */
    private $data;

    /**
     * render Renders the view using the given data
     *
     * @param $path
     * @param array $data
     * @return mixed
     */
    public function render($path, $data = [])
    {
        $this->data = array_merge($this->data, $data);
        $this->setPath($path);
        $contents = $this->renderContents();

        return $contents;
    }

    /**
     * @return string
     */
    protected function renderContents()
    {
        $path = $this->buildPath();
        ob_start();
        /** @noinspection PhpIncludeInspection */
        include($path);
        $html = ob_get_contents();
        ob_end_clean();
        return $html;
    }

    /**
     * Builds path for including
     * If $view starts with / the path will be relative to the root of the views folder.
     * Otherwise to caller file location.
     *
     * @param string $path
     * @return string
     */
    protected function buildPath($path = '')
    {
        $path = $path ? $path : $this->getPath();
        return $this->getBasePath() . ltrim($path, "/") . '.php';
    }

    //
    // GETTERS AND SETTERS
    //

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

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

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

    /**
     * @param null $basePath
     */
    public function setBasePath($basePath)
    {
        $this->basePath = $basePath;
    }

    /**
     * @param  string $name
     * @return mixed|null
     */
    public function get($name)
    {
        if ($this->has($name)) {
            return $this->data[$name];
        } else {
            return null;
        }
    }

    /**
     * @param string $name
     * @return bool
     */
    public function has($name)
    {
        return isset($this->data[$name]);
    }

    /**
     * @param string $name
     * @param mixed $value
     * @return $this
     */
    public function set($name, $value)
    {
        $this->data[$name] = $value;
        return $this;
    }

    public function append($name, $value)
    {
        $valueOld = $this->get($name);
        return $this->set($name, $valueOld . $value);
    }

    //
    // ARRAY ACCESS METHODS
    //

    /**
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    /**
     * @param mixed $offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->data[$offset];
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    /**
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->data[$offset]);
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2019
 */

namespace Praxigento\Accounting\Service\Account\Balance;

use Praxigento\Accounting\Repo\Data\Type\Asset as ETypeAsset;
use Praxigento\Accounting\Service\Account\Balance\Validate\Request as ARequest;
use Praxigento\Accounting\Service\Account\Balance\Validate\Response as AResponse;

/**
 * Validate current balances for customers accounts.
 */
class Validate
{
    /** @var \Praxigento\Accounting\Repo\Dao\Type\Asset */
    private $daoTypeAsset;
    /** @var \Psr\Log\LoggerInterface */
    private $logger;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset */
    private $ownOneAsset;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Accounting\Repo\Dao\Type\Asset $daoTypeAsset,
        \Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset $ownOneAsset
    ) {
        $this->logger = $logger;
        $this->daoTypeAsset = $daoTypeAsset;
        $this->ownOneAsset = $ownOneAsset;
    }

    public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();
        /** define local working data */
        $assets = $this->getAssetTypes();

        /** perform processing */
        $total = count($assets);
        $this->logger->info("Total $total asset types are available for balances validation.");
        foreach ($assets as $typeId => $typeCode) {
            $this->logger->info("Validate balances for asset $typeCode/$typeId.");
            $this->ownOneAsset->exec($typeId);
        }

        $result->markSucceed();
        return $result;
    }

    /**
     * Get all asset types.
     *
     * @return array [id => code]
     */
    private function getAssetTypes()
    {
        $result = [];
        $types = $this->daoTypeAsset->get();
        /** @var ETypeAsset $type */
        foreach ($types as $type) {
            $typeId = $type->getId();
            $typeCode = $type->getCode();
            $result[$typeId] = $typeCode;
        }
        return $result;
    }
}


<?php

namespace DCS\OpauthBundle\Security;

use Symfony\Component\Security\Core\SecurityContextInterface;

class Authenticator implements AuthenticatorInterface
{
    /**
     * @var \Symfony\Component\Security\Core\SecurityContextInterface
     */
    protected $securityContext;

    /**
     * @var array
     */
    protected $roles;

    function __construct(SecurityContextInterface $securityContext, array $roles)
    {
        $this->securityContext = $securityContext;
        $this->roles = $roles;
    }

    /**
     * Set token with the response data
     *
     * @param $responseData
     */
    public function authenticate($responseData)
    {
        $token = new OpauthToken($responseData, $this->roles);
        $this->securityContext->setToken($token);
    }
}


<?php

namespace ElfSundae\Laravel\Api\Middleware;

use Closure;
use Illuminate\Http\Request;
use ElfSundae\Laravel\Api\Token;
use ElfSundae\Laravel\Api\Helper;
use ElfSundae\Laravel\Api\Exceptions\InvalidApiTokenException;

class VerifyApiToken
{
    /**
     * The Token instance.
     *
     * @var \ElfSundae\Laravel\Api\Token
     */
    protected $token;

    /**
     * The URIs that should be excluded from token verification.
     *
     * @var array
     */
    protected $except = [];

    /**
     * Create the middleware.
     *
     * @param  \ElfSundae\Laravel\Api\Token  $token
     */
    public function __construct(Token $token)
    {
        $this->token = $token;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     *
     * @throws \ElfSundae\Laravel\Api\Exceptions\InvalidApiTokenException
     */
    public function handle($request, Closure $next)
    {
        if ($this->inExceptArray($request) || $this->verifyToken($request)) {
            return $next(
                Helper::setCurrentAppKeyForRequest($this->getKeyFromRequest($request), $request)
            );
        }

        throw new InvalidApiTokenException;
    }

    /**
     * Determine if the request has a URI that should be passed through verification.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function inExceptArray(Request $request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }

            if ($request->is($except)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Verify the api token from request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function verifyToken(Request $request)
    {
        $time = (int) ($request->input('_time') ?: $request->header('X-API-TIME'));
        $token = $request->input('_token') ?: $request->header('X-API-TOKEN');

        return abs(time() - $time) < (int) config('api.token_duration') &&
            $this->token->verify($token, $this->getKeyFromRequest($request), $time);
    }

    /**
     * Get the app key from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function getKeyFromRequest(Request $request)
    {
        return $request->input('_key') ?: $request->header('X-API-KEY');
    }
}


<?php
/**
 * Authors: Alex Gusev <alex@flancer64.com>
 * Since: 2018
 */

namespace Praxigento\Accounting\Service\Account\Balance\Calc\A;

use Praxigento\Accounting\Api\Repo\Query\Balance\OnDate\Closing as QBalOnDate;
use Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Request as ALastDateRequest;
use Praxigento\Accounting\Repo\Data\Account as EAccount;
use Praxigento\Accounting\Repo\Data\Transaction as ETrans;
use Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneType\A\Repo\Query\GetTransactions as QGetTrans;
use Praxigento\Accounting\Service\Account\Balance\Reset\Request as AResetRequest;

/**
 * Re-calculate balances for given asset type.
 */
class ProcessOneType
{
    private const BND_ASSET_TYPE_ID = 'assetTypeId';

    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Psr\Log\LoggerInterface */
    private $logger;
    /** @var \Praxigento\Accounting\Api\Repo\Query\Balance\OnDate\Closing */
    private $qBalancesOnDate;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneType\A\Repo\Query\GetTransactions */
    private $qGetTrans;
    /** @var \Praxigento\Accounting\Service\Account\Balance\LastDate */
    private $servBalanceLastDate;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Reset */
    private $servBalanceReset;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Calc\A\Z\CollectTransactions */
    private $zCollect;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Calc\A\Z\UpdateBalances */
    private $zUpdate;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Accounting\Api\Repo\Query\Balance\OnDate\Closing $qBalancesOnDate,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Accounting\Service\Account\Balance\LastDate $servBalanceLastDate,
        \Praxigento\Accounting\Service\Account\Balance\Reset $servBalanceReset,
        \Praxigento\Accounting\Service\Account\Balance\Calc\A\Z\CollectTransactions $zCollect,
        \Praxigento\Accounting\Service\Account\Balance\Calc\A\Z\UpdateBalances $zUpdate,
        \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneType\A\Repo\Query\GetTransactions $qGetTrans
    ) {
        $this->logger = $logger;
        $this->qBalancesOnDate = $qBalancesOnDate;
        $this->hlpPeriod = $hlpPeriod;
        $this->servBalanceLastDate = $servBalanceLastDate;
        $this->servBalanceReset = $servBalanceReset;
        $this->zCollect = $zCollect;
        $this->zUpdate = $zUpdate;
        $this->qGetTrans = $qGetTrans;
    }

    public function exec($assetTypeId, $dsBalClose)
    {
        $dsLast = $this->getBalancesLastDate($assetTypeId);
        /* reset balances if requested */
        if ($dsLast > $dsBalClose) {
            $this->resetBalances($assetTypeId, $dsBalClose);
            $dsLast = $dsBalClose;
        }
        /* get closing balances */
        $balances = $this->getBalanceClosing($assetTypeId, $dsLast);
        /* get transactions starting from the last date */
        $trans = $this->getTransactions($assetTypeId, $dsLast);
        if (is_array($trans) && count($trans)) {
            /* collect transactions by date (compose records for balances table) */
            $updates = $this->zCollect->exec($balances, $trans);
            $this->zUpdate->exec($updates);
        } else {
            $msg = "There is no transactions for asset type #$assetTypeId starting from $dsLast";
            $this->logger->info($msg);
        }
    }

    private function getBalanceClosing($assetTypeId, $dsClose)
    {
        $result = [];

        $query = $this->qBalancesOnDate->build();
        $conn = $query->getConnection();

        $where = QBalOnDate::AS_ACC . '.' . EAccount::A_ASSET_TYPE_ID . '=:' . self::BND_ASSET_TYPE_ID;
        $query->where($where);

        $bind = [
            QBalOnDate::BND_MAX_DATE => $dsClose,
            self::BND_ASSET_TYPE_ID => $assetTypeId
        ];
        $rs = $conn->fetchAll($query, $bind);
        if (is_array($rs)) {
            foreach ($rs as $one) {
                $accId = $one[QBalOnDate::A_ACC_ID];
                $balance = $one[QBalOnDate::A_BALANCE];
                $result [$accId] = $balance;
            }
        }
        return $result;
    }

    /**
     * Get the last datestamp for existing balances for given asset.
     *
     * @param int $assetTypeId
     * @return string
     * @throws \Exception
     */
    private function getBalancesLastDate($assetTypeId)
    {
        $reqLastDate = new ALastDateRequest();
        $reqLastDate->setAssetTypeId($assetTypeId);
        $respLastDate = $this->servBalanceLastDate->exec($reqLastDate);
        $result = $respLastDate->getLastDate();
        return $result;
    }

    /**
     * @param int $assetTypeId
     * @param string $dsClose YYYYMMDD (excl.)
     * @return ETrans[]
     * @throws \Exception
     */
    private function getTransactions($assetTypeId, $dsClose)
    {
        $result = [];
        /* first date should be after closing balance date */
        $tsFrom = $this->hlpPeriod->getTimestampNextFrom($dsClose);

        $query = $this->qGetTrans->build();
        $conn = $query->getConnection();
        $bind = [
            QGetTrans::BND_DATE_APPL => $tsFrom,
            QGetTrans::BND_ASSET_TYPE => $assetTypeId
        ];
        $rs = $conn->fetchAll($query, $bind);
        if ($rs) {
            foreach ($rs as $one) {
                $item = new ETrans($one);
                $result[] = $item;
            }
        }
        return $result;
    }

    /**
     * @param int $assetType
     * @param string $dsFrom
     * @throws \Exception
     */
    private function resetBalances($assetType, $dsFrom)
    {
        $req = new AResetRequest();
        $req->setAssetTypes([$assetType]);
        $req->setDateFrom($dsFrom);
        $this->servBalanceReset->exec($req);
    }

}


<?php

namespace Interpro\ImageAggr\Executors;

use Interpro\Core\Contracts\Executor\BInitializer;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\ImageAggr\Contracts\Operation\InitOperation;
use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet;

class Initializer implements BInitializer
{
    private $operation;
    private $settingsSet;

    public function __construct(InitOperation $operation, ImageSettingsSet $settingsSet)
    {
        $this->operation = $operation;
        $this->settingsSet = $settingsSet;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'imageaggr';
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $own
     * @param mixed $user_attrs
     *
     * @return void
     */
    public function init(ARef $ref, OwnField $own, $user_attrs = null)
    {
        if(!is_array($user_attrs))
        {
            $user_attrs = [];
        }

        $imageSetting = $this->settingsSet->getImage($own);

        $this->operation->execute($ref, $imageSetting, $user_attrs);
    }
}


<?php

namespace Interpro\ImageAggr\Executors;

use Interpro\Core\Contracts\Executor\RefConsistExecutor as RefConsistExecutorInterface;
use Interpro\Core\Contracts\Ref\ARef;

class ModImagesRefConsistExecutor implements RefConsistExecutorInterface
{
    /**
     * @return string
     */
    public function getFamily()
    {
        return 'modimages';
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return void
     */
    public function execute(ARef $ref)
    {
        //Ссылок на сущьности А типа в этом типе нет
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     *
     * @return bool
     */
    public function exist(ARef $ref)
    {
        $name = $ref->getType()->getName();

        if($name === 'modimages')
        {
            return true;
        }

        return false;
    }
}


<?php

namespace Nobox\LazyStrings;

use Exception;

class Validator
{
    /**
     * Provided url must be a valid google doc url.
     *
     * @param string $url Url of google doc.
     *
     * @return boolean
     */
    public function validateDocUrl($url)
    {
        $pattern = '/http:\/\/docs\.google\.com\/spreadsheets\/d\/.*\/export\?format=csv/';

        if (is_null($url) || $url === '' || preg_match($pattern, $url) !== 1) {
            return false;
        }

        return true;
    }

    /**
     * Make sure that at least 1 sheet id is provided.
     *
     * @param array $sheets The sheets to validate.
     *
     * @return boolean
     */
    public function validateSheets(array $sheets)
    {
        if (count($sheets) === 0) {
            throw new Exception('No sheets were provided.');
        }
    }
}


<?php

namespace Onoi\Tesa;

/**
 * Romanization and transliteration support for a selected group of characters.
 *
 * @see http://www.loc.gov/catdir/cpso/roman.html
 * @see https://en.wikipedia.org/wiki/List_of_ISO_transliterations
 *
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class Transliterator {

	/**
	 * Any change to the mapping of this file should be reflected in a version
	 * change (the version number does not necessarily correlate with the
	 * library version)
	 */
	const VERSION = '0.2';

	/**
	 * Transliterator supported option flags
	 */
	const NONE = 0x1;
	const DIACRITICS = 0x2;
	const GREEK = 0x4;

	/**
	 * Convert diacritics (e.g. accents) of a string to a Latin representation
	 *
	 * @see http://jsperf.com/latinize
	 *
	 * - Changed the German conversion rules for the diaeresis representation
	 *   (Ü to Ue, Ä to ae etc.)
	 * - Added ß/ss
	 *
	 *
	 * @var array
	 */
	private static $diacriticsMap = array(
			"Á" => "A", "Ă" => "A", "Ắ" => "A", "Ặ" => "A", "Ằ" => "A", "Ẳ" => "A", "Ẵ" => "A",
			"Ǎ" => "A", "Â" => "A", "Ấ" => "A", "Ậ" => "A", "Ầ" => "A", "Ẩ" => "A", "Ẫ" => "A",
			"Ä" => "AE", "Ǟ" => "A", "Ȧ" => "A", "Ǡ" => "A", "Ạ" => "A", "Ȁ" => "A", "À" => "A",
			"Ả" => "A", "Ȃ" => "A", "Ā" => "A", "Ą" => "A", "Å" => "A", "Ǻ" => "A", "Ḁ" => "A",
			"Ⱥ" => "A", "Ã" => "A", "Ꜳ" => "AA", "Æ" => "AE", "Ǽ" => "AE", "Ǣ" => "AE", "Ꜵ" => "AO",
			"Ꜷ" => "AU", "Ꜹ" => "AV", "Ꜻ" => "AV", "Ꜽ" => "AY", "Ḃ" => "B", "Ḅ" => "B", "Ɓ" => "B",
			"Ḇ" => "B", "Ƀ" => "B", "Ƃ" => "B", "Ć" => "C", "Č" => "C", "Ç" => "C", "Ḉ" => "C",
			"Ĉ" => "C", "Ċ" => "C", "Ƈ" => "C", "Ȼ" => "C", "Ď" => "D", "Ḑ" => "D", "Ḓ" => "D",
			"Ḋ" => "D", "Ḍ" => "D", "Ɗ" => "D", "Ḏ" => "D", "ǲ" => "D", "ǅ" => "D", "Đ" => "D",
			"Ƌ" => "D", "Ǳ" => "DZ", "Ǆ" => "DZ", "É" => "E", "Ĕ" => "E", "Ě" => "E", "Ȩ" => "E",
			"Ḝ" => "E", "Ê" => "E", "Ế" => "E", "Ệ" => "E", "Ề" => "E", "Ể" => "E", "Ễ" => "E",
			"Ḙ" => "E", "Ë" => "E", "Ė" => "E", "Ẹ" => "E", "Ȅ" => "E", "È" => "E", "Ẻ" => "E",
			"Ȇ" => "E", "Ē" => "E", "Ḗ" => "E", "Ḕ" => "E", "Ę" => "E", "Ɇ" => "E", "Ẽ" => "E",
			"Ḛ" => "E", "Ꝫ" => "ET", "Ḟ" => "F", "Ƒ" => "F", "Ǵ" => "G", "Ğ" => "G", "Ǧ" => "G",
			"Ģ" => "G", "Ĝ" => "G", "Ġ" => "G", "Ɠ" => "G", "Ḡ" => "G", "Ǥ" => "G", "Ḫ" => "H",
			"Ȟ" => "H", "Ḩ" => "H", "Ĥ" => "H", "Ⱨ" => "H", "Ḧ" => "H", "Ḣ" => "H", "Ḥ" => "H",
			"Ħ" => "H", "Í" => "I", "Ĭ" => "I", "Ǐ" => "I", "Î" => "I", "Ï" => "I", "Ḯ" => "I",
			"İ" => "I", "Ị" => "I", "Ȉ" => "I", "Ì" => "I", "Ỉ" => "I", "Ȋ" => "I", "Ī" => "I",
			"Į" => "I", "Ɨ" => "I", "Ĩ" => "I", "Ḭ" => "I", "Ꝺ" => "D", "Ꝼ" => "F", "Ᵹ" => "G",
			"Ꞃ" => "R", "Ꞅ" => "S", "Ꞇ" => "T", "Ꝭ" => "IS", "Ĵ" => "J", "Ɉ" => "J", "Ḱ" => "K",
			"Ǩ" => "K", "Ķ" => "K", "Ⱪ" => "K", "Ꝃ" => "K", "Ḳ" => "K", "Ƙ" => "K", "Ḵ" => "K",
			"Ꝁ" => "K", "Ꝅ" => "K", "Ĺ" => "L", "Ƚ" => "L", "Ľ" => "L", "Ļ" => "L", "Ḽ" => "L",
			"Ḷ" => "L", "Ḹ" => "L", "Ⱡ" => "L", "Ꝉ" => "L", "Ḻ" => "L", "Ŀ" => "L", "Ɫ" => "L",
			"ǈ" => "L", "Ł" => "L", "Ǉ" => "LJ", "Ḿ" => "M", "Ṁ" => "M", "Ṃ" => "M", "Ɱ" => "M",
			"Ń" => "N", "Ň" => "N", "Ņ" => "N", "Ṋ" => "N", "Ṅ" => "N", "Ṇ" => "N", "Ǹ" => "N",
			"Ɲ" => "N", "Ṉ" => "N", "Ƞ" => "N", "ǋ" => "N", "Ñ" => "N", "Ǌ" => "NJ", "Ó" => "O",
			"Ŏ" => "O", "Ǒ" => "O", "Ô" => "O", "Ố" => "O", "Ộ" => "O", "Ồ" => "O", "Ổ" => "O",
			"Ỗ" => "O", "Ö" => "OE", "Ȫ" => "O", "Ȯ" => "O", "Ȱ" => "O", "Ọ" => "O", "Ő" => "O",
			"Ȍ" => "O", "Ò" => "O", "Ỏ" => "O", "Ơ" => "O", "Ớ" => "O", "Ợ" => "O", "Ờ" => "O",
			"Ở" => "O", "Ỡ" => "O", "Ȏ" => "O", "Ꝋ" => "O", "Ꝍ" => "O", "Ō" => "O", "Ṓ" => "O",
			"Ṑ" => "O", "Ɵ" => "O", "Ǫ" => "O", "Ǭ" => "O", "Ø" => "O", "Ǿ" => "O", "Õ" => "O",
			"Ṍ" => "O", "Ṏ" => "O", "Ȭ" => "O", "Ƣ" => "OI", "Ꝏ" => "OO", "Ɛ" => "E", "Ɔ" => "O",
			"Ȣ" => "OU", "Ṕ" => "P", "Ṗ" => "P", "Ꝓ" => "P", "Ƥ" => "P", "Ꝕ" => "P", "Ᵽ" => "P",
			"Ꝑ" => "P", "Ꝙ" => "Q", "Ꝗ" => "Q", "Ŕ" => "R", "Ř" => "R", "Ŗ" => "R", "Ṙ" => "R",
			"Ṛ" => "R", "Ṝ" => "R", "Ȑ" => "R", "Ȓ" => "R", "Ṟ" => "R", "Ɍ" => "R", "Ɽ" => "R",
			"Ꜿ" => "C", "Ǝ" => "E", "Ś" => "S", "Ṥ" => "S", "Š" => "S", "Ṧ" => "S", "Ş" => "S",
			"Ŝ" => "S", "Ș" => "S", "Ṡ" => "S", "Ṣ" => "S", "Ṩ" => "S", "ß" => "ss",
			"Ť" => "T", "Ţ" => "T",
			"Ṱ" => "T", "Ț" => "T", "Ⱦ" => "T", "Ṫ" => "T", "Ṭ" => "T", "Ƭ" => "T", "Ṯ" => "T",
			"Ʈ" => "T", "Ŧ" => "T", "Ɐ" => "A", "Ꞁ" => "L", "Ɯ" => "M", "Ʌ" => "V", "Ꜩ" => "TZ",
			"Ú" => "U", "Ŭ" => "U", "Ǔ" => "U", "Û" => "U", "Ṷ" => "U", "Ü" => "UE", "Ǘ" => "U",
			"Ǚ" => "U", "Ǜ" => "U", "Ǖ" => "U", "Ṳ" => "U", "Ụ" => "U", "Ű" => "U", "Ȕ" => "U",
			"Ù" => "U", "Ủ" => "U", "Ư" => "U", "Ứ" => "U", "Ự" => "U", "Ừ" => "U", "Ử" => "U",
			"Ữ" => "U", "Ȗ" => "U", "Ū" => "U", "Ṻ" => "U", "Ų" => "U", "Ů" => "U", "Ũ" => "U",
			"Ṹ" => "U", "Ṵ" => "U", "Ꝟ" => "V", "Ṿ" => "V", "Ʋ" => "V", "Ṽ" => "V", "Ꝡ" => "VY",
			"Ẃ" => "W", "Ŵ" => "W", "Ẅ" => "W", "Ẇ" => "W", "Ẉ" => "W", "Ẁ" => "W", "Ⱳ" => "W",
			"Ẍ" => "X", "Ẋ" => "X", "Ý" => "Y", "Ŷ" => "Y", "Ÿ" => "Y", "Ẏ" => "Y", "Ỵ" => "Y",
			"Ỳ" => "Y", "Ƴ" => "Y", "Ỷ" => "Y", "Ỿ" => "Y", "Ȳ" => "Y", "Ɏ" => "Y", "Ỹ" => "Y",
			"Ź" => "Z", "Ž" => "Z", "Ẑ" => "Z", "Ⱬ" => "Z", "Ż" => "Z", "Ẓ" => "Z", "Ȥ" => "Z",
			"Ẕ" => "Z", "Ƶ" => "Z", "Ĳ" => "IJ", "Œ" => "OE", "ᴀ" => "A", "ᴁ" => "AE", "ʙ" => "B",
			"ᴃ" => "B", "ᴄ" => "C", "ᴅ" => "D", "ᴇ" => "E", "ꜰ" => "F", "ɢ" => "G", "ʛ" => "G",
			"ʜ" => "H", "ɪ" => "I", "ʁ" => "R", "ᴊ" => "J", "ᴋ" => "K", "ʟ" => "L", "ᴌ" => "L",
			"ᴍ" => "M", "ɴ" => "N", "ᴏ" => "O", "ɶ" => "OE", "ᴐ" => "O", "ᴕ" => "OU", "ᴘ" => "P",
			"ʀ" => "R", "ᴎ" => "N", "ᴙ" => "R", "ꜱ" => "S", "ᴛ" => "T", "ⱻ" => "E", "ᴚ" => "R",
			"ᴜ" => "U", "ᴠ" => "V", "ᴡ" => "W", "ʏ" => "Y", "ᴢ" => "Z", "á" => "a", "ă" => "a",
			"ắ" => "a", "ặ" => "a", "ằ" => "a", "ẳ" => "a", "ẵ" => "a", "ǎ" => "a", "â" => "a",
			"ấ" => "a", "ậ" => "a", "ầ" => "a", "ẩ" => "a", "ẫ" => "a", "ä" => "ae", "ǟ" => "a",
			"ȧ" => "a", "ǡ" => "a", "ạ" => "a", "ȁ" => "a", "à" => "a", "ả" => "a", "ȃ" => "a",
			"ā" => "a", "ą" => "a", "ᶏ" => "a", "ẚ" => "a", "å" => "a", "ǻ" => "a", "ḁ" => "a",
			"ⱥ" => "a", "ã" => "a", "ꜳ" => "aa", "æ" => "ae", "ǽ" => "ae", "ǣ" => "ae", "ꜵ" => "ao",
			"ꜷ" => "au", "ꜹ" => "av", "ꜻ" => "av", "ꜽ" => "ay", "ḃ" => "b", "ḅ" => "b", "ɓ" => "b",
			"ḇ" => "b", "ᵬ" => "b", "ᶀ" => "b", "ƀ" => "b", "ƃ" => "b", "ɵ" => "o", "ć" => "c",
			"č" => "c", "ç" => "c", "ḉ" => "c", "ĉ" => "c", "ɕ" => "c", "ċ" => "c", "ƈ" => "c",
			"ȼ" => "c", "ď" => "d", "ḑ" => "d", "ḓ" => "d", "ȡ" => "d", "ḋ" => "d", "ḍ" => "d",
			"ɗ" => "d", "ᶑ" => "d", "ḏ" => "d", "ᵭ" => "d", "ᶁ" => "d", "đ" => "d", "ɖ" => "d",
			"ƌ" => "d", "ı" => "i", "ȷ" => "j", "ɟ" => "j", "ʄ" => "j", "ǳ" => "dz", "ǆ" => "dz",
			"é" => "e", "ĕ" => "e", "ě" => "e", "ȩ" => "e", "ḝ" => "e", "ê" => "e", "ế" => "e",
			"ệ" => "e", "ề" => "e", "ể" => "e", "ễ" => "e", "ḙ" => "e", "ë" => "e", "ė" => "e",
			"ẹ" => "e", "ȅ" => "e", "è" => "e", "ẻ" => "e", "ȇ" => "e", "ē" => "e", "ḗ" => "e",
			"ḕ" => "e", "ⱸ" => "e", "ę" => "e", "ᶒ" => "e", "ɇ" => "e", "ẽ" => "e", "ḛ" => "e",
			"ꝫ" => "et", "ḟ" => "f", "ƒ" => "f", "ᵮ" => "f", "ᶂ" => "f", "ǵ" => "g", "ğ" => "g",
			"ǧ" => "g", "ģ" => "g", "ĝ" => "g", "ġ" => "g", "ɠ" => "g", "ḡ" => "g", "ᶃ" => "g",
			"ǥ" => "g", "ḫ" => "h", "ȟ" => "h", "ḩ" => "h", "ĥ" => "h", "ⱨ" => "h", "ḧ" => "h",
			"ḣ" => "h", "ḥ" => "h", "ɦ" => "h", "ẖ" => "h", "ħ" => "h", "ƕ" => "hv", "í" => "i",
			"ĭ" => "i", "ǐ" => "i", "î" => "i", "ï" => "i", "ḯ" => "i", "ị" => "i", "ȉ" => "i",
			"ì" => "i", "ỉ" => "i", "ȋ" => "i", "ī" => "i", "į" => "i", "ᶖ" => "i", "ɨ" => "i",
			"ĩ" => "i", "ḭ" => "i", "ꝺ" => "d", "ꝼ" => "f", "ᵹ" => "g", "ꞃ" => "r", "ꞅ" => "s",
			"ꞇ" => "t", "ꝭ" => "is", "ǰ" => "j", "ĵ" => "j", "ʝ" => "j", "ɉ" => "j", "ḱ" => "k",
			"ǩ" => "k", "ķ" => "k", "ⱪ" => "k", "ꝃ" => "k", "ḳ" => "k", "ƙ" => "k", "ḵ" => "k",
			"ᶄ" => "k", "ꝁ" => "k", "ꝅ" => "k", "ĺ" => "l", "ƚ" => "l", "ɬ" => "l", "ľ" => "l",
			"ļ" => "l", "ḽ" => "l", "ȴ" => "l", "ḷ" => "l", "ḹ" => "l", "ⱡ" => "l", "ꝉ" => "l",
			"ḻ" => "l", "ŀ" => "l", "ɫ" => "l", "ᶅ" => "l", "ɭ" => "l", "ł" => "l", "ǉ" => "lj",
			"ſ" => "s", "ẜ" => "s", "ẛ" => "s", "ẝ" => "s", "ḿ" => "m", "ṁ" => "m", "ṃ" => "m",
			"ɱ" => "m", "ᵯ" => "m", "ᶆ" => "m", "ń" => "n", "ň" => "n", "ņ" => "n", "ṋ" => "n",
			"ȵ" => "n", "ṅ" => "n", "ṇ" => "n", "ǹ" => "n", "ɲ" => "n", "ṉ" => "n", "ƞ" => "n",
			"ᵰ" => "n", "ᶇ" => "n", "ɳ" => "n", "ñ" => "n", "ǌ" => "nj", "ó" => "o", "ŏ" => "o",
			"ǒ" => "o", "ô" => "o", "ố" => "o", "ộ" => "o", "ồ" => "o", "ổ" => "o", "ỗ" => "o",
			"ö" => "oe", "ȫ" => "o", "ȯ" => "o", "ȱ" => "o", "ọ" => "o", "ő" => "o", "ȍ" => "o",
			"ò" => "o", "ỏ" => "o", "ơ" => "o", "ớ" => "o", "ợ" => "o", "ờ" => "o", "ở" => "o",
			"ỡ" => "o", "ȏ" => "o", "ꝋ" => "o", "ꝍ" => "o", "ⱺ" => "o", "ō" => "o", "ṓ" => "o",
			"ṑ" => "o", "ǫ" => "o", "ǭ" => "o", "ø" => "o", "ǿ" => "o", "õ" => "o", "ṍ" => "o",
			"ṏ" => "o", "ȭ" => "o", "ƣ" => "oi", "ꝏ" => "oo", "ɛ" => "e", "ᶓ" => "e", "ɔ" => "o",
			"ᶗ" => "o", "ȣ" => "ou", "ṕ" => "p", "ṗ" => "p", "ꝓ" => "p", "ƥ" => "p", "ᵱ" => "p",
			"ᶈ" => "p", "ꝕ" => "p", "ᵽ" => "p", "ꝑ" => "p", "ꝙ" => "q", "ʠ" => "q", "ɋ" => "q",
			"ꝗ" => "q", "ŕ" => "r", "ř" => "r", "ŗ" => "r", "ṙ" => "r", "ṛ" => "r", "ṝ" => "r",
			"ȑ" => "r", "ɾ" => "r", "ᵳ" => "r", "ȓ" => "r", "ṟ" => "r", "ɼ" => "r", "ᵲ" => "r",
			"ᶉ" => "r", "ɍ" => "r", "ɽ" => "r", "ↄ" => "c", "ꜿ" => "c", "ɘ" => "e", "ɿ" => "r",
			"ś" => "s", "ṥ" => "s", "š" => "s", "ṧ" => "s", "ş" => "s", "ŝ" => "s", "ș" => "s",
			"ṡ" => "s", "ṣ" => "s", "ṩ" => "s", "ʂ" => "s", "ᵴ" => "s", "ᶊ" => "s", "ȿ" => "s",
			"ɡ" => "g", "ᴑ" => "o", "ᴓ" => "o", "ᴝ" => "u", "ť" => "t", "ţ" => "t", "ṱ" => "t",
			"ț" => "t", "ȶ" => "t", "ẗ" => "t", "ⱦ" => "t", "ṫ" => "t", "ṭ" => "t", "ƭ" => "t",
			"ṯ" => "t", "ᵵ" => "t", "ƫ" => "t", "ʈ" => "t", "ŧ" => "t", "ᵺ" => "th", "ɐ" => "a",
			"ᴂ" => "ae", "ǝ" => "e", "ᵷ" => "g", "ɥ" => "h", "ʮ" => "h", "ʯ" => "h", "ᴉ" => "i",
			"ʞ" => "k", "ꞁ" => "l", "ɯ" => "m", "ɰ" => "m", "ᴔ" => "oe", "ɹ" => "r", "ɻ" => "r",
			"ɺ" => "r", "ⱹ" => "r", "ʇ" => "t", "ʌ" => "v", "ʍ" => "w", "ʎ" => "y", "ꜩ" => "tz",
			"ú" => "u", "ŭ" => "u", "ǔ" => "u", "û" => "u", "ṷ" => "u", "ü" => "ue", "ǘ" => "u",
			"ǚ" => "u", "ǜ" => "u", "ǖ" => "u", "ṳ" => "u", "ụ" => "u", "ű" => "u", "ȕ" => "u",
			"ù" => "u", "ủ" => "u", "ư" => "u", "ứ" => "u", "ự" => "u", "ừ" => "u", "ử" => "u",
			"ữ" => "u", "ȗ" => "u", "ū" => "u", "ṻ" => "u", "ų" => "u", "ᶙ" => "u", "ů" => "u",
			"ũ" => "u", "ṹ" => "u", "ṵ" => "u", "ᵫ" => "ue", "ꝸ" => "um", "ⱴ" => "v", "ꝟ" => "v",
			"ṿ" => "v", "ʋ" => "v", "ᶌ" => "v", "ⱱ" => "v", "ṽ" => "v", "ꝡ" => "vy", "ẃ" => "w",
			"ŵ" => "w", "ẅ" => "w", "ẇ" => "w", "ẉ" => "w", "ẁ" => "w", "ⱳ" => "w", "ẘ" => "w",
			"ẍ" => "x", "ẋ" => "x", "ᶍ" => "x", "ý" => "y", "ŷ" => "y", "ÿ" => "y", "ẏ" => "y",
			"ỵ" => "y", "ỳ" => "y", "ƴ" => "y", "ỷ" => "y", "ỿ" => "y", "ȳ" => "y", "ẙ" => "y",
			"ɏ" => "y", "ỹ" => "y", "ź" => "z", "ž" => "z", "ẑ" => "z", "ʑ" => "z", "ⱬ" => "z",
			"ż" => "z", "ẓ" => "z", "ȥ" => "z", "ẕ" => "z", "ᵶ" => "z", "ᶎ" => "z", "ʐ" => "z",
			"ƶ" => "z", "ɀ" => "z", "ﬀ" => "ff", "ﬃ" => "ffi", "ﬄ" => "ffl", "ﬁ" => "fi",
			"ﬂ" => "fl", "ĳ" => "ij", "œ" => "oe", "ﬆ" => "st", "ₐ" => "a", "ₑ" => "e", "ᵢ" => "i",
			"ⱼ" => "j", "ₒ" => "o", "ᵣ" => "r", "ᵤ" => "u", "ᵥ" => "v", "ₓ" => "x"
		);

		/**
		 * @see http://en.wikipedia.org/wiki/ISO_843
		 * @see https://en.wikipedia.org/wiki/Romanization_of_Greek
		 *
		 * Resolving diacritic letters can be done using it with option (
		 * Transliterator::DIACRITICS | Transliterator::GREEK )
		 *
		 * @var array
		 */
		private static $greekMap = array(

			"ου"=> "ou",
			"Ου"=> "Ou",
			"Οι"=> "Oi",
			"οι"=> "oi",
			"Υι"=> "Yi",
			"υι"=> "yi",
			"Ού"=> "Oú",
			"ού"=> "oú",

			"Α" => "A",
			"Ά" => "Á",
			"Β" => "V",
			"Γ" => "G",
			"Δ" => "D",
			"Ε" => "E",
			"Έ" => "É",
			"Ζ" => "Z",
			"Η" => "Ī",
			"Ή" => "Ī́",
			"Θ" => "Th",
			"Ι" => "I",
			"Ί" => "Í",
			"Ϊ" => "Ï",
			"ΐ" => "ḯ",
			"Κ" => "K",
			"Λ" => "L",
			"Μ" => "M",
			"Ν" => "N",
			"Ξ" => "X",
			"Ο" => "O",
			"Ό" => "Ó",
			"Π" => "P",
			"Ρ" => "R",
			"Σ" => "S",
			"ς" => "s",
			"Τ" => "T",
			"Υ" => "Y",
			"Ύ" => "Ý",
			"Ϋ" => "Ÿ",
			"ΰ" => "ÿ́",
			"Φ" => "F",
			"Χ" => "Ch",
			"Ψ" => "Ps",
			"Ω" => "Ō",
			"Ώ" => "Ṓ",
			"α" => "a",
			"ά" => "á",
			"β" => "v",
			"γ" => "g",
			"δ" => "d",
			"ε" => "e",
			"έ" => "é",
			"ζ" => "z",
			"η" => "ī",
			"ή" => "ī́",
			"θ" => "th",
			"ι" => "i",
			"ί" => "í",
			"ϊ" => "ï",
			"κ" => "k",
			"λ" => "l",
			"μ" => "m",
			"ν" => "n",
			"ξ" => "x",
			"ο" => "o",
			"ό" => "ó",
			"π" => "p",
			"ρ" => "r",
			"σ" => "s",
			"τ" => "t",
			"υ" => "y",
			"ύ" => "ý",
			"ϋ" => "ÿ",
			"φ" => "f",
			"χ" => "ch",
			"ψ" => "ps",
			"ω" => "ō",
			"ώ" => "ṓ",
		);

	/**
	 * @var array
	 */
	private static $transliterationMap = array();

	/**
	 * @since 0.1
	 *
	 * @param string $string
	 * @param integer $flag
	 *
	 * @return string
	 */
	public static function transliterate( $string, $flag = self::DIACRITICS ) {

		if ( $flag === ( $flag | self::NONE ) ) {
			return $string;
		}

		if ( !isset( self::$transliterationMap[$flag] ) ) {
			$transliterationMap = array();

			if ( $flag === ( $flag | self::GREEK ) ) {
				$transliterationMap += self::$greekMap;
			}

			if ( $flag === ( $flag | self::DIACRITICS ) ) {
				$transliterationMap += self::$diacriticsMap;
			}

			// Keep it static for the duration of a request to avoid negative
			// performance impact
			self::$transliterationMap[$flag]['k'] = array_keys( $transliterationMap );
			self::$transliterationMap[$flag]['v'] = array_values( $transliterationMap );

			unset( $transliterationMap );
		}

		return str_replace(
			self::$transliterationMap[$flag]['k'],
			self::$transliterationMap[$flag]['v'],
			$string
		);
	}

}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Operation\CleanPhOperation as CleanPhOperationInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;

class CleanPhOperation extends Operation implements CleanPhOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting)
    {
        $this->checkOwner($aRef);

        $this->deleteAllFiles($aRef, $imageSetting);

        $original_file_path = $this->phAgent->getPh(
            $imageSetting->getWidth(),
            $imageSetting->getHeight(),
            $imageSetting->getColor()
        );

        $this->dbAgent->imageToDb($aRef, $imageSetting, ['link' => $original_file_path]);

        $this->makePhImageResizes($aRef, $imageSetting);
        $this->makePhImageCrops($aRef, $imageSetting);
    }
}


<?php

namespace Interpro\ImageAggr\Settings\Collection;

use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Enum\OddEven;
use Interpro\Core\Iterator\FieldIterator;
use Interpro\Core\Iterator\OddEvenIterator;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet as ImageSettingsSetInterface;

class ImageSettingsSet implements ImageSettingsSetInterface
{
    private $images;
    private $image_names;
    private $position;

    /**
     * @param array $images
     */
    public function __construct(
        array $images
    ){
        $this->images      = $images;
        $this->image_names = array_keys($images);
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $field
     *
     * @return \Interpro\ImageAggr\Contracts\Settings\ImageSetting
     */
    public function getImage(OwnField $field)
    {
        $key = $field->getOwnerTypeName().'.'.$field->getName();

        if(array_key_exists($key, $this->images))
        {
            return $this->images[$key];
        }
        else
        {
            throw new ImageAggrException('Картинка по имени: '.$key.' не найдена в коллекции!');
        }
    }

    function rewind()
    {
        $this->position = 0;
    }

    function current()
    {
        $name = $this->image_names[$this->position];
        return $this->images[$name];
    }

    function key()
    {
        return $this->image_names[$this->position];
    }

    function next()
    {
        ++$this->position;
    }

    function valid()
    {
        return isset($this->image_names[$this->position]);
    }

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

    public function sortBy($path, $sort = 'ASC')
    {
        return new FieldIterator($this, $path, $sort);
    }

    public function odd()
    {
        return new OddEvenIterator($this->images, OddEven::ODD);
    }

    public function even()
    {
        return new OddEvenIterator($this->images, OddEven::EVEN);
    }

}


<?php

namespace ElfSundae\Laravel\Api;

use Illuminate\Support\ServiceProvider;
use Laravel\Lumen\Application as LumenApplication;

class ApiServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app instanceof LumenApplication) {
            $this->app->configure('api'); // @codeCoverageIgnore
        }

        $this->mergeConfigFrom(__DIR__.'/../config/api.php', 'api');

        $this->registerClient();

        $this->registerToken();

        if ($this->app->runningInConsole()) {
            $this->registerForConsole();
        }
    }

    /**
     * Register the Client singleton.
     *
     * @return void
     */
    protected function registerClient()
    {
        $this->app->singleton('api.client', function ($app) {
            $client = new Client(
                $app['encrypter'],
                $app['config']->get('api.clients', [])
            );

            $client->setDefaultAppKey($app['config']->get('api.default_client'));

            return $client;
        });

        $this->app->alias('api.client', Client::class);
    }

    /**
     * Register the Token singleton.
     *
     * @return void
     */
    protected function registerToken()
    {
        $this->app->singleton('api.token', function ($app) {
            return new Token($app['api.client']);
        });

        $this->app->alias('api.token', Token::class);
    }

    /**
     * Register for console.
     *
     * @return void
     */
    protected function registerForConsole()
    {
        $this->publishes([
            __DIR__.'/../config/api.php' => base_path('config/api.php'),
        ], 'laravel-api');

        $this->commands([
            Console\GenerateClientCommand::class,
            Console\GenerateTokenCommand::class,
        ]);
    }
}