<?php

namespace Interpro\ImageAggr\Operation;

use Illuminate\Support\Facades\File;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;
use Interpro\ImageAggr\Exception\OperationException;
use Interpro\ImageAggr\Contracts\Operation\Enum\MimeType;
use Interpro\ImageAggr\Contracts\Settings\Enum\GenVariant;
use Intervention\Image\Facades\Image;
use Interpro\ImageAggr\Contracts\Operation\SaveOperation as SaveOperationInterface;

class SaveOperation extends Operation implements SaveOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param array $user_attrs
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting, array $user_attrs = [])
    {
        if(array_key_exists('update_flag', $user_attrs))
        {
            if($user_attrs['update_flag'] === 'false')
            {
                $update_flag = false;
            }
            else
            {
                $update_flag = (bool) $user_attrs['update_flag'];
            }
        }
        else
        {
            $update_flag = false;
        }

        $owner_name = $aRef->getType()->getName();
        $owner_id = $aRef->getId();
        $image_name = $imageSetting->getName();

        $this->checkOwner($aRef);

        $tmp_dir = $this->pathResolver->getTmpDir();

        if (!is_readable($tmp_dir))
        {
            throw new OperationException('Временная дирректория картинок ('.$tmp_dir.') не доступна для чтения!');
        }

        $images_dir = $this->pathResolver->getImageDir();

        if (!is_writable($images_dir))
        {
            throw new OperationException('Дирректория картинок ('.$images_dir.') не доступна для записи!');
        }

        $image_prefix = $this->getImagePrefix($owner_name, $owner_id, $image_name, GenVariant::NONE);

        $image_path = $images_dir.'/'.$image_prefix;

        $tmp_finded = false;
        $phway = true;

        $tmp_file_name = '';

        if($update_flag)
        {
            $tmp_path = $tmp_dir.'/'.$image_prefix;

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

                $tmp_finded = true;
                $tmp_file_name = $file;
                break;
            }
        }
        else
        {
            //Удаление содержимого тэмпа
            $this->deleteAllFiles($aRef, $imageSetting, true);
        }

        if($tmp_finded)
        {
            //Удаление всех файлов картинок по пути без расширения, для очистки картинок отличающимся расширением от загруженной
            $this->deleteAllFiles($aRef, $imageSetting);

            $original_mime = File::mimeType($tmp_file_name);

            $original_ext = $this->getExtension($original_mime);
            $original_file_name = $image_path.'.'.$original_ext;

            File::move($tmp_file_name, $original_file_name);
            chmod($original_file_name, 0644);
            $phway = false;
        }
        else
        {
            foreach (glob($image_path.'.*') as $file)
            {
                if(is_dir($file))
                {
                    continue;
                }

                $phway = false;
                $original_mime = File::mimeType($file);
                $original_ext = $this->getExtension($original_mime);
                $original_file_name = $image_path.'.'.$original_ext;

                //Переименуем, если расширение не соответствует типу
                if($file !== $original_file_name)
                {
                    rename($file, $original_file_name);
                }

                break;
            }
        }

        //Ничего не нашли и не переместили, подставляем плэйсхолдер заданных параметров
        if($phway)
        {
            $width = $imageSetting->getWidth();
            $height = $imageSetting->getHeight();

            $original_file_path = $this->phAgent->getPh(
                $width,
                $height,
                $imageSetting->getColor()
            );

            $original_mime = MimeType::JPEG;
        }
        else
        {
            $originalImage = Image::make($original_file_name);

            $width = $originalImage->getWidth();
            $height = $originalImage->getHeight();

            $original_file_path = $this->pathResolver->getImagePath().'/'.$image_prefix.'.'.$original_ext;
        }

        $user_attrs['link'] = $original_file_path;
        $user_attrs['width'] = $width;
        $user_attrs['height'] = $height;

        $user_attrs = array_merge($user_attrs, ['alt' => '']);

        $this->dbAgent->imageToDb($aRef, $imageSetting, $user_attrs);
        //--------------------------------------------------------------------------------------

        $resize_attrs = [];
        if(array_key_exists('resizes', $user_attrs))
        {
            $resize_attrs = $user_attrs['resizes'];
        }

        $crop_attrs = [];
        if(array_key_exists('crops', $user_attrs))
        {
            $crop_attrs = $user_attrs['crops'];
        }

        if($phway)
        {
            $this->makePhImageResizes($aRef, $imageSetting, $resize_attrs);
            $this->makePhImageCrops($aRef, $imageSetting, $crop_attrs);
        }
        else
        {
            //Удаление старых ресайзов и кропов
            $this->deleteGens($aRef, $imageSetting);

            $vector = $this->isVectorImage($original_mime);

            if($vector)
            {
                $this->makeSameImageResizes($aRef, $imageSetting, $original_file_name, $resize_attrs);
                $this->makeSameImageCrops($aRef, $imageSetting, $original_file_name, $crop_attrs);
            }
            else
            {
                $this->makeImageResizes($aRef, $imageSetting, $resize_attrs);
                $this->makeImageCrops($aRef, $imageSetting, $crop_attrs);
            }
        }

        //Удаление содержимого тэмпа
        if($update_flag)
        {
            $this->deleteAllFiles($aRef, $imageSetting, true);
        }

    }
}


<?php

namespace Caxy\ForecastApi;

use GuzzleHttp\Client;

class ForecastClient
{
    const BASE_URI = 'https://api.forecastapp.com';
    const AUTH_BASE_URI = 'https://id.getharvest.com';

    /**
     * @var Client
     */
    protected $guzzle;

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

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

    /**
     * @var string|int
     */
    protected $accountId;

    /**
     * ForecastClient constructor.
     */
    public function __construct($accountId, $apiToken = null, $baseUri = self::BASE_URI)
    {
        $this->accountId = $accountId;
        $this->apiToken = $apiToken;
        $this->baseUri = $baseUri;
        $this->guzzle = $this->makeClient();
    }

    /**
     * @param string $username
     * @param string $password
     *
     * @return null|string the API access token.
     * @throws \Exception
     */
    public function authenticate($username, $password)
    {
        $authClient = $this->makeAuthClient();
        // Parse CSRF token from login form.
        $loginFormResponse = $authClient->get('/forecast/sign_in');
        $loginForm = $loginFormResponse->getBody()->getContents();
        $matches = [];
        $regexp = '/<input type="hidden" name="authenticity_token" value="(.*)"/';
        preg_match_all($regexp, $loginForm, $matches);
        $csrfToken = $matches[1][0];
        if (empty($csrfToken)) {
            throw new \Exception('CSRF token error - no token');
        }
        $data = [
            'authenticity_token' => $csrfToken,
            'email' => $username,
            'password' => $password,
            'product' => 'forecast'
        ];
        $sessionResponse = $authClient->post('/sessions', array('form_params' => $data));
        // Don't follow redirects on this one?
        $tokenRequestResponse = $authClient->get(sprintf('/accounts/%s', $this->accountId), array(
            'allow_redirects' => false,
        ));
        $tokenRequest = $tokenRequestResponse->getBody()->getContents();
        $matches = [];
        $regexp = '/access_token\/(.*)\?"/';
        preg_match_all($regexp, $tokenRequest, $matches);
        if (isset($matches[1][0]) && !empty($matches[1][0])) {
            $this->apiToken = $matches[1][0];

            // Remake the client so that it uses the api token authorization header.
            $this->guzzle = $this->makeClient();

            return $this->apiToken;
        } else {
            throw new \Exception('Could not find token. Check your login, password and APP ID');
        }
    }

    public function whoAmI()
    {
        return $this->request('GET', '/whoami');
    }

    public function getClients()
    {
        return $this->request('GET', '/clients')['clients'];
    }

    public function getPeople()
    {
        return $this->request('GET', '/people')['people'];
    }

    public function getProjects()
    {
        return $this->request('GET', '/projects')['projects'];
    }

    public function getAssignments($startDate = null, $endDate = null, $state = 'active')
    {
        $options = $this->addDateQueryToOptions($startDate, $endDate);
        $options['query']['state'] = $state;

        return $this->request('GET', '/assignments', $options)['assignments'];
    }

    public function postAssignment($data, array $options = array())
    {
        $options['json'] = $data;

        return $this->request('POST', '/assignments', $options);
    }

    public function putAssignment($id, $data, array $options = array())
    {
        $options['json'] = $data;

        return $this->request('PUT', '/assignments/' . $id, $options);
    }

    public function deleteAssignment($id, array $options = array())
    {
        return $this->request('DELETE', '/assignments/' . $id, $options);
    }

    public function getMilestones($startDate = null, $endDate = null)
    {
        $options = $this->addDateQueryToOptions($startDate, $endDate);

        return $this->request('GET', '/milestones', $options)['milestones'];
    }

    protected function addDateQueryToOptions($startDate = null, $endDate = null, $options = array())
    {
        if (!array_key_exists('query', $options)) {
            $options['query'] = array();
        }
        if ($startDate !== null) {
            $options['query']['start_date'] = $startDate;
        }

        if ($endDate !== null) {
            $options['query']['end_date'] = $endDate;
        }

        return $options;
    }

    /**
     * @param string $method
     * @param string $uri
     * @param array $options
     *
     * @return array
     * @throws ForecastException
     */
    protected function request($method, $uri, array $options = array())
    {
        $response = $this->guzzle->request($method, $uri, $options);

        if ($response->getStatusCode() < 200 || $response->getStatusCode() > 400) {
            throw new ForecastException('Forecast API error: ' . $response->getReasonPhrase(), $response->getStatusCode());
        }

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * @return Client
     */
    protected function makeClient()
    {
        $headers = array('Forecast-Account-Id' => $this->accountId);

        if ($this->apiToken) {
            $headers['Authorization'] = sprintf('Bearer %s', $this->apiToken);
        }

        return new Client(
            array(
                'base_uri' => $this->baseUri,
                'headers'  => $headers,
            )
        );
    }

    /**
     * @return Client
     */
    protected function makeAuthClient()
    {
        return new Client(
            array(
                'base_uri' => self::AUTH_BASE_URI,
                'cookies' => true,
            )
        );
    }
}


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

namespace Praxigento\Accounting\Helper;

use Praxigento\Accounting\Config as Cfg;

/**
 * System customer is a representative of the application owner in accounting.
 */
class SysCustomer
    implements \Praxigento\Accounting\Api\Helper\SysCustomer
{
    private $cacheId = null;
    /** @var \Praxigento\Core\Api\App\Repo\Generic */
    private $daoGeneric;

    public function __construct(
        \Praxigento\Core\Api\App\Repo\Generic $daoGeneric
    ) {
        $this->daoGeneric = $daoGeneric;
    }

    /**
     * Return ID of the system customer.
     *
     * @return int
     */
    public function getId()
    {
        if (is_null($this->cacheId)) {
            $conn = $this->daoGeneric->getConnection();
            $entity = Cfg::ENTITY_MAGE_CUSTOMER;
            $cols = [Cfg::E_CUSTOMER_A_ENTITY_ID];
            $quoted = $conn->quote(Cfg::SYS_CUSTOMER_EMAIL);
            $where = Cfg::E_CUSTOMER_A_EMAIL . '=' . $quoted;
            $rs = $this->daoGeneric->getEntities($entity, $cols, $where);
            $found = reset($rs);
            $this->cacheId = $found[Cfg::E_CUSTOMER_A_ENTITY_ID];
        }
        return $this->cacheId;
    }

}


<?php

namespace ElfSundae\Laravel\Api\Console;

use Illuminate\Console\Command;
use ElfSundae\Laravel\Api\Token;

class GenerateTokenCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'api:token {app key}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate an api token.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $token = $this->laravel->make(Token::class);

        $key = $this->argument('app key');

        if ($data = $token->generateDataForKey($key)) {
            $this->table(array_keys($data), [array_values($data)]);
        } else {
            $this->error('Invalid app key: '.$key);
        }
    }
}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Operation\CropOperation as CropOperationInterface;
use Interpro\ImageAggr\Contracts\Settings\CropSetting;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;

class CropOperation extends Operation implements CropOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Interpro\ImageAggr\Contracts\Settings\CropSetting $cropSetting
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting, CropSetting $cropSetting, array $attrs = [])
    {
        $this->checkOwner($aRef);

        $this->makeCrop($aRef, $imageSetting, $cropSetting, $attrs);
    }
}


<?php

namespace Interpro\ImageAggr\Collections;

use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Taxonomy\Collections\NamedCollection;
use Interpro\ImageAggr\Creation\CapGenerator;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Items\ImageItem;
use Interpro\ImageAggr\Items\ResizeItem;

class ResizesCollection extends NamedCollection
{
    private $capGenerator;
    private $imageField;
    private $original = null;

    public function __construct(OwnField $field, CapGenerator $capGenerator)
    {
        $this->capGenerator = $capGenerator;
        $this->imageField = $field;
    }

    public function setOriginal(ImageItem $original)
    {
        $this->original = $original;
    }

    /**
     * @param string $resize_name
     *
     * @return \Interpro\ImageAggr\Items\ResizeItem
     */
    public function getItem($resize_name)
    {
        if($this->exist($resize_name))
        {
            return $this->getByName($resize_name);
        }

        if($this->original)
        {
            $resizeItem = $this->capGenerator->createResize($this->imageField, $resize_name, $this->original);

            $this->addItem($resizeItem);
        }

        return $this->getByName($resize_name);
    }

    protected function notFoundAction($name)
    {
        throw new ImageAggrException('Ресайз по имени '.$name.' не найден!');
    }

    /**
     * @param \Interpro\ImageAggr\Items\ResizeItem $item
     *
     * @return void
     */
    public function addItem(ResizeItem $item)
    {
        $this->addByName($item);
    }

}


<?php

namespace ArjanWestdorp\Imaginary;

class Builder
{
    /**
     * @var string
     */
    protected $key;
    /**
     * @var array
     */
    protected $manipulations;
    /**
     * @var string
     */
    protected $url;

    /**
     * Builder constructor.
     *
     * @param string $key
     */
    public function __construct($key)
    {
        $this->key = $key;
    }

    /**
     * Make a circle of the image with the given radius.
     *
     * @param string $radius
     * @return $this
     */
    public function circle($radius = 'max')
    {
        $this->manipulations['r'] = $radius;

        return $this;
    }

    /**
     * Fit the image when resizing it.
     *
     * @param null|string $gravity
     * @return $this
     */
    public function fit($gravity = null)
    {
        $this->manipulations['c'] = 'fit';

        if (!is_null($gravity)) {
            $this->manipulations['g'] = $gravity;
        }

        return $this;
    }

    /**
     * Set the desired height of the image.
     *
     * @param int $height
     * @return $this
     */
    public function height($height)
    {
        $this->manipulations['h'] = $height;

        return $this;
    }

    /**
     * Set the desired width of the image.
     *
     * @param int $width
     * @return $this
     */
    public function width($width)
    {
        $this->manipulations['w'] = $width;

        return $this;
    }

    /**
     * Set the desired dpr of the image.
     *
     * @param mixed $dpr
     * @return $this
     */
    public function dpr($dpr = 'auto')
    {
        $this->manipulations['dpr'] = $dpr;

        return $this;
    }

    /**
     * Get the string representation of all manipulations that
     * need to be executed on the given resource.
     *
     * @return string|null
     */
    public function getManipulations()
    {
        $manipulations = array_map(function ($key) {
            return $key . '_' . $this->manipulations[$key];
        }, array_keys($this->manipulations ?: []));

        return implode(',', $manipulations);
    }

    /**
     * Get the key where we build the url for.
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }
}


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

namespace Praxigento\Accounting\Repo\Dao;

use Praxigento\Accounting\Repo\Data\Transaction as Entity;

class Transaction
    extends \Praxigento\Core\App\Repo\Dao
{
    /** @var \Praxigento\Accounting\Repo\Dao\Account */
    private $repoAccount;

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

    /**
     * @param null $where
     * @param null $order
     * @param null $limit
     * @param null $offset
     * @param null $columns
     * @param null $group
     * @param null $having
     * @return Entity[]
     */
    public function get($where = null,
                        $order = null,
                        $limit = null,
                        $offset = null,
                        $columns = null,
                        $group = null,
                        $having = null)
    {
        return parent::get($where, $order, $limit, $offset, $columns, $group, $having);
    }

    /**
     * Create transaction and update balances in account table.
     *
     * @param \Praxigento\Accounting\Repo\Data\Transaction|array $data
     * @return int
     */
    public function create($data)
    {
        $result = parent::create($data);
        if ($result) {
            /* update balances for accounts */
            if (is_array($data)) {
                $data = new Entity($data);
            }
            $value = $data->getValue();
            $creditAccId = $data->getCreditAccId();
            $debitAccId = $data->getDebitAccId();
            $this->repoAccount->updateBalance($creditAccId, 0 + $value);
            $this->repoAccount->updateBalance($debitAccId, 0 - $value);
        }
        return $result;
    }

}


<?php

namespace DCS\OpauthBundle\Security;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;

class OpauthToken extends AbstractToken
{
    private $uid;

    private $provider;

    private $info;

    private $credentials;

    private $raw;

    public function __construct($response, array $roles = array())
    {
        $this->uid          = $response['auth']['uid'];
        $this->provider     = $response['auth']['provider'];
        $this->info         = $response['auth']['info'];
        $this->credentials  = $response['auth']['credentials'];
        $this->raw     = $response;

        parent::__construct($roles);

        $this->setUser($response['auth']['info']['name']);
        $this->setAuthenticated(true);
    }

    /**
     * @return mixed
     */
    public function getUid()
    {
        return $this->uid;
    }

    /**
     * @return mixed
     */
    public function getProvider()
    {
        return $this->provider;
    }

    /**
     * @return mixed
     */
    public function getInfo()
    {
        return $this->info;
    }

    /**
     * @return mixed
     */
    public function getCredentials()
    {
        return '';
    }

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

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return serialize(
            array(
                $this->uid,
                $this->provider,
                $this->info,
                $this->credentials,
                $this->raw,
                parent::serialize(),
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($serialized)
    {
        list($this->uid, $this->provider, $this->info, $this->credentials, $this->raw, $parentStr) = unserialize($serialized);
        parent::unserialize($parentStr);
    }
}


<?php

namespace Onoi\Tesa;

use Onoi\Tesa\StopwordAnalyzer\StopwordAnalyzer;
use Onoi\Tesa\StopwordAnalyzer\NullStopwordAnalyzer;
use Onoi\Tesa\StopwordAnalyzer\CdbStopwordAnalyzer;
use Onoi\Tesa\StopwordAnalyzer\ArrayStopwordAnalyzer;
use Onoi\Tesa\Synonymizer\Synonymizer;
use Onoi\Tesa\Synonymizer\NullSynonymizer;
use Onoi\Tesa\LanguageDetector\NullLanguageDetector;
use Onoi\Tesa\LanguageDetector\TextCatLanguageDetector;
use Onoi\Tesa\Tokenizer\CJKSimpleCharacterRegExTokenizer;
use Onoi\Tesa\Tokenizer\Tokenizer;
use Onoi\Tesa\Tokenizer\GenericRegExTokenizer;
use Onoi\Tesa\Tokenizer\JaCompoundGroupTokenizer;
use Onoi\Tesa\Tokenizer\IcuWordBoundaryTokenizer;
use Onoi\Tesa\Tokenizer\NGramTokenizer;
use Onoi\Tesa\Tokenizer\JaTinySegmenterTokenizer;
use Onoi\Tesa\Tokenizer\PunctuationRegExTokenizer;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class SanitizerFactory {

	/**
	 * @since 0.1
	 *
	 * @return Sanitizer
	 */
	public function newSanitizer( $text = '' ) {
		return new Sanitizer( $text );
	}

	/* StopwordAnalyzer */

	/**
	 * @since 0.1
	 *
	 * @param string|null $languageCode
	 *
	 * @return StopwordAnalyzer
	 */
	public function newStopwordAnalyzerByLanguage( $languageCode = null ) {

		if ( $languageCode === null ) {
			return $this->newNullStopwordAnalyzer();
		}

		$cdbStopwordAnalyzer = $this->newCdbStopwordAnalyzer(
			$languageCode
		);

		return $cdbStopwordAnalyzer->isAvailable() ? $cdbStopwordAnalyzer : $this->newNullStopwordAnalyzer();;
	}

	/**
	 * @since 0.1
	 *
	 * @return StopwordAnalyzer
	 */
	public function newCdbStopwordAnalyzer( $languageCode = null ) {
		return new CdbStopwordAnalyzer( CdbStopwordAnalyzer::getTargetByLanguage( $languageCode ) );
	}

	/**
	 * @since 0.1
	 *
	 * @param array $stopwords;
	 *
	 * @return StopwordAnalyzer
	 */
	public function newArrayStopwordAnalyzer( array $stopwords = array() ) {
		return new ArrayStopwordAnalyzer( $stopwords );
	}

	/**
	 * @since 0.1
	 *
	 * @return StopwordAnalyzer
	 */
	public function newNullStopwordAnalyzer() {
		return new NullStopwordAnalyzer();
	}

	/**
	 * @since 0.1
	 *
	 * @param string|null $languageCode
	 *
	 * @return Synonymizer
	 */
	public function newSynonymizerByLanguage( $languageCode = null ) {

		if ( $languageCode === null ) {
			return $this->newNullSynonymizer();
		}

		return $this->newNullSynonymizer();;
	}

	/* Synonymizer */

	/**
	 * @since 0.1
	 *
	 * @return Synonymizer
	 */
	public function newNullSynonymizer() {
		return new NullSynonymizer();
	}

	/* LanguageDetector */

	/**
	 * @since 0.1
	 *
	 * @return NullLanguageDetector
	 */
	public function newNullLanguageDetector() {
		return new NullLanguageDetector();
	}

	/**
	 * @since 0.1
	 *
	 * @return TextCatLanguageDetector
	 */
	public function newTextCatLanguageDetector() {
		return new TextCatLanguageDetector();
	}

	/* Tokenizer */

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 * @param string|null $languageCode
	 *
	 * @return Tokenizer
	 */
	public function newPreferredTokenizerByLanguage( $text, $languageCode = null ) {

		$tokenizer = $this->newIcuWordBoundaryTokenizer();

		if ( !$tokenizer->isAvailable() && CharacterExaminer::contains( CharacterExaminer::CJK_UNIFIED, $text ) ) {
			return $this->newCJKMatchableTokenizer( $text );
		} elseif( !$tokenizer->isAvailable() ) {
			return $this->newGenericRegExTokenizer( $tokenizer );
		}

		$tokenizer->setLocale( $languageCode );

		$tokenizer->setWordTokenizerAttribute(
			!CharacterExaminer::contains( CharacterExaminer::CJK_UNIFIED, $text )
		);

		return $this->newGenericRegExTokenizer( $tokenizer );
	}

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 *
	 * @return Tokenizer
	 */
	public function newCJKMatchableTokenizer( $text ) {

		$tokenizer = null;

		if ( CharacterExaminer::contains( CharacterExaminer::HIRAGANA_KATAKANA, $text ) ) {
			$tokenizer = $this->newJaTinySegmenterTokenizer();
		} else {
			$tokenizer = $this->newNGramTokenizer( $tokenizer );
		}

		$tokenizer = $this->newCJKSimpleCharacterRegExTokenizer( $tokenizer );

		return $this->newGenericRegExTokenizer( $tokenizer );
	}

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer|null $tokenizer
	 *
	 * @return Tokenizer
	 */
	public function newIcuWordBoundaryTokenizer( Tokenizer $tokenizer = null ) {
		return new IcuWordBoundaryTokenizer( $tokenizer );
	}

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer|null $tokenizer
	 *
	 * @return Tokenizer
	 */
	public function newGenericRegExTokenizer( Tokenizer $tokenizer = null ) {
		return new GenericRegExTokenizer( $tokenizer );
	}

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer|null $tokenizer
	 *
	 * @return Tokenizer
	 */
	public function newPunctuationRegExTokenizer( Tokenizer $tokenizer = null ) {
		return new PunctuationRegExTokenizer( $tokenizer );
	}

	/**
	 * @since 0.1
	 *
	 * @return Tokenizer
	 */
	public function newJaCompoundGroupTokenizer( Tokenizer $tokinizer = null ) {
		return new JaCompoundGroupTokenizer( $tokinizer );
	}

	/**
	 * @since 0.1
	 *
	 * @return Tokenizer
	 */
	public function newJaTinySegmenterTokenizer( Tokenizer $tokinizer = null ) {
		return new JaTinySegmenterTokenizer( $tokinizer );
	}

	/**
	 * @since 0.1
	 *
	 * @return Tokenizer
	 */
	public function newCJKSimpleCharacterRegExTokenizer( Tokenizer $tokinizer = null ) {
		return new CJKSimpleCharacterRegExTokenizer( $tokinizer );
	}

	/**
	 * @since 0.1
	 *
	 * @return Tokenizer
	 */
	public function newNGramTokenizer( Tokenizer $tokinizer = null, $ngram = 2 ) {
		return new NGramTokenizer( $tokinizer, $ngram );
	}

}


<?php

namespace Interpro\ImageAggr\Collections;

use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Taxonomy\Collections\NamedCollection;
use Interpro\ImageAggr\Creation\CapGenerator;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Items\CropItem;
use Interpro\ImageAggr\Items\ImageItem;

class CropsCollection extends NamedCollection
{
    private $capGenerator;
    private $imageField;
    private $original = null;

    public function __construct(OwnField $field, CapGenerator $capGenerator)
    {
        $this->capGenerator = $capGenerator;
        $this->imageField = $field;
    }

    public function setOriginal(ImageItem $original)
    {
        $this->original = $original;
    }

    /**
     * @param string $field_name
     *
     * @return \Interpro\ImageAggr\Items\CropItem
     */
    public function getItem($crop_name)
    {
        if($this->exist($crop_name))
        {
            return $this->getByName($crop_name);
        }

        if($this->original)
        {
            $resizeItem = $this->capGenerator->createResize($this->imageField, $crop_name, $this->original);

            $this->addItem($resizeItem);
        }

        return $this->getByName($crop_name);
    }

    protected function notFoundAction($name)
    {
        throw new ImageAggrException('Кроп по имени '.$name.' не найден!');
    }

    /**
     * @param \Interpro\ImageAggr\Items\CropItem $item
     *
     * @return void
     */
    public function addItem(CropItem $item)
    {
        $this->addByName($item);
    }

}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Operation\DeleteOperation as DeleteOperationInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;

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

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

        $this->dbAgent->deleteImage($aRef, $imageSetting);

        $resizes = $imageSetting->getResizes();
        foreach($resizes as $resizeSetting)
        {
            $this->dbAgent->deleteResize($aRef, $imageSetting, $resizeSetting);
        }

        $crops = $imageSetting->getCrops();
        foreach($crops as $cropSetting)
        {
            $this->dbAgent->deleteCrop($aRef, $imageSetting, $cropSetting);
        }
    }

}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;
use Interpro\ImageAggr\Exception\OperationException;
use Interpro\ImageAggr\Contracts\Settings\Enum\GenVariant;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Interpro\ImageAggr\Contracts\Operation\UploadOperation as UploadOperationInterface;

class UploadOperation extends Operation implements UploadOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting, UploadedFile $uploadedFile)
    {
        $owner_name = $aRef->getType()->getName();
        $owner_id = $aRef->getId();
        $image_name = $imageSetting->getName();

        $this->checkOwner($aRef);

        $exts = ['png', 'jpg', 'jpeg', 'gif', 'svg'];

        $tmp_dir = $this->pathResolver->getTmpDir();

        if (!is_writable($tmp_dir))
        {
            throw new OperationException('Временная дирректория картинок ('.$tmp_dir.') не доступна для записи!');
        }

        $ext = $uploadedFile->guessClientExtension();

        if(!in_array($ext, $exts))
        {
            throw new OperationException('Тип файла картинки может быть только '.implode(',', $exts).'!');
        }

        $image_name_ext = $this->getImagePrefix($owner_name, $owner_id, $image_name, GenVariant::NONE).'.'.$ext;

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

        $uploadedFile->move(
            $tmp_dir,
            $image_name_ext
        );

        $tmp_path = $tmp_dir.'/'.$image_name_ext;

        chmod($tmp_path, 0644);

        //5й аргумент $tmp определяет, что будут сделаны только служебные ресайзы, например иконка для обновления в интерфесе загрузки
        $this->makeImageResizes($aRef, $imageSetting, [], true);
    }
}


<?php
namespace Able\Prototypes;

trait TFillable {

	/**
	 * Fill object values via array.
	 *
	 * @param array $Values
	 * @throws \Exception
	 */
	public function fill(array $Values) {
		foreach ($Values as $name => $value){
			if (!property_exists($this, $name)){
				throw new \Exception('Undefined property "' . $name . '"!');
			}

			$this->{$name} = $value;
		}
	}

}


<?php
namespace Basic\Module\Modules;

use DateTime;
use Skinny\Module\ModuleInterface;
use Skinny\Network\Wrapper;

class Basic implements ModuleInterface
{

    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onChannelMessage(Wrapper $wrapper, $message)
    {
    }

    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onPrivateMessage(Wrapper $wrapper, $message)
    {
    }

    /**
     * {@inheritDoc}
     *
     * @param \Skinny\Network\Wrapper $wrapper The Wrapper instance.
     * @param array $message The message array.
     *
     * @return void
     */
    public function onCommandMessage(Wrapper $wrapper, $message)
    {
        //Handle the command.
        switch ($message['command']) {
            case 'say':
                $wrapper->Channel->sendMessage($message['parts'][1]);

                break;

            case 'info':
                $wrapper->Message->reply(
                    'I\'m open-source! You can find me on GitHub : https://github.com/SkinnyBot/Skinny .'
                );

                break;

            case 'time':
                $seconds = floor(microtime(true) - TIME_START);
                $start = new DateTime("@0");
                $end = new DateTime("@$seconds");
                $wrapper->Message->reply(
                    'I\'m running since ' . $start->diff($end)->format('%a days, %h hours, %i minutes and %s seconds.')
                );

                break;
        }
    }
}


<?php

namespace Praxigento\Accounting\Ui\DataProvider\Grid\Account;

use Praxigento\Accounting\Config as Cfg;
use Praxigento\Accounting\Repo\Data\Account as EAccount;
use Praxigento\Accounting\Repo\Data\Type\Asset as ETypeAsset;

class Query
    extends \Praxigento\Core\App\Ui\DataProvider\Grid\Query\Builder
{

    /**#@+ Tables aliases for external usage ('camelCase' naming) */
    const AS_ACCOUNT = 'paa';
    const AS_CUSTOMER = 'ce';
    const AS_TYPE_ASSET = 'pata';
    /**#@- */

    /**#@+ Columns/expressions aliases for external usage */
    const A_ASSET = 'asset';
    const A_BALANCE = 'balance';
    const A_CUST_EMAIL = 'custEmail';
    const A_CUST_ID = 'custId';
    const A_CUST_NAME = 'custName';
    const A_ID = 'id';
    /**#@- */

    /**
     * Construct expression for customer name ("firstName lastName").
     */
    public function getExpForCustName()
    {
        $value = 'CONCAT(' . Cfg::E_CUSTOMER_A_FIRSTNAME . ", ' ', " . Cfg::E_CUSTOMER_A_LASTNAME . ')';
        $result = new \Praxigento\Core\App\Repo\Query\Expression($value);
        return $result;
    }

    protected function getMapper()
    {
        if (is_null($this->mapper)) {
            $map = [
                self::A_ASSET => self::AS_TYPE_ASSET . '.' . ETypeAsset::A_CODE,
                self::A_CUST_NAME => $this->getExpForCustName(),
                self::A_CUST_EMAIL => self::AS_CUSTOMER . '.' . Cfg::E_CUSTOMER_A_EMAIL,
                self::A_BALANCE => self::AS_ACCOUNT . '.' . EAccount::A_BALANCE,
                self::A_ID => self::AS_ACCOUNT . '.' . EAccount::A_ID
            ];
            $this->mapper = new \Praxigento\Core\App\Repo\Query\Criteria\Def\Mapper($map);
        }
        $result = $this->mapper;
        return $result;
    }

    /**
     * SELECT
     * `paa`.`id`,
     * `paa`.`balance`,
     * `prxgt_acc_type_asset`.`code` AS `asset`,
     * (CONCAT(firstname, ' ', lastname)) AS `custName`,
     * `ce`.`email` AS `custEmail`
     * FROM `prxgt_acc_account` AS `paa`
     * LEFT JOIN `prxgt_acc_type_asset`
     * ON pata.id = paa.asset_type_id
     * LEFT JOIN `customer_entity` AS `ce`
     * ON ce.entity_id = paa.customer_id
     */
    protected function getQueryItems()
    {
        $result = $this->conn->select();

        /* define tables aliases for internal usage (in this method) */
        $asAcc = self::AS_ACCOUNT;
        $asCust = self::AS_CUSTOMER;
        $asAsset = self::AS_TYPE_ASSET;

        /* SELECT FROM prxgt_acc_account */
        $tbl = $this->resource->getTableName(EAccount::ENTITY_NAME);
        $as = $asAcc;
        $cols = [
            self::A_ID => EAccount::A_ID,
            self::A_BALANCE => EAccount::A_BALANCE
        ];
        $result->from([$as => $tbl], $cols);

        /* LEFT JOIN prxgt_acc_type_asset */
        $tbl = $this->resource->getTableName(ETypeAsset::ENTITY_NAME);
        $as = $asAsset;
        $cols = [
            self::A_ASSET => ETypeAsset::A_CODE
        ];
        $cond = $as . '.' . ETypeAsset::A_ID . '=' . $asAcc . '.' . EAccount::A_ASSET_TYPE_ID;
        $result->joinLeft([$as => $tbl], $cond, $cols);

        /* LEFT JOIN customer_entity */
        $tbl = $this->resource->getTableName(Cfg::ENTITY_MAGE_CUSTOMER);
        $as = $asCust;
        $exp = $this->getExpForCustName();
        $cols = [
            self::A_CUST_NAME => $exp,
            self::A_CUST_EMAIL => Cfg::E_CUSTOMER_A_EMAIL,
            self::A_CUST_ID => Cfg::E_CUSTOMER_A_ENTITY_ID
        ];
        $cond = $as . '.' . Cfg::E_CUSTOMER_A_ENTITY_ID . '=' . $asAcc . '.' . EAccount::A_CUST_ID;
        $result->joinLeft([$as => $tbl], $cond, $cols);

        /* return  result */
        return $result;
    }

    protected function getQueryTotal()
    {
        /* get query to select items */
        /** @var \Magento\Framework\DB\Select $result */
        $result = $this->getQueryItems();
        /* ... then replace "columns" part with own expression */
        $value = 'COUNT(' . self::AS_ACCOUNT . '.' . EAccount::A_ID . ')';

        /**
         * See method \Magento\Framework\DB\Select\ColumnsRenderer::render:
         */
        /**
         * if ($column instanceof \Zend_Db_Expr) {...}
         */
        $exp = new \Praxigento\Core\App\Repo\Query\Expression($value);
        /**
         *  list($correlationName, $column, $alias) = $columnEntry;
         */
        $entry = [null, $exp, null];
        $cols = [$entry];
        $result->setPart('columns', $cols);
        return $result;
    }
}


<?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\Reset\Request as AResetRequest;

/**
 * Re-calculate balances for given account starting from given date (excl.).
 */
class ProcessOneAccount
{
    private const BND_ACC_ID = 'accId';

    /** @var \Praxigento\Accounting\Repo\Dao\Transaction */
    private $daoTransaction;
    /** @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 \Magento\Framework\App\ResourceConnection */
    private $resource;
    /** @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,
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Accounting\Repo\Dao\Transaction $daoTransaction,
        \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
    ) {
        $this->logger = $logger;
        $this->resource = $resource;
        $this->daoTransaction = $daoTransaction;
        $this->qBalancesOnDate = $qBalancesOnDate;
        $this->hlpPeriod = $hlpPeriod;
        $this->servBalanceLastDate = $servBalanceLastDate;
        $this->servBalanceReset = $servBalanceReset;
        $this->zCollect = $zCollect;
        $this->zUpdate = $zUpdate;
    }

    /**
     * @param int $accId
     * @param string $dsBalClose YYYYMMDD
     * @throws \Exception
     */
    public function exec($accId, $dsBalClose)
    {
        $dsLast = $this->getBalancesLastDate($accId);
        /* reset balances if requested */
        if ($dsLast > $dsBalClose) {
            $this->resetBalances($accId, $dsBalClose);
            $dsLast = $dsBalClose;
        }
        /* get closing balances */
        $balance = $this->getBalanceClosing($accId, $dsLast);
        /* get transactions starting from the last date */
        $trans = $this->getTransactions($accId, $dsLast);
        if (is_array($trans) && count($trans)) {
            /* collect transactions by date (compose records for balances table) */
            $balances = [$accId => $balance];
            $updates = $this->zCollect->exec($balances, $trans);
            /* process this account balances only*/
            $updates = [$accId => $updates[$accId]];
            $this->zUpdate->exec($updates);
        } else {
            $msg = "There is no transactions for account #$accId starting from $dsLast";
            $this->logger->info($msg);
        }
    }

    /**
     * @param int $accId
     * @param string $dsClose YYYYMMDD
     * @return int
     */
    private function getBalanceClosing($accId, $dsClose)
    {
        $result = 0;

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

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

        $bind = [
            QBalOnDate::BND_MAX_DATE => $dsClose,
            self::BND_ACC_ID => $accId
        ];
        $rs = $conn->fetchAll($query, $bind);
        if (is_array($rs) && count($rs)) {
            $entry = reset($rs);
            $result = $entry[QBalOnDate::A_BALANCE];
        }
        return $result;
    }

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

    /**
     * @param int $accId
     * @param string $dsClose YYYYMMDD
     * @return \Praxigento\Accounting\Repo\Data\Transaction[]
     */
    private function getTransactions($accId, $dsClose)
    {
        /* first date should be after closing balance date */
        $tsFrom = $this->hlpPeriod->getTimestampNextFrom($dsClose);
        $conn = $this->resource->getConnection();
        $byDateFrom = ETrans::A_DATE_APPLIED . '>=' . $conn->quote($tsFrom);
        $byAccIdDebit = ETrans::A_DEBIT_ACC_ID . '=' . (int)$accId;
        $byAccIdCredit = ETrans::A_CREDIT_ACC_ID . '=' . (int)$accId;
        $where = "($byDateFrom) AND (($byAccIdDebit) OR ($byAccIdCredit))";
        $order = ETrans::A_DATE_APPLIED . ' ASC';
        $result = $this->daoTransaction->get($where, $order);
        return $result;
    }

    /**
     * Reset balances for account starting from given date (excl).
     * @param int $accId
     * @param string $dsFrom
     * @throws \Exception
     */
    private function resetBalances($accId, $dsFrom)
    {
        $req = new AResetRequest();
        $req->setAccounts([$accId]);
        $req->setDateFrom($dsFrom);
        $this->servBalanceReset->exec($req);
    }
}


<?php

/**
 * This file is part of the cyberalien/simple-tokenizer package.
 *
 * (c) Vjacheslav Trushkin <cyberalien@gmail.com>
 *
 * This is not open source library.
 * This library can be used only with products available on artodia.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package cyberalien/simple-tokenizer
 */

namespace CyberAlien\SimpleTokenizer;

/**
 * Class that converts tokens list or tree back to css
 */
class Builder
{
    /*
     * Options
     */
    public $minify;
    public $tab;
    public $newline;
    public $ruleSeparator;
    public $selectorsSeparator;
    public $ruleModifiers;
    public $newLineAfterSelector;

    /**
     * Constructor
     *
     * @param array $options
     */
    function __construct($options = []) {
        $this->minify = !isset($options['minify']) ? false : $options['minify'];
        $this->tab = $this->minify ? '' : (!isset($options['tab']) ? "\t" : $options['tab']);
        $this->newline = $this->minify ? '' : (!isset($options['newline']) ? "\n" : $options['newline']);
        $this->newLineAfterSelector = !isset($options['newLineAfterSelector']) ? true : $options['newLineAfterSelector'];
        $this->ruleSeparator = $this->minify ? ':' : ': ';
        $this->selectorsSeparator = $this->minify ? ',' : ', ';
        $this->ruleModifiers = isset($options['ruleModifiers']) ? $options['ruleModifiers'] : ['default', 'important'];
    }

    /**
     * Convert list of tokens to string
     *
     * @param array $tokens
     * @return string
     */
    public function build($tokens) {
        return trim($this->_build($tokens, ''));
    }

    /**
     * Convert list of tokens to string
     *
     * @param array $tokens
     * @param string $space
     * @return string
     */
    protected function _build($tokens, $space) {
        $output = '';
        $lastToken = false;
        $level = 0;

        foreach ($tokens as $token) {
            switch ($token['token']) {
                case 'code':
                    $output .= $space . $token['code'] . $this->newline;
                    break;

                case '}':
                    $level --;
                    $space = substr($space, strlen($this->tab));
                    $output .= $space . '}' . $this->newline;
                    break;

                case '{':
                    if ($lastToken === '}') {
                        // Double new line between 2 items in same scope
                        $output .= $this->newline;
                    }
                    if (isset($token['selectors'])) {
                        $output .= $space . implode($this->selectorsSeparator, $token['selectors']);
                    } elseif (isset($token['atRule'])) {
                        $output .= $space . '@' . $token['atRule'];
                        if (!empty($token['atValues'])) {
                            $values = implode($this->selectorsSeparator, $token['atValues']);
                            $output .= $values === '' ? '' : ' ' . $values;
                        }
                    } else {
                        // Error - use code as backup
                        $output .= $space . $token['code'];
                    }
                    $output .= ($this->newLineAfterSelector ?
                            $this->newline . $space :
                            ($this->minify ? '' : ' ')
                        ) . '{' . $this->newline;
                    if (isset($token['children'])) {
                        $output .= $this->_build($token['children'], $space . $this->tab);
                        $output .= $space . '}' . $this->newline;
                    } else {
                        $level ++;
                        $space .= $this->tab;
                    }
                    break;

                case 'rule':
                    $output .= $space . $token['key'] . $this->ruleSeparator . $token['value'];
                    foreach ($this->ruleModifiers as $mod) {
                        if (!empty($token[$mod])) {
                            $output .= ' !' . $mod;
                        }
                    }
                    $output .= ';' . $this->newline;
                    break;
            }
            $lastToken = $token['token'];
        }

        return $output;
    }
}


<?php
namespace Able\Prototypes;

use \Able\Helpers\Arr;

trait TAggregatable {

	/**
	 * Return an aggregate value of given property.
	 *
	 * @param string $name
	 * @return array
	 */
	protected static function aggregate(string $name) : array {
		return array_merge(is_callable($target = [get_parent_class(static::class), 'aggregate'])
			? call_user_func($target, $name) : [], Arr::cast(Arr::get(get_class_vars(static::class), $name)));
	}
}


<?php

namespace Onoi\Tesa\Tokenizer;

use IntlRuleBasedBreakIterator;

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

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

	/**
	 * @var string
	 */
	private $locale = 'en';

	/**
	 * @var string
	 */
	private $isWordTokenizer = true;

	/**
	 * @since 0.1
	 *
	 * @param Tokenizer|null $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 $this->isWordTokenizer;
	}

	/**
	 * @since 0.1
	 *
	 * {@inheritDoc}
	 */
	public function setWordTokenizerAttribute( $usesWordBoundaries ) {
		return $this->isWordTokenizer = $usesWordBoundaries;
	}

	/**
	 * @since 0.1
	 *
	 * @return boolean
	 */
	public function isAvailable() {
		return class_exists( 'IntlRuleBasedBreakIterator' );
	}

	/**
	 * @since 0.1
	 *
	 * @param string $locale
	 */
	public function setLocale( $locale ) {
		$this->locale = $locale;
	}

	/**
	 * @since 0.1
	 *
	 * @param string $string
	 *
	 * @return array|false
	 */
	public function tokenize( $string ) {

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

		if ( !$this->isAvailable() ) {
			return $this->tokenizer !== null ? $this->tokenizer->tokenize( $string ) : array( $string );
		}

		return $this->createTokens( $string );
	}

	private function createTokens( $string ) {

		$tokens = array();

		if ( $tokenizer = IntlRuleBasedBreakIterator::createWordInstance( $this->locale ) ) {
			$tokenizer->setText( $string );
			$prev = 0;

			foreach ( $tokenizer as $token ) {

				if ( $token == 0 ) {
					continue;
				}

				$res = substr( $string, $prev, $token - $prev );

				if ( $res !== '' && $res !== ' ' ) {
					$tokens[] = $res;
				}

				$prev = $token;
			}
		}

		return $tokens;
	}

}


<?php

namespace Interpro\ImageAggr\Settings;

use Interpro\ImageAggr\Contracts\Settings\GenSettingsSetFactory as GenSettingsSetFactoryInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSettingsSetFactory as ImageSettingsSetFactoryInterface;

use Interpro\ImageAggr\Settings\Collection\ImageSettingsSet;
use Interpro\Core\Contracts\Taxonomy\Taxonomy as TaxonomyInterface;

class ImageSettingsSetFactory implements ImageSettingsSetFactoryInterface
{
    private $images_config;
    private $genSettingsSetFactory;
    private $taxonomy;
    private $image_settings;

    /**
     * @param array $images_config
     * @param \Interpro\Core\Contracts\Taxonomy\Taxonomy $taxonomy
     * @param \Interpro\ImageAggr\Contracts\Settings\GenSettingsSetFactory $genSettingsSetFactory
     *
     * @return void
     */
    public function __construct(TaxonomyInterface $taxonomy, array $images_config, GenSettingsSetFactoryInterface $genSettingsSetFactory)
    {
        $this->images_config         = $images_config;
        $this->genSettingsSetFactory = $genSettingsSetFactory;
        $this->taxonomy              = $taxonomy;
        $this->image_settings        = [];
    }

    private function createImageSetting($owner_type, $field_name)
    {
        $image_key = $owner_type.'.'.$field_name;

        if(array_key_exists($image_key, $this->image_settings))
        {
            return $this->image_settings[$image_key];
        }

        $color = '#808080';
        $width = 400;
        $height = 400;
        $resizes = [];
        $crops = [];

        if(array_key_exists($image_key, $this->images_config))
        {
            $attrs = $this->images_config[$image_key];

            if(array_key_exists('color', $attrs))
            {
                $color = $attrs['color'];
            }

            if(array_key_exists('width', $attrs))
            {
                $width = $attrs['width'];
            }

            if(array_key_exists('height', $attrs))
            {
                $height = $attrs['height'];
            }

            if(array_key_exists('resizes', $attrs))
            {
                $resizes = $attrs['resizes'];
            }

            if(array_key_exists('crops', $attrs))
            {
                $crops = $attrs['crops'];
            }
        }

        $resizeSettingsSet = $this->genSettingsSetFactory->createResizeSettingsSet($resizes);
        $cropSettingsSet = $this->genSettingsSetFactory->createCropSettingsSet($crops);

        $imageSetting = new ImageSetting($owner_type, $field_name, $resizeSettingsSet, $cropSettingsSet, $color, $width, $height);

        //Закэшируем, чтобы экземпляры не повторялись
        $this->image_settings[$image_key] = $imageSetting;

        return $imageSetting;
    }

    /**
     * @param $owner_name
     *
     * @return \Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet
     */
    public function create($owner_name = 'all')
    {
        //Пытаемся получить из $images_config, если нет, то создаем без конфига с одним original линком
        //Получаем массив использования типа картинки
        $imageType = $this->taxonomy->getType('image');

        $using = $imageType->getUsing();

        $imageSettings = [];

        if($owner_name === 'all')
        {
            foreach($using as $owner_type_name => $ownerType)
            {
                $fields = $ownerType->getOwns()->getTyped('image');

                foreach($fields as $field_name => $field)
                {
                    $imageSetting = $this->createImageSetting($owner_type_name, $field_name);
                    $imageSettings[$owner_type_name.'.'.$field_name] = $imageSetting;
                }
            }
        }
        else
        {
            //Проверим тип хозяина на существование
            $ownerType = $this->taxonomy->getType($owner_name);

            $owner_type_name = $ownerType->getName();

            $fields = $ownerType->getOwns()->getTyped('image');

            foreach($fields as $field_name => $field)
            {
                $imageSetting = $this->createImageSetting($owner_type_name, $field_name);
                $imageSettings[$owner_type_name.'.'.$field_name] = $imageSetting;
            }
        }

        $imageSettingsSet = new ImageSettingsSet($imageSettings);

        return $imageSettingsSet;
    }
}


<?php

namespace Interpro\ImageAggr\Db;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Extractor\Contracts\Collections\MapBCollection;
use Interpro\Extractor\Contracts\Creation\CItemBuilder;
use Interpro\Extractor\Contracts\Creation\CollectionFactory;
use Interpro\Extractor\Contracts\Db\AMapper;
use Interpro\Extractor\Contracts\Db\MappersMediator;
use Interpro\Extractor\Items\AItem;
use Interpro\Extractor\Contracts\Selection\SelectionUnit;
use Interpro\Extractor\Fields\ABOwnField;
use Interpro\Extractor\Fields\ACOwnField;
use Interpro\Extractor\Items\BlockItem;
use Interpro\ImageAggr\Exception\ImageAggrException;

class ModImagesAMapper implements AMapper
{
    private $collectionFactory;
    private $cItemBuilder;
    private $mappersMediator;
    private $item = null;
    private $local_fields = ['name' => 'modimages', 'title' => 'mod images'];

    public function __construct(CollectionFactory $collectionFactory, CItemBuilder $cItemBuilder, MappersMediator $mappersMediator)
    {
        $this->collectionFactory = $collectionFactory;
        $this->cItemBuilder      = $cItemBuilder;
        $this->mappersMediator   = $mappersMediator;
    }

    private function local($field_name)
    {
        return array_key_exists($field_name, $this->local_fields);
    }

    /**
     * @return void
     */
    public function reset()
    {
        $this->item = null;
    }

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

    /**
     * @param AItem $owner
     * @param OwnField $ownMeta
     * @param mixed $value
     *
     * @return \Interpro\Extractor\Fields\ACOwnField
     */
    private function createLocalCField(AItem $owner, OwnField $ownMeta, $value)
    {
        $fieldType = $ownMeta->getFieldType();

        $scalarItem = $this->cItemBuilder->create($fieldType, $value);

        $newField = new ACOwnField($owner, $ownMeta);
        $newField->setItem($scalarItem);

        return $newField;
    }

    private function createExternalBFieldByRef(AItem $owner, OwnField $ownMeta, MapBCollection $map)
    {
        $field_name = $ownMeta->getName();

        $ref = $owner->getSelfRef();

        $fieldItem = $map->getItem($ref, $field_name);
        $newField = new ABOwnField($owner, $ownMeta);
        $newField->setItem($fieldItem);

        return $newField;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param bool $asUnitMember
     *
     * @return \Interpro\Extractor\Contracts\Items\AItem
     */
    public function getByRef(ARef $ref, $asUnitMember = false)
    {
        if($this->item)
        {
            return $this->item;
        }

        $type  = $ref->getType();
        $rank = $type->getRank();
        $type_name = $type->getName();

        if($type_name !== 'modimages' or $rank !== TypeRank::BLOCK)
        {
            throw new ImageAggrException('Маппер предназначен для получения блока modimages(A), передано: '.$type_name.'('.$rank.')!');
        }

        $fields  = $this->collectionFactory->createFieldsCollection();
        $owns    = $this->collectionFactory->createOwnsCollection();
        $refs    = $this->collectionFactory->createRefsCollection();
        $subVars = $this->collectionFactory->createSubVarCollection($ref);

        $item = new BlockItem($ref, $fields, $owns, $refs, $subVars);

        //====================================================поля
        $ownsMetaCollection = $type->getOwns();

        foreach($ownsMetaCollection as $ownMeta)
        {
            $fieldType = $ownMeta->getFieldType();
            $fieldMode = $ownMeta->getMode();

            $field_name = $ownMeta->getName();

            if($this->local($field_name)) //все поля локального хранения - С типы
            {
                $newField = $this->createLocalCField($item, $ownMeta, $this->local_fields[$field_name]);
            }
            else
            {
                if($fieldMode === TypeMode::MODE_B)
                {
                    $mapper = $this->mappersMediator->getBMapper($fieldType->getFamily());
                    $map = $mapper->getByRef($ref);
                    $newField = $this->createExternalBFieldByRef($item, $ownMeta, $map);
                }
                elseif($fieldMode === TypeMode::MODE_C)
                {
                    throw new ImageAggrException('Попытка добавить внешнее (С)поле в блок картинок модификации, такая возможность не поддерживается!');
                }
                else
                {
                    throw new ImageAggrException('В типе '.$type_name.' обнаружено поле-собственность типа отличного от В или С: '.$field_name.'('.$fieldMode.')!');
                }
            }

            $item->setOwn($newField);
            $item->setField($newField);
        }

        $this->item = $item;

        return $item;
    }

    /**
     * @param \Interpro\Extractor\Contracts\Selection\SelectionUnit $selectionUnit
     *
     * @return \Interpro\Extractor\Contracts\Collections\MapGroupCollection
     */
    public function select(SelectionUnit $selectionUnit)
    {
        //Заглушка: возвращаем пустую коллекцию

        $type = $selectionUnit->getType();

        $mapCollection = $this->collectionFactory->createMapGroupCollection($type);

        return $mapCollection;
    }

    /**
     * @param \Interpro\Extractor\Contracts\Selection\SelectionUnit $selectionUnit
     *
     * @return int
     */
    public function count(SelectionUnit $selectionUnit)
    {
        return 0;
    }

}


<?php

namespace Interpro\ImageAggr\Executors;

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

class UpdateExecutor implements BUpdateExecutor
{
    private $saveOperation;
    private $settingsSet;

    public function __construct(SaveOperation $saveOperation, ImageSettingsSet $settingsSet)
    {
        $this->saveOperation = $saveOperation;
        $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 update(ARef $ref, OwnField $own, $user_attrs)
    {
        if(!is_array($user_attrs))
        {
            $user_attrs = [];
        }

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

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


<?php

namespace Onoi\Tesa;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class CharacterExaminer {

	const CYRILLIC = 'CYRILLIC';
	const LATIN = 'LATIN';
	const HIRAGANA_KATAKANA = 'HIRAGANA_KATAKANA';
	const HANGUL = 'HANGUL';
	const CJK_UNIFIED = 'CJK_UNIFIED';
	const HAN = 'HAN';

	/**
	 * @see http://jrgraphix.net/research/unicode_blocks.php
	 * @since 0.1
	 *
	 * @param string $type
	 * @param string $text
	 *
	 * @return boolean
	 */
	public static function contains( $type, $text ) {

		if ( $type === self::CYRILLIC ) {
			return preg_match('/\p{Cyrillic}/u', $text ) > 0;
		}

		if ( $type === self::LATIN ) {
			return preg_match('/\p{Latin}/u', $text ) > 0;
		}

		if ( $type === self::HAN ) {
			return preg_match('/\p{Han}/u', $text ) > 0;
		}

		if ( $type === self::HIRAGANA_KATAKANA ) {
			return preg_match('/[\x{3040}-\x{309F}]/u', $text ) > 0 || preg_match('/[\x{30A0}-\x{30FF}]/u', $text ) > 0; // isHiragana || isKatakana
		}

		if ( $type === self::HANGUL ) {
			return preg_match('/[\x{3130}-\x{318F}]/u', $text ) > 0 || preg_match('/[\x{AC00}-\x{D7AF}]/u', $text ) > 0;
		}

		// @see https://en.wikipedia.org/wiki/CJK_Unified_Ideographs
		// Chinese, Japanese and Korean (CJK) scripts share common characters
		// known as CJK characters

		if ( $type === self::CJK_UNIFIED ) {
			return preg_match('/[\x{4e00}-\x{9fa5}]/u', $text ) > 0;
		}

		return false;
	}

}


<?php

namespace DCS\OpauthBundle\Configuration;

use DCS\OpauthBundle\Exception\StrategyNotFoundException;
use Symfony\Component\Routing\RouterInterface;

class StrategyParser implements StrategyParserInterface
{
    /**
     * @var RouterInterface
     */
    protected $router;

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

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

    function __construct(RouterInterface $router, $callParams, array $strategies = array())
    {
        $this->router = $router;
        $this->callParams = $callParams;
        $this->strategies = $strategies;
    }

    /**
     * Get the configuration of the strategy
     *
     * @param string $strategy
     * @return array
     * @throws \DCS\OpauthBundle\Exception\StrategyNotFoundException
     */
    public function get($strategy)
    {
        if (!isset($this->strategies[$strategy])) {
            throw new StrategyNotFoundException(sprintf('Strategy "%s" not found in the configurations set', $strategy));
        }

        return $this->buildConfiguration($strategy, $this->strategies[$strategy]);
    }

    /**
     * Build the configuration params for the Opauth library
     *
     * @param $strategy
     * @param $strategyConfig
     * @return array
     */
    protected function buildConfiguration($strategy, $strategyConfig)
    {
        $config = array_merge($this->callParams, array(
            'path' => rtrim($this->router->generate('dcs_opauth_connect'), '/').'/',
            'callback_url' => $this->router->generate('dcs_opauth_response', array(
                'strategy' => $strategy,
            )),
            'security_salt' => uniqid(null, true),
        ));

        if (isset($strategyConfig['options']) && is_array($strategyConfig['options'])) {
            $strategyConfig = array_merge($strategyConfig, $strategyConfig['options']);
            unset($strategyConfig['options']);
        }

        $config['Strategy'][$strategy] = $strategyConfig;

        return $config;
    }
}


<?php
/**
 *
 */

namespace Praxigento\Accounting\Service\Account;

use Praxigento\Accounting\Api\Service\Account\Get\Request as ARequest;
use Praxigento\Accounting\Api\Service\Account\Get\Response as AResponse;
use Praxigento\Accounting\Repo\Data\Account as EAccount;

/**
 * Get account data or create new account if customer has no account for the requested asset.
 */
class Get
    implements \Praxigento\Accounting\Api\Service\Account\Get
{
    /** @var array save accounts data for system customer. */
    private $cachedSysAccs = [];
    /** @var  \Praxigento\Accounting\Repo\Dao\Account */
    private $daoAccount;
    /** @var \Praxigento\Accounting\Repo\Dao\Type\Asset */
    private $daoTypeAsset;

    public function __construct(
        \Praxigento\Accounting\Repo\Dao\Account $daoAccount,
        \Praxigento\Accounting\Repo\Dao\Type\Asset $daoTypeAsset
    )
    {
        $this->daoAccount = $daoAccount;
        $this->daoTypeAsset = $daoTypeAsset;
    }

    /**
     * Perform DB to API data conversion directly.
     *
     * @param \Praxigento\Accounting\Repo\Data\Account $acc
     * @return \Praxigento\Accounting\Api\Service\Account\Get\Response
     */
    private function composeResult(EAccount $acc)
    {
        /** define local working data */
        $accId = $acc->getId();
        $custId = $acc->getCustomerId();
        $balance = $acc->getBalance();
        $typeId = $acc->getAssetTypeId();

        /** compose result */
        $result = new AResponse();
        $result->setId($accId);
        $result->setCustomerId($custId);
        $result->setBalance($balance);
        $result->setAssetTypeId($typeId);
        return $result;
    }

    /**
     * Get account data or create new account if customer has no account for the requested asset.
     *
     * @param ARequest $request
     *
     * @return AResponse
     */
    public function exec($request)
    {
        assert($request instanceof ARequest);
        /** define local working data */
        $typeCode = $request->getAssetTypeCode();
        $typeId = $request->getAssetTypeId();
        $custId = $request->getCustomerId();
        $isSys = $request->getIsSystem();

        /** perform processing */
        if (is_null($typeId)) {
            /* get type ID by code if missed */
            $typeId = $this->daoTypeAsset->getIdByCode($typeCode);
        }

        /* return cached data for system customer if exists */
        if (
            $isSys &&
            isset($this->cachedSysAccs[$typeId])
        ) {
            $result = $this->cachedSysAccs[$typeId];
        } else {
            /* ... or get data from DB */
            if ($isSys) {
                /* get system customer ID */
                $custId = $this->daoAccount->getSystemCustomerId();
            }
            $account = $this->getAccount($custId, $typeId);
            $result = $this->composeResult($account);
            /* cache data for system customer */
            if ($isSys) {
                $this->cachedSysAccs[$typeId] = $result;
            }
        }

        /** compose result */
        return $result;
    }

    /**
     * Get account by $custId & asset $typeId or create new one if not found.
     *
     * @param int $custId
     * @param int $typeId
     * @return EAccount
     */
    private function getAccount($custId, $typeId)
    {
        /** perform processing & compose result */
        /* get account by customerId & assetTypeId */
        $result = $this->daoAccount->getByCustomerId($custId, $typeId);
        if (!$result) {
            /* create new account */
            $result = new EAccount();
            $result->setCustomerId($custId);
            $result->setAssetTypeId($typeId);
            $result->setBalance(0);
            $accId = $this->daoAccount->create($result);
            $result->setId($accId);
        }
        return $result;
    }

}


<?php

namespace Interpro\ImageAggr\Collections;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Extractor\Contracts\Collections\MapBCollection;
use Interpro\Extractor\Contracts\Items\AggrOwnItem;
use Interpro\ImageAggr\Creation\CapGenerator;
use Interpro\ImageAggr\Exception\ImageAggrException;

class MapImageCollection implements MapBCollection
{
    private $items = [];
    private $capGenerator;

    public function __construct(CapGenerator $capGenerator)
    {
        $this->capGenerator = $capGenerator;
    }

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

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param string $field_name
     *
     * @return \Interpro\Extractor\Contracts\Items\AggrOwnItem
     */
    public function getItem(ARef $ref, $field_name)
    {
        $ownerType = $ref->getType();

        if(!$ownerType->fieldExist($field_name))
        {
            throw new ImageAggrException('Обращение к несуществующей картинке '.$field_name.' в хозяине типа '.$ownerType->getName().'!');
        }

        $ownField = $ownerType->getField($field_name);

        if($ownField->getFieldTypeName() !== 'image')
        {
            throw new ImageAggrException('Обращение к несуществующей картинке '.$field_name.' в хозяине типа '.$ownerType->getName().'!');
        }

        $type_name = $ownerType->getName();
        $key = $field_name.'_'.$ref->getId();

        if(!array_key_exists($type_name, $this->items))
        {
            $this->items[$type_name] = [];
        }

        if(!array_key_exists($key, $this->items[$type_name]))
        {
            $item = $this->capGenerator->createImage($ownField);

            $this->items[$type_name][$key] = $item;
        }

        return $this->items[$type_name][$key];
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param string $field_name
     * @param \Interpro\Extractor\Contracts\Items\AggrOwnItem $item
     *
     * @return void
     */
    public function addItem(ARef $ref, $field_name, AggrOwnItem $item)
    {
        $ownerType = $ref->getType();
        $type_name = $ownerType->getName();
        $key = $field_name.'_'.$ref->getId();

        if(!array_key_exists($type_name, $this->items))
        {
            $this->items[$type_name] = [];
        }

        $this->items[$type_name][$key] = $item;
    }

}


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

namespace Praxigento\Accounting\Service\Operation;

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

class Create
    implements \Praxigento\Accounting\Api\Service\Operation\Create
{
    /** @var \Praxigento\Accounting\Repo\Dao\Log\Change\Admin */
    private $daoELogChangeAdmin;
    /** @var \Praxigento\Accounting\Repo\Dao\Log\Change\Customer */
    private $daoELogChangeCust;
    /** @var  \Praxigento\Accounting\Repo\Dao\Operation */
    private $daoOper;
    /** @var  \Praxigento\Accounting\Repo\Dao\Type\Operation */
    private $daoTypeOper;
    /** @var \Praxigento\Core\Api\Helper\Date */
    private $hlpDate;
    /** @var \Psr\Log\LoggerInterface */
    private $logger;
    /**
     * Don't delete transaction from this service.
     * Better this service will break outer transaction than we will clean up data manually.
     *
     * @var  \Praxigento\Core\Api\App\Repo\Transaction\Manager
     */
    private $manTrans;
    /** @var \Praxigento\Accounting\Service\Operation\Create\A\Add */
    private $ownAdd;
    /** @var \Magento\Backend\Model\Auth\Session */
    private $sessAdmin;
    /** @var \Magento\Customer\Model\Session */
    private $sessCust;

    public function __construct(
        \Magento\Backend\Model\Auth\Session $sessAdmin,
        \Magento\Customer\Model\Session $sessCust,
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\App\Repo\Transaction\Manager $manTrans,
        \Praxigento\Accounting\Repo\Dao\Operation $daoOper,
        \Praxigento\Accounting\Repo\Dao\Type\Operation $daoTypeOper,
        \Praxigento\Accounting\Repo\Dao\Log\Change\Admin $daoELogChangeAdmin,
        \Praxigento\Accounting\Repo\Dao\Log\Change\Customer $daoELogChangeCust,
        \Praxigento\Core\Api\Helper\Date $hlpDate,
        \Praxigento\Accounting\Service\Operation\Create\A\Add $ownAdd
    ) {
        $this->sessAdmin = $sessAdmin;
        $this->sessCust = $sessCust;
        $this->logger = $logger;
        $this->manTrans = $manTrans;
        $this->daoTypeOper = $daoTypeOper;
        $this->daoOper = $daoOper;
        $this->daoELogChangeAdmin = $daoELogChangeAdmin;
        $this->daoELogChangeCust = $daoELogChangeCust;
        $this->hlpDate = $hlpDate;
        $this->ownAdd = $ownAdd;
    }

    /**
     * Add operation with list of transactions and change account balances.
     *
     * @param ARequest $request
     *
     * @return AResponse
     * @throws \Exception
     */
    public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();
        $operationTypeId = $request->getOperationTypeId();
        $operationTypeCode = $request->getOperationTypeCode();
        $datePerformed = $request->getDatePerformed();
        $note = $request->getOperationNote();
        $transactions = $request->getTransactions();
        $asRef = $request->getAsTransRef();
        $customerId = $request->getCustomerId();
        $adminUserId = $request->getAdminUserId();

        if (empty($datePerformed)) {
            $datePerformed = $this->hlpDate->getUtcNowForDb();
        }
        /* add operation itself */
        if (!$operationTypeId) {
            $operationTypeId = $this->daoTypeOper->getIdByCode($operationTypeCode);
        }
        $bindToAdd = [
            EOperation::A_TYPE_ID => $operationTypeId,
            EOperation::A_DATE_PREFORMED => $datePerformed
        ];
        if (!is_null($note)) {
            $bindToAdd[EOperation::A_NOTE] = $note;
        }
        $validTrans = $this->validateTransactions($transactions);
        if ($validTrans == AResponse::ERR_NO_ERROR) {
            /**
             * Better this nested transaction will break outer transaction than we will clean up data manually.
             */
            $def = $this->manTrans->begin();
            try {

                $operId = $this->daoOper->create($bindToAdd);
                if ($operId) {
                    $transIds = $this->ownAdd->exec($operId, $transactions, $datePerformed, $asRef);
                    $result->setOperationId($operId);
                    $result->setTransactionsIds($transIds);
                    /* extract IDs from sessions if both are empty */
                    list($customerId, $adminUserId) = $this->prepareLogIds($customerId, $adminUserId);
                    /* log customer link */
                    if ($customerId) {
                        $log = new \Praxigento\Accounting\Repo\Data\Log\Change\Customer();
                        $log->setCustomerRef($customerId);
                        $log->setOperationRef($operId);
                        $this->daoELogChangeCust->create($log);
                    }
                    /* log admin link */
                    if ($adminUserId) {
                        $log = new \Praxigento\Accounting\Repo\Data\Log\Change\Admin();
                        $log->setUserRef($adminUserId);
                        $log->setOperationRef($operId);
                        $this->daoELogChangeAdmin->create($log);
                    }
                    $this->manTrans->commit($def);
                    $result->markSucceed();
                }

            } finally {
                /* rollback transaction if not committed (on exception, for example) */
                $this->manTrans->end($def);
            }
        } else {
            $dump = var_export($request, true);
            $this->logger->error("Validation error: $validTrans. Details: $dump.");
            $result->setErrorCode($validTrans);
        }
        return $result;
    }

    /**
     * Extract IDs from sessions if both are empty.
     *
     * @param int $custId .
     * @param int $adminId
     * @return int[]
     */
    private function prepareLogIds($custId, $adminId)
    {

        if (!$custId && !$adminId) {
            /* both are empty */
            $customer = $this->sessCust->getCustomer();
            if ($customer) {
                $custId = $customer->getId();
            }
            $user = $this->sessAdmin->getUser();
            if ($user instanceof \Magento\User\Model\User) {
                $adminId = $user->getId();
            }
        }
        return [$custId, $adminId];
    }

    /**
     * Validate transactions.
     *
     * @param ETrans[] $trans
     * @return string
     */
    private function validateTransactions($trans)
    {
        $result = AResponse::ERR_NO_ERROR;
            foreach ($trans as $one) {
                if (is_array($one)) {
                    $accDbt = $one[ETrans::A_DEBIT_ACC_ID];
                    $accCrd = $one[ETrans::A_CREDIT_ACC_ID];
                } else {
                    $accDbt = $one->getDebitAccId();
                    $accCrd = $one->getCreditAccId();
                }
                if ($accDbt == $accCrd) {
                    $result = AResponse::ERR_ONE_ACCOUNT_FOR_DEBIT_AND_CREDIT;
                    break;
                }
            }
        return $result;
    }
}


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

namespace Praxigento\Accounting\Service\Account\Balance;

use Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Request as ARequest;
use Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Response as AResponse;
use Praxigento\Accounting\Repo\Data\Account as EAccount;
use Praxigento\Accounting\Repo\Data\Balance as EBalance;
use Praxigento\Accounting\Repo\Data\Transaction as ETran;
use Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMaxDateBalance as QGetMaxDate;
use Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMinDateTrans as QGetMinDate;
use Praxigento\Core\Api\Helper\Period as HPeriod;

class LastDate
    implements \Praxigento\Accounting\Api\Service\Account\Balance\LastDate
{
    /** @var \Praxigento\Accounting\Repo\Dao\Type\Asset */
    private $daoTypeAsset;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMaxDateBalance */
    private $qGetMaxDate;
    /** @var \Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMinDateTrans */
    private $qGetMinDate;

    public function __construct(
        \Praxigento\Accounting\Repo\Dao\Type\Asset $daoTypeAsset,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMaxDateBalance $qGetMaxDate,
        \Praxigento\Accounting\Service\Account\Balance\LastDate\A\Repo\Query\GetMinDateTrans $qGetMinDate
    ) {
        $this->daoTypeAsset = $daoTypeAsset;
        $this->hlpPeriod = $hlpPeriod;
        $this->qGetMaxDate = $qGetMaxDate;
        $this->qGetMinDate = $qGetMinDate;
    }

    /**
     * Get the last date for the balance (by asset type or by account).
     *
     * @param \Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Request $request
     * @return \Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Response
     * @throws \Exception
     */
    public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();

        /** define local working data */
        $accountId = $request->getAccountId();
        $assetTypeId = $request->getAssetTypeId();
        $assetTypeCode = $request->getAssetTypeCode();
        $lastDate = null;

        /** validate pre-processing conditions */
        if (
            is_null($assetTypeId) &&
            !empty($assetTypeCode)
        ) {
            $assetTypeId = $this->daoTypeAsset->getIdByCode($assetTypeCode);
        }

        /** perform processing */
        if (!empty($accountId)) {
            /* prefer to get by account */
            $lastDate = $this->getBalanceMaxDateByAccId($accountId);
            if (!$lastDate) {
                /* balances are empty for the account, get transaction with minimal date */
                $transMinDate = $this->getTranMinDateByAccId($accountId);
                if ($transMinDate) {
                    $period = $this->hlpPeriod->getPeriodCurrent($transMinDate);
                    $lastDate = $this->hlpPeriod->getPeriodPrev($period, HPeriod::TYPE_DAY);
                }
            }
        } else if (!empty($assetTypeId)) {
            /* or get by assetType */
            $lastDate = $this->getBalanceMaxDateByAssetType($assetTypeId);
            if (!$lastDate) {
                /* there is no balance data yet, get transaction with minimal date */
                $transMinDate = $this->getTranMinDateByAssetType($assetTypeId);
                if ($transMinDate) {
                    $period = $this->hlpPeriod->getPeriodCurrent($transMinDate);
                    $lastDate = $this->hlpPeriod->getPeriodPrev($period, HPeriod::TYPE_DAY);
                }
            }
        }

        /** compose result */
        if ($lastDate) {
            $result->setLastDate($lastDate);
            $result->markSucceed();
        }
        return $result;
    }

    private function getBalanceMaxDateByAccId($accId)
    {
        $query = $this->qGetMaxDate->build();
        $where = QGetMaxDate::AS_BAL . '.' . EBalance::A_ACCOUNT_ID . '=' . (int)$accId;
        $query->where($where);

        $conn = $query->getConnection();
        $result = $conn->fetchOne($query);
        return $result;
    }

    private function getBalanceMaxDateByAssetType($assetTypeId)
    {
        $query = $this->qGetMaxDate->build();
        $where = QGetMaxDate::AS_ACC . '.' . EAccount::A_ASSET_TYPE_ID . '=' . (int)$assetTypeId;
        $query->where($where);

        $conn = $query->getConnection();
        $result = $conn->fetchOne($query);
        return $result;
    }

    private function getTranMinDateByAccId($accId)
    {
        $query = $this->qGetMinDate->build();
        $byDebit = QGetMinDate::AS_TRAN . '.' . ETran::A_DEBIT_ACC_ID . '=' . (int)$accId;
        $byCredit = QGetMinDate::AS_TRAN . '.' . ETran::A_CREDIT_ACC_ID . '=' . (int)$accId;
        $where = "($byDebit) OR ($byCredit)";
        $query->where($where);

        $conn = $query->getConnection();
        $result = $conn->fetchOne($query);
        return $result;
    }

    private function getTranMinDateByAssetType($assetTypeId)
    {
        $query = $this->qGetMinDate->build();
        $where = QGetMinDate::AS_ACC . '.' . EAccount::A_ASSET_TYPE_ID . '=' . (int)$assetTypeId;
        $query->where($where);

        $conn = $query->getConnection();
        $result = $conn->fetchOne($query);
        return $result;
    }
}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Operation\InitOperation as InitOperationInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;

class InitOperation extends Operation implements InitOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param array $user_attrs
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting, array $user_attrs = [])
    {
        $this->checkOwner($aRef);

        //Не обращая внимание на то что хранится в папке оригинала проставляем везде плейсхолдеры
        //Если в БД совпали по ключам записи для картинки - сохраняем значения атрибутов неизменными

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

        $user_attrs['link'] = $original_file_path;

        $this->dbAgent->imageToDb($aRef, $imageSetting, $user_attrs, true);

        $resize_attrs = [];
        if(array_key_exists('resizes', $user_attrs))
        {
            $resize_attrs = $user_attrs['resizes'];
        }

        $crop_attrs = [];
        if(array_key_exists('crops', $user_attrs))
        {
            $crop_attrs = $user_attrs['crops'];
        }

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

}


<?php

namespace Interpro\ImageAggr\Creation;

use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Items\ImageItem;

class CapGenerator
{
    private $imageItemFactory;
    private $settingsSet;

    public function __construct(ImageSettingsSet $settingsSet)
    {
        $this->imageItemFactory = null;
        $this->settingsSet = $settingsSet;
    }

    public function setFactory(ImageItemFactory $imageItemFactory)
    {
        $this->imageItemFactory = $imageItemFactory;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $field
     * @param string $resize_name
     * @param \Interpro\ImageAggr\Items\ImageItem $original
     *
     * @return \Interpro\ImageAggr\Items\ResizeItem
     */
    public function createResize(OwnField $field, $resize_name, ImageItem $original)
    {
        if(!$this->imageItemFactory)
        {
            throw new ImageAggrException('Для генератора заглушек не установлена фабрика элементов!');
        }

        $type = $field->getFieldType();
        $subs = $type->getSubs('original');
        $resizeType = $subs->getSub('resize');

        $resizeItem  = $this->imageItemFactory->createResize($resizeType, ['name' => $resize_name], true);

        $resizeItem->getRef('original')->setItem($original);

        return $resizeItem;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $field
     * @param string $crop_name
     * @param \Interpro\ImageAggr\Items\ImageItem $original
     *
     * @return \Interpro\ImageAggr\Items\CropItem
     */
    public function createCrop(OwnField $field, $crop_name, ImageItem $original)
    {
        if(!$this->imageItemFactory)
        {
            throw new ImageAggrException('Для генератора заглушек не установлена фабрика элементов!');
        }

        $type = $field->getFieldType();
        $subs = $type->getSubs('original');
        $cropType = $subs->getSub('crop');

        $cropItem  = $this->imageItemFactory->createCrop($cropType, ['name' => $crop_name], true);

        $cropSetting = $this->settingsSet->getImage($field)->getCrop($crop_name);

        $cropItem->getRef('original')->setItem($original);

        $man_name = $cropSetting->getMan()->getName();
        $target_name = $cropSetting->getTarget()->getName();

        $cropItem->getRef('man')->setItem($original->getResize($man_name));
        $cropItem->getRef('target')->setItem($original->getResize($target_name));

        return $cropItem;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $field
     *
     * @return \Interpro\ImageAggr\Items\ImageItem
     */
    public function createImage(OwnField $field)
    {
        if(!$this->imageItemFactory)
        {
            throw new ImageAggrException('Для генератора заглушек не установлена фабрика элементов!');
        }

        $type = $field->getFieldType();

        $subs = $type->getSubs('original');
        $resizeType = $subs->getSub('resize');
        $cropType = $subs->getSub('crop');

        $name = $field->getName();

        $item  = $this->imageItemFactory->createImage($field, ['name' => $name], true);

        //Ресайзы
        $resizesSet = $this->settingsSet->getImage($field)->getResizes();

        foreach($resizesSet as $resize_name => $resizeSetting)
        {
            $resizeItem  = $this->imageItemFactory->createResize($resizeType, ['name' => $resize_name], true);

            $resizeItem->getRef('original')->setItem($item);

            $item->addResize($resizeItem);
        }

        //Кропы
        $cropsSet = $this->settingsSet->getImage($field)->getCrops();

        foreach($cropsSet as $crop_name => $cropSetting)
        {
            $cropItem  = $this->imageItemFactory->createCrop($cropType, ['name' => $crop_name], true);

            $cropItem->getRef('original')->setItem($item);

            $man_name = $cropSetting->getMan()->getName();
            $target_name = $cropSetting->getTarget()->getName();

            $cropItem->getRef('man')->setItem($item->getResize($man_name));
            $cropItem->getRef('target')->setItem($item->getResize($target_name));

            $item->addCrop($cropItem);
        }

        return $item;
    }

}