<?php

namespace Interpro\ImageAggr\Db;

use Interpro\Core\Contracts\Mediator\RefConsistMediator;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Settings\CropSetting as CropSettingInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting as ImageSettingInterface;
use Interpro\ImageAggr\Contracts\Settings\ResizeSetting as ResizeSettingInterface;
use Interpro\ImageAggr\Model\Crop;
use Interpro\ImageAggr\Model\Image;
use Interpro\ImageAggr\Model\Resize;
use Interpro\ImageAggr\Contracts\Db\ImageAggrDbAgent as ImageAggrDbAgentInterface;

class ImageAggrDbAgent implements ImageAggrDbAgentInterface
{
    private $refConsistMediator;
    /**
     * @return void
     */
    public function __construct(RefConsistMediator $refConsistMediator)
    {
        $this->refConsistMediator = $refConsistMediator;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     */
    public function ownerExist(ARef $aRef)
    {
        return $this->refConsistMediator->exist($aRef);
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     *
     * @return array
     */
    public function getCropsCoordinates(ARef $aRef, ImageSettingInterface $imageSetting)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $owner_id = $aRef->getId();

        $collection = Crop::where('entity_name', '=', $owner_name)
            ->where('entity_id', '=', $owner_id)
            ->where('image_name', '=', $image_name)
            ->get();

        $crops_array = [];

        foreach($collection as $crop)
        {
            $crops_array[$crop->name] = ['x' => $crop->x, 'y'=> $crop->y];
        }

        return $crops_array;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param array $attrs
     *
     * @return void
     */
    public function imageToDb(ARef $aRef, ImageSettingInterface $imageSetting, $attrs = [], $init = false)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $owner_id = $aRef->getId();

        $collection = Image::where('entity_name', '=', $owner_name)->where('entity_id', '=', $owner_id)->where('name', '=', $image_name)->get();

        $cache_index = 0;

        $image = null;

        //Удалим лишние записи по этому ключу, если есть (на всякий случай, т. к. записи в БД уникальны по авто инк. id)
        foreach($collection as $curr_image)
        {
            if($image === null)
            {
                $cache_index = $curr_image->cache_index;
                $image = $curr_image;

                if($init)
                {
                    break;
                }
            }
            else
            {
                $image->delete();
            }
        }

        $db = !$init;

        if($image === null)
        {
            $image = new Image;
            $image->alt = '';
            $image->link = '';
            $image->width = 400;
            $image->height = 400;
            $db = true;
        }

        $cache_index++;

        if($db)
        {
            //Если реквизита нет переданных для записи или не собираемся записывать в базу(инициализация), то взять для построения item'а реквизит из базы
            if(!array_key_exists('alt', $attrs))
            {
                $attrs['alt'] = $image->alt;
            }

            if(!array_key_exists('link', $attrs))
            {
                $attrs['link'] = $image->link;
            }

            if(!array_key_exists('width', $attrs))
            {
                $attrs['width'] = $image->width;
            }

            if(!array_key_exists('height', $attrs))
            {
                $attrs['height'] = $image->height;
            }

            $image->cache_index  = $cache_index;
            $image->entity_name  = $owner_name;
            $image->entity_id    = $owner_id;
            $image->name         = $image_name;
            $image->alt          = $attrs['alt'];
            $image->link         = $attrs['link'];
            $image->width        = $attrs['width'];
            $image->height       = $attrs['height'];

            $image->save();
        }
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Interpro\ImageAggr\Contracts\Settings\ResizeSetting $resizeSetting
     * @param array $attrs
     *
     * @return void
     */
    public function resizeToDb(ARef $aRef, ImageSettingInterface $imageSetting, ResizeSettingInterface $resizeSetting, $attrs = [], $init = false)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $resize_name = $resizeSetting->getName();
        $owner_id = $aRef->getId();

        $collection = Resize::where('entity_name', '=', $owner_name)
            ->where('entity_id', '=', $owner_id)
            ->where('image_name', '=', $image_name)
            ->where('name', '=', $resize_name)
            ->get();

        $cache_index = 0;

        $resize = null;

        //Удалим все записи по этому ключу (на всякий случай, т. к. записи в БД уникальны по авто инк. id)
        foreach($collection as $curr_resize)
        {
            if($resize === null)
            {
                $cache_index = $curr_resize->cache_index;
                $resize = $curr_resize;

                if($init)
                {
                    break;
                }
            }
            else
            {
                $curr_resize->delete();
            }
        }

        $db = !$init;

        if($resize === null)
        {
            $resize = new Resize;
            $resize->alt = '';
            $resize->link = '';
            $resize->width = 400;
            $resize->height = 400;
            $db = true;
        }

        $cache_index++;

        if($db)
        {
            if(!array_key_exists('alt', $attrs))
            {
                $attrs['alt'] = $resize->alt;
            }

            if(!array_key_exists('link', $attrs))
            {
                $attrs['link'] = $resize->link;
            }

            if(!array_key_exists('width', $attrs))
            {
                $attrs['width'] = $resize->width;
            }

            if(!array_key_exists('height', $attrs))
            {
                $attrs['height'] = $resize->height;
            }

            $resize->cache_index = $cache_index;
            $resize->entity_name = $owner_name;
            $resize->entity_id   = $owner_id;
            $resize->image_name  = $image_name;
            $resize->name        = $resize_name;
            $resize->alt         = $attrs['alt'];
            $resize->link        = $attrs['link'];
            $resize->width       = $attrs['width'];
            $resize->height      = $attrs['height'];

            $resize->save();
        }
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Interpro\ImageAggr\Contracts\Settings\CropSetting $cropSetting
     * @param array $attrs
     *
     * @return void
     */
    public function cropToDb(ARef $aRef, ImageSettingInterface $imageSetting, CropSettingInterface $cropSetting, $attrs = [], $init = false)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $crop_name = $cropSetting->getName();
        $owner_id = $aRef->getId();

        $collection = Crop::where('entity_name', '=', $owner_name)
            ->where('entity_id', '=', $owner_id)
            ->where('image_name', '=', $image_name)
            ->where('name', '=', $crop_name)
            ->get();

        $cache_index = 0;

        $crop = null;

        //Удалим лишние записи по этому ключу, если есть (на всякий случай, т. к. записи в БД уникальны по авто инк. id)
        foreach($collection as $curr_crop)
        {
            if($crop === null)
            {
                $cache_index = $curr_crop->cache_index;
                $crop = $curr_crop;

                if($init)
                {
                    break;
                }
            }
            else
            {
                $crop->delete();
            }
        }

        $db = !$init;

        if($crop === null)
        {
            $crop = new Crop;
            $crop->alt = '';
            $crop->link = '';
            $crop->width = 400;
            $crop->height = 400;
            $crop->x = 0;
            $crop->y = 0;
            $db = true;
        }

        $cache_index++;

        if($db)
        {
            if(!array_key_exists('alt', $attrs))
            {
                $attrs['alt'] = $crop->alt;
            }

            if(!array_key_exists('link', $attrs))
            {
                $attrs['link'] = $crop->link;
            }

            if(!array_key_exists('width', $attrs))
            {
                $attrs['width'] = $crop->width;
            }

            if(!array_key_exists('height', $attrs))
            {
                $attrs['height'] = $crop->height;
            }

            if(!array_key_exists('x', $attrs))
            {
                $attrs['x'] = $crop->x;
            }

            if(!array_key_exists('y', $attrs))
            {
                $attrs['y'] = $crop->y;
            }

            $crop->name        = $crop_name;
            $crop->entity_name = $owner_name;
            $crop->entity_id   = $owner_id;
            $crop->image_name  = $image_name;
            $crop->alt         = $attrs['alt'];
            $crop->link        = $attrs['link'];
            $crop->man_name    = $cropSetting->getMan()->getName();
            $crop->target_name = $cropSetting->getTarget()->getName();
            $crop->cache_index = $cache_index;

            $crop->x = $attrs['x'];
            $crop->y = $attrs['y'];

            //Кроп всегда задан постоянными размерами
            $crop->width  = $attrs['width'];
            $crop->height = $attrs['height'];

            $crop->save();
        }
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     *
     * @return void
     */
    public function deleteImage(ARef $aRef, ImageSettingInterface $imageSetting)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $owner_id = $aRef->getId();

        //Удалим все записи по этому ключу (на всякий случай, т. к. записи в БД уникальны по авто инк. id)
        Image::where('entity_name', '=', $owner_name)->where('entity_id', '=', $owner_id)->where('name', '=', $image_name)->delete();
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Interpro\ImageAggr\Contracts\Settings\ResizeSetting $resizeSetting
     *
     * @return void
     */
    public function deleteResize(ARef $aRef, ImageSettingInterface $imageSetting, ResizeSettingInterface $resizeSetting)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $resize_name = $resizeSetting->getName();
        $owner_id = $aRef->getId();

        Resize::where('entity_name', '=', $owner_name)
            ->where('entity_id', '=', $owner_id)
            ->where('image_name', '=', $image_name)
            ->where('name', '=', $resize_name)
            ->delete();
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $aRef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     * @param \Interpro\ImageAggr\Contracts\Settings\CropSetting $cropSetting
     *
     * @return void
     */
    public function deleteCrop(ARef $aRef, ImageSettingInterface $imageSetting, CropSettingInterface $cropSetting)
    {
        $owner_name = $aRef->getType()->getName();
        $image_name = $imageSetting->getName();
        $crop_name = $cropSetting->getName();
        $owner_id = $aRef->getId();

        Crop::where('entity_name', '=', $owner_name)
            ->where('entity_id', '=', $owner_id)
            ->where('image_name', '=', $image_name)
            ->where('name', '=', $crop_name)
            ->delete();
    }

}


<?php

namespace Onoi\Tesa\StopwordAnalyzer;

use Cdb\Reader;
use Cdb\Writer;
use Exception;
use RuntimeException;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class CdbStopwordAnalyzer implements StopwordAnalyzer {

	/**
	 * Any change to the content of its data files should be reflected in a
	 * version change (the version number does not necessarily correlate with
	 * the library version)
	 */
	const VERSION = '0.1.cdb';

	/**
	 * @var Cdb
	 */
	private $cdb;

	/**
	 * @since 0.1
	 *
	 * @param string $target
	 */
	public function __construct( $target ) {
		try {
			$this->cdb = Reader::open( $target );
		} catch( Exception $e ) {
			// Do nothing
		}
	}

	/**
	 * @since 0.1
	 *
	 * @return boolean
	 */
	public function isAvailable() {
		return $this->cdb !== null;
	}

	/**
	 * @since 0.1
	 *
	 * @param string $language
	 *
	 * @return string
	 */
	public static function getLocation() {
		return str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, __DIR__ . '/data/' );
	}

	/**
	 * @since 0.1
	 *
	 * @param string $language
	 *
	 * @return string
	 */
	public static function getTargetByLanguage( $language ) {
		return self::getLocation() . 'cdb/' . strtolower( $language )  . '.cdb';
	}

	/**
	 * @since 0.1
	 *
	 * @param string $word
	 *
	 * @return boolean
	 */
	public function isStopWord( $word ) {

		if ( $this->cdb !== null && $this->cdb->get( $word ) !== false ) {
			return true;
		}

		return false;
	}

	/**
	 * @since 0.1
	 *
	 * @param string $location
	 * @param string $language
	 *
	 * @return boolean
	 */
	public static function createCdbByLanguage( $location, $language ) {

		$language = strtolower( $language );
		$source = $location . $language . '.json';

		if ( !file_exists( $source ) ) {
			throw new RuntimeException( "{$source} is not available." );
		}

		$contents = json_decode( file_get_contents( $source ), true );

		if ( !isset( $contents['list'] ) ) {
			throw new RuntimeException( "JSON is missing the `list` index." );
		}

		$writer = Writer::open(
			self::getTargetByLanguage( $language )
		);

		foreach ( $contents['list'] as $words ) {
			$writer->set( trim( $words ), true );
		}

		$writer->close();

		return true;
	}

}


<?php

namespace Interpro\ImageAggr\Operation;

use Illuminate\Support\Facades\File;
use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Settings\Enum\GenVariant;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;
use Interpro\ImageAggr\Exception\OperationException;
use Interpro\ImageAggr\Contracts\Operation\Enum\MimeType;
use Interpro\ImageAggr\Contracts\Operation\RefreshOperation as RefreshOperationInterface;

class RefreshOperation extends Operation implements RefreshOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting)
    {
        $owner_name = $aRef->getType()->getName();
        $owner_id = $aRef->getId();
        $image_name = $imageSetting->getName();

        $this->checkOwner($aRef);

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

        if (!is_readable($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;

        $phway = true;

        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)
        {
            $original_file_path = $this->phAgent->getPh(
                $imageSetting->getWidth(),
                $imageSetting->getHeight(),
                $imageSetting->getColor()
            );

            $original_mime = MimeType::JPEG;
        }
        else
        {
            $original_file_path = $this->pathResolver->getImagePath().'/'.$image_prefix.'.'.$original_ext;
        }

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

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

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

            if($vector)
            {
                $this->makeSameImageResizes($aRef, $imageSetting, $original_file_name);
                $this->makeSameImageCrops($aRef, $imageSetting, $original_file_name);
            }
            else
            {
                //В Save операции координаты будут приходить от пользователя, здесь из базы
                $crop_xy = $this->dbAgent->getCropsCoordinates($aRef, $imageSetting);

                $this->makeImageResizes($aRef, $imageSetting);
                $this->makeImageCrops($aRef, $imageSetting, $crop_xy);
            }
        }

    }
}


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

namespace Praxigento\Accounting\Service\Account\Balance;

use Praxigento\Accounting\Repo\Data\Account as EAccount;
use Praxigento\Accounting\Repo\Data\Balance as EBalance;
use Praxigento\Accounting\Service\Account\Balance\Reset\Request as ARequest;
use Praxigento\Accounting\Service\Account\Balance\Reset\Response as AResponse;

class Reset
{
    /** @var \Praxigento\Accounting\Repo\Dao\Balance */
    private $daoBalance;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Magento\Framework\App\ResourceConnection */
    private $resource;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Accounting\Repo\Dao\Balance $daoBalance
    ) {
        $this->resource = $resource;
        $this->logger = $logger;
        $this->daoBalance = $daoBalance;
    }

    /**
     * Reset balance history for all accounts on dates after requested (excl.).
     *
     * @param ARequest $request
     * @return AResponse
     * @throws \Exception
     */
    public function exec($request)
    {
        assert($request instanceof ARequest);
        /** define local working data */
        $accounts = $request->getAccounts();
        $assetTypes = $request->getAssetTypes();
        $dateFrom = $request->getDateFrom();

        if (is_array($accounts)) {
            /* reset balances for the given accounts */
            $deleted = $this->resetByAccounts($accounts, $dateFrom);
        } elseif (is_array($assetTypes)) {
            /* reset balances for the given assets */
            $deleted = $this->resetByAssets($assetTypes, $dateFrom);
        } else {
            /* reset all balances */
            $deleted = $this->resetAll($dateFrom);
        }
        $this->logger->info("Total $deleted balances where reset.");
        /** compose result */
        $result = new AResponse();
        $result->setRowsDeleted($deleted);
        $result->markSucceed();
        return $result;
    }

    /**
     * Quotes string data to use inside SQL queries.
     *
     * @param string $data
     * @return string
     */
    private function quote($data)
    {
        $conn = $this->resource->getConnection();
        $result = $conn->quote($data);
        return $result;
    }

    /**
     * Reset all balances starting from date.
     *
     * @param $dateFrom
     * @return int
     */
    private function resetAll($dateFrom)
    {
        $quoted = $this->quote($dateFrom);
        $where = EBalance::A_DATE . '>' . $quoted;
        $result = (int)$this->daoBalance->delete($where);
        return $result;
    }

    private function resetByAccounts($accounts, $dateFrom)
    {
        $result = 0;
        $json = json_encode($accounts);
        $this->logger->info("Reset balances greater than '$dateFrom' for accounts: $json.");
        if (count($accounts)) {
            $quoted = $this->quote($dateFrom);
            $where = EBalance::A_ACCOUNT_ID . ' IN (';
            foreach ($accounts as $account) {
                $id = (int)$account;
                $where .= "$id,";
            }
            /* trim the last ',' */
            $where = substr($where, 0, strlen($where) - 1);
            $where .= ')';
            $where .= " AND (" . EBalance::A_DATE . ">$quoted)";
            $result = (int)$this->daoBalance->delete($where);
        }
        return $result;
    }

    private function resetByAssets($assets, $dateFrom)
    {
        $result = 0;
        $json = json_encode($assets);
        $this->logger->info("Reset balances greater than '$dateFrom' for assets: $json.");
        if (count($assets)) {
            $query = $this->queryDeleteByAssets($assets, $dateFrom);
            $conn = $this->resource->getConnection();
            $stmt = $conn->query($query);
            $result = $stmt->rowCount();
        }
        return $result;
    }

    /**
     * Compose query to delete balances filtered by asset types and date.
     *
     * @param int[] $assetTypeIds
     * @param string $dateFrom
     * @return string
     */
    private function queryDeleteByAssets($assetTypeIds, $dateFrom)
    {
        $tblAcc = $this->resource->getTableName(EAccount::ENTITY_NAME);
        $tblBal = $this->resource->getTableName(EBalance::ENTITY_NAME);
        $conn = $this->resource->getConnection();
        $quoted = $conn->quote($dateFrom);
        $in = '';
        foreach ($assetTypeIds as $id) {
            $in .= (int)$id . ',';
        }
        $in = substr($in, 0, strlen($in) - 1);
        $select = "SELECT " . EAccount::A_ID . " FROM $tblAcc";
        $select .= " WHERE " . EAccount::A_ASSET_TYPE_ID . " IN ($in)";
        $result = "DELETE FROM $tblBal WHERE " . EBalance::A_ACCOUNT_ID . " IN ($select)"
            . " AND (" . EBalance::A_DATE . ">$quoted)";
        return $result;
    }
}


<?php declare(strict_types=1);

namespace Kuria\ClassLoader;

abstract class ComposerBridge
{
    /**
     * Add autoload configuration of packages managed by Composer
     *
     * - $vendorDirPath should be a path to the vendor directory without a trailing slash
     * - if $usePrefixes is FALSE, prefixes will not be loaded (use with optimized autoload files)
     */
    static function configure(ClassLoader $classLoader, string $vendorDirPath, bool $usePrefixes = true): void
    {
        $composerBasePath = $vendorDirPath . '/composer/';

        $classLoader->addClassMap(require $composerBasePath . 'autoload_classmap.php');
        $classLoader->setUsePrefixes($usePrefixes);

        if ($usePrefixes) {
            $classLoader->addPrefixes(require $composerBasePath . 'autoload_psr4.php');
            $classLoader->addPrefixes(require $composerBasePath . 'autoload_namespaces.php', ClassLoader::PSR0);
        }

        $autoloadedFilesPath =  $composerBasePath . 'autoload_files.php';

        if (is_file($autoloadedFilesPath)) {
            foreach (require $autoloadedFilesPath as $file) {
                require $file;
            }
        }
    }
}


<?php
/*
 * PSX is a open source PHP framework to develop RESTful APIs.
 * For the current version and informations visit <http://phpsx.org>
 *
 * Copyright 2010-2018 Christoph Kappestein <christoph.kappestein@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace PSX\Dependency;

use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use ReflectionClass;
use ReflectionException;

/**
 * A simple and fast PSR container implementation
 *
 * @author  Christoph Kappestein <christoph.kappestein@gmail.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @link    http://phpsx.org
 */
class Container implements ContainerInterface
{
    /**
     * @var array
     */
    protected $factories;

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

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

    public function __construct()
    {
        $this->factories  = [];
        $this->services   = [];
        $this->parameters = [];
    }

    /**
     * @param string $name
     * @param mixed $object
     */
    public function set($name, $object)
    {
        $name = self::normalizeName($name);

        if ($object instanceof \Closure) {
            $this->factories[$name] = $object;
        } else {
            $this->services[$name] = $object;
        }
    }

    /**
     * @param string $name
     * @return mixed
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function get($name)
    {
        $name = self::normalizeName($name);

        if (!isset($this->services[$name])) {
            if (isset($this->factories[$name])) {
                $this->services[$name] = call_user_func_array($this->factories[$name], [$this]);
            } elseif (method_exists($this, $method = 'get' . $name)) {
                $this->services[$name] = $this->$method();
            } else {
                throw new NotFoundException('Service ' . $name . ' not defined');
            }
        }

        return $this->services[$name];
    }

    /**
     * @param string $name
     * @return boolean
     */
    public function has($name)
    {
        $name = self::normalizeName($name);

        return isset($this->services[$name]) || isset($this->factories[$name]) || method_exists($this, 'get' . $name);
    }

    /**
     * @param string $name
     * @return boolean
     */
    public function initialized($name)
    {
        $name = self::normalizeName($name);

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

    /**
     * @param string $name
     * @param mixed $value
     */
    public function setParameter($name, $value)
    {
        $name = strtolower($name);

        $this->parameters[$name] = $value;
    }

    /**
     * @param string $name
     * @return mixed
     */
    public function getParameter($name)
    {
        $name = strtolower($name);

        if ($this->hasParameter($name)) {
            return $this->parameters[$name];
        } else {
            throw new InvalidArgumentException('Parameter ' . $name . ' not set');
        }
    }

    /**
     * @param string $name
     * @return boolean
     */
    public function hasParameter($name)
    {
        $name = strtolower($name);

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

    /**
     * Returns all available service ids of this container
     *
     * @return array
     * @throws \ReflectionException
     */
    public function getServiceIds()
    {
        $services  = [];
        $reserved  = ['get', 'getParameter', 'getServiceIds', 'getReturnType'];
        $container = new \ReflectionClass($this);

        foreach ($this->factories as $name => $factory) {
            $services[] = self::underscore($name);
        }

        foreach ($container->getMethods() as $method) {
            if (!in_array($method->name, $reserved) && preg_match('/^get(.+)$/', $method->name, $match)) {
                $services[] = self::underscore($match[1]);
            }
        }

        sort($services);

        return $services;
    }

    /**
     * Tries to determine the return type of a service. At first we try to
     * determine the type from the return annotation which is in most cases
     * more useful because it could specify an interface instead of an concrete
     * implementation. As fallback we get an instance of the service and return
     * the type
     *
     * @param string $name
     * @return string
     * @throws \ReflectionException
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getReturnType($name)
    {
        $container = new ReflectionClass($this);

        try {
            $method = $container->getMethod('get' . self::normalizeName($name));
            $doc    = $method->getDocComment();

            if (!empty($doc)) {
                preg_match('/@return ([a-zA-Z0-9_\x7f-\xff\x5c]+)/', $doc, $matches);

                if (isset($matches[1])) {
                    return $matches[1];
                }
            }
        } catch (ReflectionException $e) {
            // method does not exist
        }

        // as fallback we get the service and return the used type
        $service = $this->get($name);

        if (is_object($service)) {
            return get_class($service);
        } else {
            return gettype($service);
        }
    }

    /**
     * @param string $name
     * @return string
     */
    public static function normalizeName($name)
    {
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
    }

    /**
     * @param string $id
     * @return string
     */
    public static function underscore($id)
    {
        return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), strtr($id, '_', '.')));
    }
}


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

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

use Praxigento\Accounting\Repo\Data\Balance as EBalance;
use Praxigento\Accounting\Repo\Data\Transaction as ETrans;

/**
 * Collect transactions and compose daily balances updates.
 */
class CollectTransactions
{
    /**
     * @var \Praxigento\Core\Api\Helper\Period
     */
    private $hlpPeriod;

    public function __construct(
        \Praxigento\Core\Api\Helper\Period $hlpPeriod
    ) {
        $this->hlpPeriod = $hlpPeriod;
    }

    /**
     * Collect transactions and compose daily balances updates.
     *
     * @param array $balances [accId => balance]
     * @param ETrans[] $trans
     * @return array [accId => EBalance[]]
     * @throws \Exception
     */
    public function exec($balances, $trans)
    {
        $result = [];
        foreach ($trans as $one) {
            $accDebit = $one->getDebitAccId();
            $accCredit = $one->getCreditAccId();
            $timestamp = $one->getDateApplied();
            $value = $one->getValue();
            /* date_applied is in UTC format */
            $date = $this->hlpPeriod->getPeriodCurrent($timestamp);
            /**
             * Process debit account:
             */
            /** @var EBalance $entry Get balance on the transaction date (calculated or new) */
            $entry = $this->getBalanceEntry($balances, $result, $accDebit, $date);
            /* change total debit for the entry */
            $totalDebit = $entry->getTotalDebit() + $value;
            $entry->setTotalDebit($totalDebit);
            /* change close balance for the entry */
            $balanceClose = $entry->getBalanceClose() - $value;
            $entry->setBalanceClose($balanceClose);
            /* update calculated entries for result balances */
            $result[$accDebit][$date] = $entry;
            /* update current balances in the working var */
            if (isset($balances[$accDebit])) {
                $balances[$accDebit] -= $value;
            } else {
                $balances[$accDebit] = -$value;
            }
            /**
             * Process credit account:
             */
            /* get balance on the transaction date (calculated or new) */
            $entry = $this->getBalanceEntry($balances, $result, $accCredit, $date);
            /* change total credit for the entry */
            $totalCredit = $entry->getTotalCredit() + $value;
            $entry->setTotalCredit($totalCredit);
            /* change close balance for the entry */
            $balanceClose = $entry->getBalanceClose() + $value;
            $entry->setBalanceClose($balanceClose);
            /* update calculated entries for result balances */
            $result[$accCredit][$date] = $entry;
            /* update current balances in the working var */
            if (isset($balances[$accCredit])) {
                $balances[$accCredit] += $value;
            } else {
                $balances[$accCredit] = $value;
            }
        }
        return $result;
    }

    /**
     * Extract existing balance on the date or create new empty entity.
     *
     * @param array $current [accId => balance]
     * @param EBalance[] $balances
     * @param $accId
     * @param $datestamp
     * @return EBalance
     * @throws \Exception
     */
    private function getBalanceEntry($current, $balances, $accId, $datestamp)
    {
        if (isset($balances[$accId][$datestamp])) {
            /* there is data for this account on this date */
            $result = $balances[$accId][$datestamp];
        } else {
            /* there is NO data for this account on this date */
            $result = new EBalance();
            $result->setAccountId($accId);
            $result->setDate($datestamp);
            $result->setBalanceOpen(0);
            $result->setTotalDebit(0);
            $result->setTotalCredit(0);
            $result->setBalanceClose(0);
            if (isset($current[$accId])) {
                /* we need to update entry balances for newly created entry */
                $result->setBalanceOpen($current[$accId]);
                $result->setBalanceClose($current[$accId]);
            }
        }
        return $result;
    }

}


<?php

namespace Interpro\ImageAggr\Db;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Contracts\Taxonomy\Types\BType;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\Extractor\Contracts\Db\BMapper;
use Interpro\Extractor\Contracts\Selection\SelectionUnit;
use Interpro\Extractor\Contracts\Selection\Tuner;
use Interpro\ImageAggr\Collections\MapImageCollection;
use Interpro\ImageAggr\Creation\CapGenerator;
use Interpro\ImageAggr\Creation\ImageItemFactory;
use Interpro\Core\Helpers;

class ImageBMapper implements BMapper
{
    private $itemFactory;
    private $imageQuerier;
    private $tuner;
    private $capGenerator;
    private $units = [];

    public function __construct(ImageItemFactory $itemFactory, CapGenerator $capGenerator, ImageQuerier $imageQuerier, Tuner $tuner)
    {
        $this->itemFactory  = $itemFactory;
        $this->imageQuerier = $imageQuerier;
        $this->tuner        = $tuner;
        $this->capGenerator = $capGenerator;
    }

    /**
     * @return void
     */
    public function reset()
    {
        $this->units = [];
    }

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

    private function createImage(OwnField $imageField, array $item_array)
    {
        $imageItem = $this->itemFactory->createImage($imageField, $item_array);

        return $imageItem;
    }

    private function createCrop(BType $cropType, array $crop_arr)
    {
        $cropItem = $this->itemFactory->createCrop($cropType, $crop_arr);

        return $cropItem;
    }

    private function createResize(BType $resizeType, array $resize_arr)
    {
        $resizeItem = $this->itemFactory->createResize($resizeType, $resize_arr);

        return $resizeItem;
    }

    /**
     * @param AType $ownerType
     * @param $images_result
     * @param $resizes_result
     * @param $crops_result
     *
     * @return MapImageCollection
     */
    private function resultsToCollection(AType $ownerType, $images_result, $resizes_result, $crops_result)
    {
        $collection = new MapImageCollection($this->capGenerator);

        $gens = [];

        foreach($images_result as $item_array)
        {
            $field_name = $item_array['name'];

            if($ownerType->fieldExist($field_name))
            {
                $imageField = $ownerType->getField($field_name);

                $imageItem = $this->createImage($imageField, $item_array);

                $ref = new \Interpro\Core\Ref\ARef($ownerType, $item_array['entity_id']);

                $collection->addItem($ref, $field_name, $imageItem);

                $key = $item_array['name'].'_'.$item_array['entity_id'];
                $gens[$key] = ['resizes' => [], 'crops' => [], 'item' => $imageItem, 'name' => $item_array['name']];
            }
        }

        //-----------------------------------------------------------

        foreach($resizes_result as $resize_arr)
        {
            $key = $resize_arr['image_name'].'_'.$resize_arr['entity_id'];

            if(array_key_exists($key, $gens)) //Записи без соответствия картинке отметаем
            {
                $gens[$key]['resizes'][$resize_arr['name']] = $resize_arr;
            }
        }

        foreach($crops_result as $crop_arr)
        {
            $key = $crop_arr['image_name'].'_'.$crop_arr['entity_id'];

            if(array_key_exists($key, $gens)) //Записи без соответствия картинке отметаем
            {
                $gens[$key]['crops'][$crop_arr['name']] = $crop_arr;
            }
        }
        //-----------------------------------------------------------

        foreach($gens as $gen_arr)
        {
            $image_name = $gen_arr['name'];

            if($ownerType->fieldExist($image_name))
            {
                $imageField = $ownerType->getField($image_name);

                //Костыль, чтобы не заводить экземпляр таксономии в этот класс
                $imageType = $imageField->getFieldType();
                $subs = $imageType->getSubs('original');
                $resizeType = $subs->getSub('resize');
                $cropType = $subs->getSub('crop');
                //--------------------------------------

                $resizes = $gen_arr['resizes'];
                $crops = $gen_arr['crops'];
                $imageItem = $gen_arr['item'];

                foreach($resizes as $resize_arr)
                {
                    $resizeItem = $this->createResize($resizeType, $resize_arr);

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

                    $imageItem->addResize($resizeItem);
                }

                foreach($crops as $crop_arr)
                {
                    $cropItem = $this->createCrop($cropType, $crop_arr);

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

                    $imageItem->addCrop($cropItem);
                }
            }
        }

        return $collection;
    }

    /**
     * @param \Interpro\Core\Contracts\Ref\ARef $ref
     * @param bool $asUnitMember
     *
     * @return \Interpro\Extractor\Contracts\Collections\MapBCollection
     */
    public function getByRef(ARef $ref, $asUnitMember = false)
    {
        $ownerType = $ref->getType();
        $type_name = $ownerType->getName();
        $typeRank = $ownerType->getRank();

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

        if($typeRank === TypeRank::GROUP and $asUnitMember)
        {
            $selectionUnit = $this->tuner->getSelection($type_name, 'group');

            return $this->select($selectionUnit);
        }

        if(array_key_exists($key, $this->units))
        {
            return $this->units[$key];
        }

        $imagesQuery = $this->imageQuerier->selectImagesByRef($ref);
        $resizesQuery = $this->imageQuerier->selectResizesByRef($ref);
        $cropsQuery = $this->imageQuerier->selectCropsByRef($ref);

        $images_result = Helpers::laravel_db_result_to_array($imagesQuery->get());
        $resizes_result = Helpers::laravel_db_result_to_array($resizesQuery->get());
        $crops_result = Helpers::laravel_db_result_to_array($cropsQuery->get());

        $collection = $this->resultsToCollection($ownerType, $images_result, $resizes_result, $crops_result);

        $this->units[$key] = $collection;

        return $collection;
    }

    /**
     * @param \Interpro\Extractor\Contracts\Selection\SelectionUnit $selectionUnit
     *
     * @return \Interpro\Extractor\Contracts\Collections\MapBCollection
     */
    public function select(SelectionUnit $selectionUnit)
    {
        $ownerType = $selectionUnit->getType();

        $unit_number = $selectionUnit->getNumber();
        $key = 'unit_'.$unit_number;

        if(array_key_exists($key, $this->units))
        {
            return $this->units[$key];
        }

        //----------------------------------------------------------
        $imagesQuery = $this->imageQuerier->selectImagesByUnit($selectionUnit);
        $resizesQuery = $this->imageQuerier->selectResizesByUnit($selectionUnit);
        $cropsQuery = $this->imageQuerier->selectCropsByUnit($selectionUnit);

        $images_result = Helpers::laravel_db_result_to_array($imagesQuery->get());
        $resizes_result = Helpers::laravel_db_result_to_array($resizesQuery->get());
        $crops_result = Helpers::laravel_db_result_to_array($cropsQuery->get());

        $collection = $this->resultsToCollection($ownerType, $images_result, $resizes_result, $crops_result);

        $this->units[$key] = $collection;

        return $collection;
    }

}


<?php
namespace Able\Prototypes;

trait THierarchical {

	/**
	 * Retrieves hierarchical list of the class ancestors.
	 *
	 * @attention The called class name is included.
	 * @return array
	 */
	protected final static function hierarchy(){
		$Hierarchy = [get_called_class()];

		while(class_exists($class = get_parent_class($Hierarchy[count($Hierarchy) -1]))){
			array_push($Hierarchy, $class);
		}

		return $Hierarchy;
	}
}


<?php

namespace Onoi\Tesa\Tokenizer;

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

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

	/**
	 * @var integer
	 */
	private $ngramSize = 2;

	/**
	 * @var boolean
	 */
	private $withMarker = false;

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

	/**
	 * @since 0.1
	 *
	 * @param boolean $withMarker
	 */
	public function withMarker( $withMarker ) {
		$this->withMarker = (bool)$withMarker;
	}

	/**
	 * @since 0.1
	 *
	 * @param integer $ngramSize
	 */
	public function setNgramSize( $ngramSize ) {
		$this->ngramSize = (int)$ngramSize;
	}

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

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

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

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

		$result = $this->createNGrams( $string, $this->ngramSize, $this->withMarker );

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

		return array();
	}

	private function createNGrams( $text, $ngramSize, $withMarker ) {

		$ngramList = array();

		// Identify the beginning-of-word and end-of-word
		if ( $withMarker ) {
			$text = '_' . str_replace( ' ', '_', $text );
		}

		$text = mb_strtolower( $text );
		$textLength = mb_strlen( $text, 'UTF-8' );

		for ( $i = 0; $i < $textLength; ++$i ) {

			// Those failing the length of the ngramSize are skipped
			if ( !$withMarker && $i + $ngramSize > $textLength ) {
				continue;
			}

			$ngram = mb_substr( $text, $i, $ngramSize, 'UTF-8' );

			// str_pad has issues with utf-8 length
			if ( $withMarker && ( $ngl = mb_strlen( $ngram, 'UTF-8' ) ) < $ngramSize ) {
				$ngram = $ngram . str_repeat( '_', ( $ngramSize - $ngl ) );
			}

			$ngramList[] = $ngram;
		}

		return array_values( $ngramList );
	}

}


<?php

/**
 * A basic CURL wrapper for PHP
 *
 * @package EasyCurl
 *
 * @author LightAir
 */

namespace LightAir\EasyCurl;

class EasyCurl
{

    /**
     * Headers
     *
     * @var array
     */
    private $headers = [];

    /**
     * URI Request
     *
     * @var string
     */
    private $uri;

    /**
     * Proxy address
     *
     * @var string
     */
    private $proxy;

    /**
     * User Agent
     *
     * @var string
     */
    private $userAgent = 'Curl PHP';

    /**
     * Login for Basic Authorization
     *
     * @var string
     */
    private $login;

    /**
     * Password for Basic Authorization
     *
     * @var string
     */
    private $password;

    /**
     * Time Out
     *
     * @var int
     */
    private $timeOut = 10;

    private $curl;
    private $options;

    private $response;
    private $responseHeaders;
    private $rawResponseHeaders;

    private $error = false;

    private $curlError = false;
    private $curlErrorCode = 0;
    private $curlErrorMessage;

    private $httpError = false;
    private $httpErrorCode = 0;
    private $httpStatusCode = 0;
    private $httpErrorMessage;

    private $autoJSON = false;

    /**
     * Request constructor.
     *
     * @param string $uri
     */
    public function __construct($uri = null)
    {
        if (null !== $uri) {
            $this->uri = $uri;
            $this->curl = curl_init($uri);
        }
    }

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

    /**
     * @param $autoJSONDecode
     *
     * @return $this
     */
    public function setAutoJSON($autoJSON)
    {
        $this->autoJSON = $autoJSON;

        return $this;
    }

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

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

    /**
     * @return boolean
     */
    public function isError()
    {
        return $this->error;
    }

    /**
     * @return boolean
     */
    public function isCurlError()
    {
        return $this->curlError;
    }

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

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

    /**
     * @return boolean
     */
    public function isHttpError()
    {
        return $this->httpError;
    }

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

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

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

    /**
     * Setter proxy
     *
     * @param string $proxy
     *
     * @return $this
     */
    public function setProxy($proxy)
    {
        $this->proxy = $proxy;

        return $this;
    }

    /**
     * Setter User Agent
     *
     * @param $userAgent
     *
     * @return $this
     */
    public function setUserAgent($userAgent)
    {
        $this->userAgent = $userAgent;

        return $this;
    }

    /**
     * Login setter for Basic Authorization
     *
     * @param $login
     *
     * @return $this
     */
    public function setLogin($login)
    {
        $this->login = $login;

        return $this;
    }

    /**
     * Password setter for Basic Authorization
     *
     * @param $password
     *
     * @return $this
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Timeout setter
     *
     * @param int $timeOut
     *
     * @return $this
     */
    public function setTimeOut($timeOut)
    {
        $this->timeOut = $timeOut;

        return $this;
    }

    /**
     * Change header content type
     *
     * @param string $type
     *
     * @return $this
     */
    public function changeContentType($type)
    {

        $mime = [
            'json' => 'application/json',
            'javascript' => 'application/javascript',
            'js' => 'application/javascript',
            'ogg' => 'audio/ogg',
            'mpeg' => 'audio/mpeg',
            'html' => 'text/html',
            'plain' => 'text/plain',
            'urlencoded' => 'application/x-www-form-urlencoded'
        ];

        if (array_key_exists($type, $mime)) {
            $this->unsetHeader('Content-Type');
            $this->setHeader('Content-Type', $mime[$type]);
        }

        return $this;

    }

    /**
     * Unset header
     *
     * @param $headerName
     *
     * @return $this
     */
    public function unsetHeader($headerName)
    {
        $this->setHeader($headerName, '');
        unset($this->headers[$headerName]);

        return $this;
    }

    /**
     * Set header
     *
     * @param string $headerName
     * @param string $headerValue
     *
     * @return $this
     */
    public function setHeader($headerName, $headerValue)
    {
        $this->headers[$headerName] = $headerValue;

        $headers = [];

        foreach ($this->headers as $key => $value) {
            $headers[$key] = $value;
        }

        $callback = function ($aval, $akey) {
            return $akey . ': ' . $aval;
        };

        $finishedHeaders = array_map($callback, $headers, array_keys($headers));

        $this->setOpt(CURLOPT_HTTPHEADER, $finishedHeaders);

        return $this;
    }

    /**
     * Set Options
     *
     * @param  mixed $option
     * @param  mixed $value
     *
     * @return boolean
     */
    public function setOpt($option, $value)
    {
        $this->options[$option] = $value;
        return curl_setopt($this->curl, $option, $value);
    }

    /**
     * Performs query
     *
     * @param string $method
     * @param array $data
     * @param string $uri
     *
     * @return mixed
     */
    public function query($method = 'get', array $data = [], $uri = null)
    {

        if (null !== $uri) {
            $this->uri = $uri;

            if ($this->curl !== null) {
                curl_close($this->curl);
            }

            $this->curl = curl_init($uri);
        }

        $method = strtoupper($method);

        if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE'], true)) {
            $method = 'GET';
        }

        if (is_array($data) && empty($data)) {
            $this->unsetHeader('Content-Length');
        }

        $this->setOpt(CURLOPT_CUSTOMREQUEST, $method);

        if ($method === 'GET') {
            $this->setOpt(CURLOPT_HTTPGET, true);
            $this->setOpt(CURLOPT_URL, $this->uri . '?' . http_build_query($data));
            return $this->exec();
        }

        $this->setOpt(CURLOPT_POST, true);

        if ($this->isAutoJSON()) {
            $dataJson = json_encode($data);

            $this->setOpt(
                CURLOPT_HTTPHEADER,
                [
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($dataJson)
                ]);

            $this->setOpt(CURLOPT_POSTFIELDS, $dataJson);

            return $this->exec();
        }

        $this->setOpt(CURLOPT_POSTFIELDS, http_build_query($data));

        return $this->exec();
    }

    /**
     * Execution request
     *
     * @return mixed
     */
    private function exec()
    {
        $this->buildQuery();

        $this->response = curl_exec($this->curl);

        // curl
        $this->curlErrorCode = curl_errno($this->curl);
        $this->curlErrorMessage = curl_error($this->curl);
        $this->curlError = !($this->curlErrorCode === 0);

        // http
        $this->httpStatusCode = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
        $this->httpError = in_array(floor($this->httpStatusCode / 100), array(4, 5));
        $this->httpErrorCode = $this->httpError ? $this->httpStatusCode : 0;

        // base
        $this->error = $this->curlError || $this->httpError;

        if (!$this->curlError) {
            $this->responseHeaders = $this->headerParse($this->rawResponseHeaders);
        }

        if ($this->httpError) {
            $this->httpErrorMessage = $this->responseHeaders['Status-Line'];
        }

        if ($this->autoJSON && $this->isJSON($this->response)) {
            return json_decode($this->response, true);
        }

        return $this->response;
    }

    /**
     * @uses  headerCallback()
     *
     * Build query
     */
    public function buildQuery()
    {
        if ($this->proxy) {
            $this->setOpt(CURLOPT_PROXY, $this->proxy);
        }

        $this->setOpt(CURLOPT_RETURNTRANSFER, true);
        $this->setOpt(CURLOPT_USERAGENT, $this->userAgent);
        $this->setOpt(CURLOPT_CONNECTTIMEOUT, $this->timeOut);
        $this->setOpt(CURLINFO_HEADER_OUT, true);
        $this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'headerCallback'));

        if (null !== $this->login && null !== $this->password) {
            $this->setOpt(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            $this->setOpt(CURLOPT_USERPWD, $this->login . ':' . $this->password);
        }
    }

    /**
     * Parser for headers
     *
     * @param $rawHeader
     *
     * @return array
     */
    private function headerParse($rawHeader)
    {

        $headers = array();

        $headerLine = substr($rawHeader, 0, strpos($rawHeader, "\r\n\r\n"));

        foreach (explode("\r\n", $headerLine) as $i => $line) {
            if ($i === 0) {
                $headers['Status-Line'] = $line;
                continue;
            }

            list ($key, $value) = explode(': ', $line);
            $headers[$key] = $value;
        }

        return $headers;
    }

    /**
     * Performs get request
     *
     * @param array $data
     * @param string $uri
     *
     * @return mixed
     */

    public function get(array $data = [], $uri = null)
    {
        return $this->query('get', $data, $uri);
    }

    /**
     * Performs post request
     *
     * @param array $data
     * @param string $uri
     *
     * @return mixed
     */
    public function post(array $data = [], $uri = null)
    {
        return $this->query('post', $data, $uri);
    }

    /**
     * Performs put request
     *
     * @param array $data
     * @param string $uri
     *
     * @return mixed
     */

    public function put(array $data = [], $uri = null)
    {
        return $this->query('put', $data, $uri);
    }

    /**
     * Performs delete request
     *
     * @param array $data
     * @param string $uri
     *
     * @return mixed
     */

    public function delete(array $data = [], $uri = null)
    {
        return $this->query('delete', $data, $uri);
    }

    /**
     * Header Callback
     *
     * @param  $ch
     * @param  $header
     *
     * @return integer
     */
    private function headerCallback(/** @noinspection PhpUnusedParameterInspection */
        $ch, $header)
    {
        $this->rawResponseHeaders .= $header;
        return strlen($header);
    }

    /**
     * Check string is JSON
     *
     * @param $string
     *
     * @return bool
     */
    public function isJSON($string)
    {
        return
            is_array(json_decode($string, true)) &&
            is_string($string) &&
            (json_last_error() === JSON_ERROR_NONE);
    }
}


<?php

namespace Interpro\ImageAggr\Creation;

use Interpro\Core\Contracts\Taxonomy\Fields\OwnField;
use Interpro\Core\Contracts\Taxonomy\Types\BType;
use Interpro\Extractor\Contracts\Creation\CItemBuilder;
use Interpro\Extractor\Contracts\Creation\CollectionFactory;
use Interpro\ImageAggr\Fields\OriginalRefField;
use Interpro\ImageAggr\Fields\ResizeRefField;
use Interpro\ImageAggr\Collections\CropsCollection;
use Interpro\ImageAggr\Collections\ResizesCollection;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Fields\ImageOwnField;
use Interpro\ImageAggr\Items\CropItem;
use Interpro\ImageAggr\Items\ImageAggrItem;
use Interpro\ImageAggr\Items\ImageItem;
use Interpro\ImageAggr\Items\ResizeItem;

/**
 * Значения ссылок проставляются вне этой фабрики
 * Class ImageItemFactory
 * @package Interpro\ImageAggr\Creation
 */
class ImageItemFactory
{
    private $collectionFactory;
    private $cItemBuilder;
    private $capGenerator;
    private $defs;

    public function __construct(CollectionFactory $collectionFactory, CItemBuilder $cItemBuilder, CapGenerator $capGenerator)
    {
        $this->collectionFactory = $collectionFactory;
        $this->cItemBuilder = $cItemBuilder;
        $this->capGenerator = $capGenerator;

        $this->defs = [
            'integer' => 0,
            'string' => '',
            'boolean' => false
        ];
    }

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

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

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

        return $newField;
    }

    private function checkAndGetData(array $data, $name, $type_name)
    {
        if(!is_string($name))
        {
            throw new ImageAggrException('Имя поля должно быть задано строкой, передано: '.gettype($name).'!');
        }

        if(!array_key_exists($type_name, $this->defs))
        {
            throw new ImageAggrException('Собственные поля картинки могут быть типа '.implode(',', $this->defs).', передано '.$type_name.'!');
        }

        if(array_key_exists($name, $data))
        {
            $value = $data[$name];
        }
        else
        {
            $value = $this->defs[$type_name];
        }

        if($type_name === 'integer')
        {
            $value = (int) $value;
        }
        elseif($type_name === 'string')
        {
            $value = (string) $value;
        }
        elseif($type_name === 'boolean')
        {
            $value = (bool) $value;
        }
        elseif(gettype($value) !== $type_name)
        {
            throw new ImageAggrException('Значение не соответствует заявленному типу: '.$value.'('.$type_name.')!');
        }

        return $value;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\BType $type
     * @param array $data
     * @param bool $cap
     *
     * @return \Interpro\ImageAggr\Items\ResizeItem
     */
    public function createResize(BType $resizeType, array $data, $cap = false)
    {
        if($resizeType->getName() !== 'resize')
        {
            throw new ImageAggrException('Попытка создания ресайза с типом не равным resize ('.$resizeType->getName().')!');
        }

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

        $resizeItem = new ResizeItem($resizeType, $fields, $owns, $refs, $cap);

        $metaName       = $resizeType->getOwn('name');
        $metaLink       = $resizeType->getOwn('link');
        $metaAlt        = $resizeType->getOwn('alt');
        $metaCacheIndex = $resizeType->getOwn('cache_index');
        $metaWidth      = $resizeType->getOwn('width');
        $metaHeight     = $resizeType->getOwn('height');

        $metaOriginal   = $resizeType->getRef('original');

        //Собственные поля
        $fieldName       = $this->createLocalCField($resizeItem, $metaName,       $this->checkAndGetData($data, 'name', 'string'));
        $fieldLink       = $this->createLocalCField($resizeItem, $metaLink,       $this->checkAndGetData($data, 'link', 'string'));
        $fieldAlt        = $this->createLocalCField($resizeItem, $metaAlt,        $this->checkAndGetData($data, 'alt', 'string'));
        $fieldCacheIndex = $this->createLocalCField($resizeItem, $metaCacheIndex, $this->checkAndGetData($data, 'cache_index', 'integer'));
        $fieldWidth      = $this->createLocalCField($resizeItem, $metaWidth,      $this->checkAndGetData($data, 'width', 'integer'));
        $fieldHeight     = $this->createLocalCField($resizeItem, $metaHeight,     $this->checkAndGetData($data, 'height', 'integer'));

        //Ссылки
        $resizeItem->setOwn($fieldName);   $resizeItem->setField($fieldName);
        $resizeItem->setOwn($fieldLink);   $resizeItem->setField($fieldLink);
        $resizeItem->setOwn($fieldAlt);    $resizeItem->setField($fieldAlt);
        $resizeItem->setOwn($fieldCacheIndex); $resizeItem->setField($fieldCacheIndex);
        $resizeItem->setOwn($fieldWidth);  $resizeItem->setField($fieldWidth);
        $resizeItem->setOwn($fieldHeight); $resizeItem->setField($fieldHeight);

        //Ссылки
        $originalRef = new OriginalRefField($resizeItem, $metaOriginal);

        $resizeItem->setRef($originalRef); $resizeItem->setField($originalRef);

        return $resizeItem;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\BType $cropType
     * @param array $data
     * @param bool $cap
     *
     * @return \Interpro\ImageAggr\Items\CropItem
     */
    public function createCrop(BType $cropType, array $data, $cap = false)
    {
        if($cropType->getName() !== 'crop')
        {
            throw new ImageAggrException('Попытка создания кропа с типом не равным crop ('.$cropType->getName().')!');
        }

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

        $cropItem = new CropItem($cropType, $fields, $owns, $refs, $cap);

        $metaName       = $cropType->getOwn('name');
        $metaLink       = $cropType->getOwn('link');
        $metaAlt        = $cropType->getOwn('alt');
        $metaCacheIndex = $cropType->getOwn('cache_index');
        $metaWidth      = $cropType->getOwn('width');
        $metaHeight     = $cropType->getOwn('height');
        $metaX          = $cropType->getOwn('x');
        $metaY          = $cropType->getOwn('y');

        $metaOriginal   = $cropType->getRef('original');
        $metaMan        = $cropType->getRef('man');
        $metaTarget     = $cropType->getRef('target');

        $fieldName       = $this->createLocalCField($cropItem, $metaName,       $this->checkAndGetData($data, 'name', 'string'));
        $fieldLink       = $this->createLocalCField($cropItem, $metaLink,       $this->checkAndGetData($data, 'link', 'string'));
        $fieldAlt        = $this->createLocalCField($cropItem, $metaAlt,        $this->checkAndGetData($data, 'alt', 'string'));
        $fieldCacheIndex = $this->createLocalCField($cropItem, $metaCacheIndex, $this->checkAndGetData($data, 'cache_index', 'integer'));
        $fieldWidth      = $this->createLocalCField($cropItem, $metaWidth,      $this->checkAndGetData($data, 'width', 'integer'));
        $fieldHeight     = $this->createLocalCField($cropItem, $metaHeight,     $this->checkAndGetData($data, 'height', 'integer'));
        $fieldX          = $this->createLocalCField($cropItem, $metaX,          $this->checkAndGetData($data, 'x', 'integer'));
        $fieldY          = $this->createLocalCField($cropItem, $metaY,          $this->checkAndGetData($data, 'y', 'integer'));

        //Собственные поля
        $cropItem->setOwn($fieldName);  $cropItem->setField($fieldName);
        $cropItem->setOwn($fieldLink);  $cropItem->setField($fieldLink);
        $cropItem->setOwn($fieldAlt);   $cropItem->setField($fieldAlt);
        $cropItem->setOwn($fieldCacheIndex); $cropItem->setField($fieldCacheIndex);
        $cropItem->setOwn($fieldWidth);  $cropItem->setField($fieldWidth);
        $cropItem->setOwn($fieldHeight); $cropItem->setField($fieldHeight);
        $cropItem->setOwn($fieldX);      $cropItem->setField($fieldX);
        $cropItem->setOwn($fieldY);      $cropItem->setField($fieldY);

        //Ссылки
        $originalRef = new OriginalRefField($cropItem, $metaOriginal);
        $manRef      = new ResizeRefField($cropItem, $metaMan);
        $targetRef   = new ResizeRefField($cropItem, $metaTarget);

        $cropItem->setRef($originalRef); $cropItem->setField($originalRef);
        $cropItem->setRef($manRef);      $cropItem->setField($manRef);
        $cropItem->setRef($targetRef);   $cropItem->setField($targetRef);

        return $cropItem;
    }

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Fields\OwnField $field
     * @param array $data
     * @param bool $cap
     *
     * @return \Interpro\ImageAggr\Items\ImageItem
     */
    public function createImage(OwnField $field, array $data, $cap = false)
    {
        $imageType = $field->getFieldType();

        if($imageType->getName() !== 'image')
        {
            throw new ImageAggrException('Попытка картинки для поля не картинки ('.$imageType->getName().')!');
        }

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

        $resizes = new ResizesCollection($field, $this->capGenerator);
        $crops = new CropsCollection($field, $this->capGenerator);

        $imageItem = new ImageItem($field, $fields, $owns, $refs, $resizes, $crops, $cap);

        $resizes->setOriginal($imageItem);
        $crops->setOriginal($imageItem);

        $metaName       = $imageType->getOwn('name');
        $metaLink       = $imageType->getOwn('link');
        $metaAlt        = $imageType->getOwn('alt');
        $metaCacheIndex = $imageType->getOwn('cache_index');
        $metaWidth      = $imageType->getOwn('width');
        $metaHeight     = $imageType->getOwn('height');

        $fieldName       = $this->createLocalCField($imageItem, $metaName,       $this->checkAndGetData($data, 'name', 'string'));
        $fieldLink       = $this->createLocalCField($imageItem, $metaLink,       $this->checkAndGetData($data, 'link', 'string'));
        $fieldAlt        = $this->createLocalCField($imageItem, $metaAlt,        $this->checkAndGetData($data, 'alt', 'string'));
        $fieldCacheIndex = $this->createLocalCField($imageItem, $metaCacheIndex, $this->checkAndGetData($data, 'cache_index', 'integer'));
        $fieldWidth      = $this->createLocalCField($imageItem, $metaWidth,      $this->checkAndGetData($data, 'width', 'integer'));
        $fieldHeight     = $this->createLocalCField($imageItem, $metaHeight,     $this->checkAndGetData($data, 'height', 'integer'));

        //Собственные поля
        $imageItem->setOwn($fieldName);   $imageItem->setField($fieldName);
        $imageItem->setOwn($fieldLink);   $imageItem->setField($fieldLink);
        $imageItem->setOwn($fieldAlt);    $imageItem->setField($fieldAlt);
        $imageItem->setOwn($fieldCacheIndex); $imageItem->setField($fieldCacheIndex);
        $imageItem->setOwn($fieldWidth);  $imageItem->setField($fieldWidth);
        $imageItem->setOwn($fieldHeight); $imageItem->setField($fieldHeight);

        return $imageItem;
    }

}


<?php
/**
 * Copyright 2017 NanoSector
 *
 * You should have received a copy of the MIT license with the project.
 * See the LICENSE file for more information.
 */

namespace ValidationClosures;

class Ranges
{
	/**
	 * @param int $minimumLength
	 * @param int $maximumLength
	 *
	 * @return \Closure
	 */
	public static function stringWithLengthBetween(int $minimumLength, int $maximumLength): \Closure
	{
		if ($maximumLength < 0 || $maximumLength < 1)
			throw new \InvalidArgumentException('Minimum length cannot be below 0, maximum length cannot be below 1');

		return function ($value) use ($minimumLength, $maximumLength)
		{
			return Types::string()($value) && static::intBetween($minimumLength, $maximumLength)(strlen($value));
		};
	}

	/**
	 * @param int $minimum
	 * @param int $maximum
	 *
	 * @return \Closure
	 */
	public static function intBetween(int $minimum, int $maximum): \Closure
	{
        if ($maximum <= $minimum)
            throw new \InvalidArgumentException('Maximum can not be lesser than or equal to minimum.');

		return function ($value) use ($minimum, $maximum)
		{
			return Types::int()($value) && ($value >= $minimum && $value <= $maximum);
		};
	}

    /**
     * @param int $minimum
     * @param int $maximum
     *
     * @return \Closure
     */
    public static function intBetweenExclusive(int $minimum, int $maximum): \Closure
    {
        if ($maximum <= $minimum)
            throw new \InvalidArgumentException('Maximum can not be lesser than or equal to minimum.');

        return function ($value) use ($minimum, $maximum)
        {
            return Types::int()($value) && ($value > $minimum && $value < $maximum);
        };
	}

	/**
	 * @param float $minimum
	 * @param float $maximum
	 *
	 * @return \Closure
	 */
	public static function floatBetween(float $minimum, float $maximum): \Closure
	{
        if ($maximum <= $minimum)
            throw new \InvalidArgumentException('Maximum can not be lesser than or equal to minimum.');

		return function ($value) use ($minimum, $maximum)
		{
			return Types::float()($value) && ($value >= $minimum && $value <= $maximum);
		};
	}

    /**
     * @param float $minimum
     * @param float $maximum
     *
     * @return \Closure
     */
    public static function floatBetweenExclusive(float $minimum, float $maximum): \Closure
    {
        if ($maximum <= $minimum)
            throw new \InvalidArgumentException('Maximum can not be lesser than or equal to minimum.');

        return function ($value) use ($minimum, $maximum)
        {
            return Types::float()($value) && ($value > $minimum && $value < $maximum);
        };
	}

	/**
	 * @param array ...$allowedValues
	 *
	 * @return \Closure
	 */
	public static function enum(...$allowedValues): \Closure
	{
		return function ($value) use ($allowedValues)
		{
			return in_array($value, $allowedValues, true);
		};
	}

	/**
	 * @param array ...$allowedTypes
	 *
	 * @return \Closure
	 */
	public static function typeEnum(...$allowedTypes): \Closure
	{
		return function ($value) use ($allowedTypes)
		{
			return in_array(gettype($value), $allowedTypes, true);
		};
	}

	/**
	 * @param array ...$allowedValues
	 *
	 * @return \Closure
	 */
	public static function stringOneOf(...$allowedValues): \Closure
	{
		if (!Utils::validateArray(Types::string(), $allowedValues))
			throw new \InvalidArgumentException('Ranges::stringOneOf expects arguments of type string only');

		return function ($value) use ($allowedValues)
		{
			return Types::string() && in_array($value, $allowedValues);
		};
	}
}


<?php

namespace Nobox\LazyStrings;

class Str
{
    /**
     * Strip newlines and returns from string.
     *
     * @param string $string String to strip.
     *
     * @return string
     */
    public function strip($string)
    {
        return trim(preg_replace('/\s+/', ' ', $string));
    }

    /**
     * Convert dotted string to a nested array.
     * Append the value to the last nested array.
     *
     * @param string $string
     * @param string $value
     *
     * @return string|array
     */
    public function convertToArray($string, $value)
    {
        $keys = explode('.', $string);

        return $this->buildDimensionalArray($keys, count($keys), $value);
    }

    /**
     * Check if the string is separated by dots.
     *
     * @param string $string
     *
     * @return boolean
     */
    public function hasDots($string)
    {
        if (strpos($string, '.') === false) {
            return false;
        }

        return true;
    }

    /**
     * Builds nested array with the specified keys.
     *
     * @param array $keys
     * @param int $dimensions
     * @param string $value
     *
     * @return array
     */
    private function buildDimensionalArray(array $keys, $dimensions, $value)
    {
        $result = [];

        // add first dimension
        $result[$keys[0]] = [];
        $pointer = &$result[$keys[0]];

        for ($i = 1; $i < $dimensions; $i++) {
            if ($i === ($dimensions - 1)) {
                $pointer[$keys[$i]] = $value;
            } else {
                $pointer[$keys[$i]] = [];
                $pointer = &$pointer[$keys[$i]];
            }
        }

        return $result;
    }
}


<?php

namespace Onoi\Tesa\LanguageDetector;

use TextCat;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class TextCatLanguageDetector implements LanguageDetector {

	const VERION = '0.1';

	/**
	 * @var TextCat
	 */
	private $textCat;

	/**
	 * @var array|null
	 */
	private $languageCandidates = null;

	/**
	 * @since 0.1
	 *
	 * @param TextCat|null $textCat
	 */
	public function __construct( TextCat $textCat = null ) {
		$this->textCat = $textCat;

		if ( $this->textCat === null ) {
			$this->textCat = new TextCat();
		}
	}

	/**
	 * @since 0.1
	 *
	 * @param array $languageCandidates
	 */
	public function setLanguageCandidates( array $languageCandidates ) {
		$this->languageCandidates = $languageCandidates;
	}

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 *
	 * @return string|null
	 */
	public function detect( $text ) {

		$languages = $this->textCat->classify( $text, $this->languageCandidates );
		reset( $languages );

		// For now, only return the best match
		return key( $languages );
	}

}


<?php

namespace Interpro\ImageAggr\CommandAgents;

use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Core\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\ImageAggr\Contracts\CommandAgents\OperationsAgent as OperationsAgentInterface;
use Interpro\ImageAggr\Contracts\Operation\CleanOperation;
use Interpro\ImageAggr\Contracts\Operation\CleanPhOperation;
use Interpro\ImageAggr\Contracts\Operation\CropOperation;
use Interpro\ImageAggr\Contracts\Operation\RefreshOperation;
use Interpro\ImageAggr\Contracts\Operation\UploadOperation;
use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class OperationsAgent implements OperationsAgentInterface
{
    private $taxonomy;
    private $clean;
    private $cleanPh;
    private $refresh;
    private $crop;
    private $upload;
    private $imageSettingsSet;

    public function __construct(Taxonomy $taxonomy,
                                ImageSettingsSet $imageSettingsSet,
                                CleanOperation $clean,
                                CleanPhOperation $cleanPh,
                                RefreshOperation $refresh,
                                CropOperation $crop,
                                UploadOperation $upload)
    {
        $this->taxonomy = $taxonomy;

        $this->clean   = $clean;
        $this->cleanPh = $cleanPh;
        $this->refresh = $refresh;
        $this->crop    = $crop;
        $this->upload  = $upload;
        $this->imageSettingsSet = $imageSettingsSet;
    }

    private function ownerNameControl($owner_name)
    {
        if(!is_string($owner_name))
        {
            throw new ImageAggrException('Название типа хозяина) должно быть задано строкой!');
        }
    }

    private function ownerIdControl($owner_id)
    {
        if(!is_int($owner_id))
        {
            throw new ImageAggrException('Id типа хозяина должно быть задано целым числом!');
        }
    }

    private function imageNameControl($image_name)
    {
        if(!is_string($image_name))
        {
            throw new ImageAggrException('Имя поля картинки должно быть задано строкой!');
        }
    }

    private function cropNameControl($crop_name)
    {
        if(!is_string($crop_name))
        {
            throw new ImageAggrException('Имя кропа картинки должно быть задано строкой!');
        }
    }

    private function makeOwnerRef($owner_name, $owner_id)
    {
        $this->ownerNameControl($owner_name);
        $this->ownerIdControl($owner_id);

        $type = $this->taxonomy->getType($owner_name);

        $typeMode = $type->getMode();

        if($typeMode !== TypeMode::MODE_A)
        {
            throw new ImageAggrException('Агент удаления может удалять только тип (A) уровня, передан тип:'.$type->getName().'('.$typeMode.')!');
        }

        $ref = new ARef($type, $owner_id);

        return $ref;
    }

    private function makeImageField($owner_name, $image_name)
    {
        $this->ownerNameControl($owner_name);
        $this->imageNameControl($image_name);

        $type = $this->taxonomy->getType($owner_name);

        $imageField = $type->getOwn($image_name);

        if($imageField->getFieldTypeName() !== 'image')
        {
            throw new ImageAggrException('Тип поля хозяина '.$owner_name.' = '.$imageField->getName().' вместо ожидаемого image.');
        }

        return $imageField;
    }

    /**
     * @param string $owner_name
     * @param string $owner_id
     * @param string $image_name
     *
     * @return void
     */
    public function clean($owner_name, $owner_id, $image_name)
    {
        $aRef = $this->makeOwnerRef($owner_name, $owner_id);
        $imageField = $this->makeImageField($owner_name, $image_name);

        $imageSetting = $this->imageSettingsSet->getImage($imageField);

        $this->clean->execute($aRef, $imageSetting);
    }

    /**
     * @param string $owner_name
     * @param string $owner_id
     * @param string $image_name
     *
     * @return void
     */
    public function cleanToPh($owner_name, $owner_id, $image_name)
    {
        $aRef = $this->makeOwnerRef($owner_name, $owner_id);
        $imageField = $this->makeImageField($owner_name, $image_name);

        $imageSetting = $this->imageSettingsSet->getImage($imageField);

        $this->cleanPh->execute($aRef, $imageSetting);
    }

    /**
     * @param string $owner_name
     * @param string $owner_id
     * @param string $image_name
     *
     * @return void
     */
    public function refresh($owner_name, $owner_id, $image_name)
    {
        $aRef = $this->makeOwnerRef($owner_name, $owner_id);
        $imageField = $this->makeImageField($owner_name, $image_name);

        $imageSetting = $this->imageSettingsSet->getImage($imageField);

        $this->refresh->execute($aRef, $imageSetting);
    }

    /**
     * @param string $owner_name
     * @param string $owner_id
     * @param string $image_name
     * @param string $crop_name
     * @param array $attrs
     *
     * @return void
     */
    public function crop($owner_name, $owner_id, $image_name, $crop_name, array $attrs)
    {
        $aRef = $this->makeOwnerRef($owner_name, $owner_id);
        $imageField = $this->makeImageField($owner_name, $image_name);

        $imageSetting = $this->imageSettingsSet->getImage($imageField);
        $cropSetting = $imageSetting->getCrops()->getCrop($crop_name);

        $this->crop->execute($aRef, $imageSetting, $cropSetting);
    }

    /**
     * @param $owner_name
     * @param $owner_id
     * @param $image_name
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile
     *
     * @return void
     */
    public function upload($owner_name, $owner_id, $image_name, UploadedFile $uploadedFile)
    {
        $aRef = $this->makeOwnerRef($owner_name, $owner_id);
        $imageField = $this->makeImageField($owner_name, $image_name);

        $imageSetting = $this->imageSettingsSet->getImage($imageField);

        $this->upload->execute($aRef, $imageSetting, $uploadedFile);
    }

}


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

namespace Praxigento\Accounting\Service\Account\Balance;

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

/**
 * Re-calculate daily balances.
 */
class Calc
    implements \Praxigento\Accounting\Api\Service\Account\Balance\Calc
{
    private const DEF_DAYS_TO_RESET = 2;

    /** @var \Praxigento\Accounting\Repo\Dao\Type\Asset */
    private $daoTypeAsset;
    /** @var \Praxigento\Core\Api\Helper\Date */
    private $hlpDate;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Psr\Log\LoggerInterface */
    private $logger;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneAccount */
    private $ownProcessOneAcc;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneType */
    private $ownProcessOneType;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Accounting\Repo\Dao\Type\Asset $daoTypeAsset,
        \Praxigento\Core\Api\Helper\Date $hlpDate,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneAccount $ownProcessOneAcc,
        \Praxigento\Accounting\Service\Account\Balance\Calc\A\ProcessOneType $ownProcessOneType
    ) {
        $this->logger = $logger;
        $this->daoTypeAsset = $daoTypeAsset;
        $this->hlpDate = $hlpDate;
        $this->hlpPeriod = $hlpPeriod;
        $this->ownProcessOneAcc = $ownProcessOneAcc;
        $this->ownProcessOneType = $ownProcessOneType;
    }

    public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();
        /** define local working data */
        $accountsIds = $request->getAccountsIds();
        $assetTypeCodes = $request->getAssetTypeCodes();
        $assetTypeIds = $request->getAssetTypeIds();
        $dateResetFrom = $request->getDateResetFrom();
        $daysToReset = (int)$request->getDaysToReset();

        /** validate pre-processing conditions */
        $dsBalanceClose = $this->getDateBalanceClose($dateResetFrom, $daysToReset);

        /** perform processing */
        if (
            is_array($accountsIds) &&
            (count($accountsIds) > 0)
        ) {
            $total = count($accountsIds);
            $this->logger->info("Total $total accounts will be re-calculated from '$dsBalanceClose' (excl.).");
            foreach ($accountsIds as $one) {
                $accId = (int)$one;
                $this->logger->info("Re-calc balances for account #$accId.");
                $this->ownProcessOneAcc->exec($accId, $dsBalanceClose);
            }
        } else {
            $assets = $this->getAssetTypes($assetTypeIds, $assetTypeCodes);
            $total = count($assets);
            $this->logger->info("Total $total asset types will be re-calculated from '$dsBalanceClose'.");
            foreach ($assets as $typeId => $typeCode) {
                $this->logger->info("Re-calc balances for asset $typeCode/$typeId.");
                $this->ownProcessOneType->exec($typeId, $dsBalanceClose);
            }
        }

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

    /**
     * Validate given asset type or get all types.
     *
     * @param int[] $typeIds
     * @param string[] $typeCodes
     * @return array [id => code]
     */
    private function getAssetTypes($typeIds, $typeCodes)
    {
        $result = [];
        $types = $this->daoTypeAsset->get();
        if (
            empty($typeIds) &&
            empty($typeCodes)
        ) {
            /* return all asset types */
            /** @var ETypeAsset $type */
            foreach ($types as $type) {
                $typeId = $type->getId();
                $typeCode = $type->getCode();
                $result[$typeId] = $typeCode;
            }
        } else {
            /* validate ID for given type ID or convert type code to type ID */
            /** @var ETypeAsset $type */
            foreach ($types as $type) {
                $typeId = $type->getId();
                $typeCode = $type->getCode();
                if (
                    (is_array($typeIds) && in_array($typeId, $typeIds)) ||
                    (is_array($typeCodes) && in_array($typeCode, $typeCodes))
                ) {
                    $result[$typeId] = $typeCode;
                }
            }
        }
        return $result;
    }

    /**
     * Calculate datestamp for the last day of balances to leave w/o reset.
     *
     * @param string $daysToReset
     * @param int $daysToReset
     * @return string YYYYMMDD
     */
    private function getDateBalanceClose($dateResetFrom, $daysToReset)
    {
        if (!empty($dateResetFrom)) {
            $applied = $this->hlpPeriod->getPeriodCurrent($dateResetFrom);
            $result = $this->hlpPeriod->getPeriodPrev($applied);
        } else {
            $days = abs((int)$daysToReset);
            if ($days < 0) {
                $days = self::DEF_DAYS_TO_RESET;
            }
            $dtNow = $this->hlpDate->getUtcNow();
            $dtMod = $dtNow->modify("-$days days");
            $result = $this->hlpPeriod->getPeriodCurrent($dtMod);
        }
        return $result;
    }

}


<?php

namespace Interpro\ImageAggr\Executors;

use Illuminate\Support\Facades\DB;
use Interpro\Core\Contracts\Executor\ASynchronizer as ASynchronizerInterface;
use Interpro\Core\Contracts\Mediator\SyncMediator;
use Interpro\Core\Contracts\Taxonomy\Types\AType;
use Interpro\Core\Ref\ARef;
use Interpro\Core\Taxonomy\Enum\TypeMode;
use Interpro\ImageAggr\Exception\ImageAggrException;

class ModImagesSynchronizer implements ASynchronizerInterface
{
    private $syncMediator;

    public function __construct(SyncMediator $syncMediator)
    {
        $this->syncMediator = $syncMediator;
    }

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

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\AType $type
     *
     * @return void
     */
    public function sync(AType $type)
    {
        $name = $type->getName();
        $mode = $type->getMode();

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

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

        $synchronizer = $this->syncMediator->getOwnSynchronizer('imageaggr');

        $aRef = new ARef($type, 0);

        $images = $type->getOwns('image');

        foreach($images as $image)
        {
            $synchronizer->sync($aRef, $image);
        }

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


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

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

use Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Request as ARequestLastDate;
use Praxigento\Accounting\Api\Service\Account\Balance\LastDate\Response as AResponseLastDate;
use Praxigento\Accounting\Config as Cfg;
use Praxigento\Accounting\Repo\Data\Account as EAccount;
use Praxigento\Accounting\Repo\Query\Balance\OnDate\Closing\ByAsset as QBalanceOnDate;
use Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset\A\Data\Trans as DTrans;
use Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset\A\Repo\Query\GetTransactions as QGetTrans;

class ProcessOneAsset
{
    /** @var \Praxigento\Accounting\Repo\Dao\Account */
    private $daoAcc;
    /** @var \Praxigento\Accounting\Repo\Dao\Transaction */
    private $daoTrans;
    /** @var \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Psr\Log\LoggerInterface */
    private $logger;
    /** @var \Praxigento\Accounting\Repo\Query\Balance\OnDate\Closing\ByAsset */
    private $qBalanceOnDate;
    /** @var \Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset\A\Repo\Query\GetTransactions */
    private $qGetTrans;
    /** @var \Praxigento\Accounting\Api\Service\Account\Balance\LastDate */
    private $servLastDate;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Accounting\Repo\Dao\Account $daoAcc,
        \Praxigento\Accounting\Repo\Dao\Transaction $daoTrans,
        \Praxigento\Accounting\Repo\Query\Balance\OnDate\Closing\ByAsset $qBalanceOnDate,
        \Praxigento\Accounting\Service\Account\Balance\Validate\A\ProcessOneAsset\A\Repo\Query\GetTransactions $qGetTrans,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\Accounting\Api\Service\Account\Balance\LastDate $servLastDate
    ) {
        $this->logger = $logger;
        $this->daoAcc = $daoAcc;
        $this->daoTrans = $daoTrans;
        $this->qBalanceOnDate = $qBalanceOnDate;
        $this->qGetTrans = $qGetTrans;
        $this->hlpPeriod = $hlpPeriod;
        $this->servLastDate = $servLastDate;
    }

    /**
     * Validate balances for one asset type.
     *
     * @param int $assetTypeId
     * @throws \Exception
     */
    public function exec($assetTypeId)
    {
        /* get the last date with balances for given asset then take previous date */
        $dsLast = $this->getDateBalanceClose($assetTypeId);
        $dsPrev = $this->hlpPeriod->getPeriodPrev($dsLast);
        /* get all closing balances for previous date */
        $balances = $this->getBalances($assetTypeId, $dsPrev);
        /* get all accounts with given asset type */
        $accounts = $this->getAccounts($assetTypeId);
        /* get all transactions starting from "balance close -1 day" for given asset */
        $trans = $this->getTransactions($assetTypeId, $dsPrev);
        /* then validate current balances */
        $this->validate($accounts, $balances, $trans);
    }

    /**
     * Get current balances for account with given asset ($typeId).
     *
     * @param int $typeId
     * @return array [$accountId => $balance]
     */
    private function getAccounts($typeId)
    {
        $result = [];
        $where = EAccount::A_ASSET_TYPE_ID . '=' . (int)$typeId;
        $rows = $this->daoAcc->get($where);
        /** @var EAccount $row */
        foreach ($rows as $row) {
            $accId = $row->getId();
            $balance = $row->getBalance();
            $result[$accId] = $balance;
        }
        return $result;
    }

    /**
     * Get closing balances on given date ($ds) for given asset ($typeId).
     *
     * @param int $typeId
     * @param string $ds
     * @return array [$accountId => $balance]
     */
    private function getBalances($typeId, $ds)
    {
        $result = [];
        $query = $this->qBalanceOnDate->build();
        $conn = $query->getConnection();
        $bind = [
            QBalanceOnDate::BND_ASSET_TYPE_ID => $typeId,
            QBalanceOnDate::BND_MAX_DATE => $ds
        ];
        $rows = $conn->fetchAll($query, $bind);
        foreach ($rows as $row) {
            $accId = $row[QBalanceOnDate::A_ACC_ID];
            $balance = $row[QBalanceOnDate::A_BALANCE];
            $result[$accId] = $balance;
        }
        return $result;
    }

    /**
     * Get datestamp for the last day of available balances.
     *
     * @param int $typeId asset type
     * @return string YYYYMMDD
     * @throws \Exception
     */
    private function getDateBalanceClose($typeId)
    {
        $req = new ARequestLastDate();
        $req->setAssetTypeId($typeId);
        /** @var AResponseLastDate $resp */
        $resp = $this->servLastDate->exec($req);
        $result = $resp->getLastDate();
        return $result;
    }

    /**
     * @param int $typeId
     * @param string $ds 'YYYYMMDD'
     * @return DTrans[]
     */
    private function getTransactions($typeId, $ds)
    {
        $result = [];
        $dateFrom = $this->hlpPeriod->getTimestampNextFrom($ds);
        $query = $this->qGetTrans->build();
        $conn = $query->getConnection();
        $bind = [
            QGetTrans::BND_ASSET_TYPE_ID => $typeId,
            QGetTrans::BND_DATE_FROM => $dateFrom
        ];
        $rows = $conn->fetchAll($query, $bind);
        foreach ($rows as $row) {
            $item = new DTrans();
            $item->accIdDebit = $row[QGetTrans::A_ACC_ID_DEBIT];
            $item->accIdCredit = $row[QGetTrans::A_ACC_ID_CREDIT];
            $item->amount = $row[QGetTrans::A_AMOUNT];
            $result[] = $item;
        }
        return $result;
    }

    /**
     * @param array $accounts
     * @param array $balances
     * @param DTrans[] $trans
     */
    private function validate($accounts, $balances, $trans)
    {
        /* compose current balances based on $balances & $transactions */
        foreach ($trans as $one) {
            $accIdDebit = $one->accIdDebit;
            $accIdCredit = $one->accIdCredit;
            $amount = $one->amount;
            if (isset($balances[$accIdDebit])) {
                $balances[$accIdDebit] -= $amount;
            } else {
                $balances[$accIdDebit] = (-1) * $amount;
            }
            if (isset($balances[$accIdCredit])) {
                $balances[$accIdCredit] += $amount;
            } else {
                $balances[$accIdCredit] = $amount;
            }
        }
        /* total sum of all balances should be equal to zero.*/
        $sum = 0;
        foreach ($accounts as $accId => $balanceAct) {
            /* accounts with zero balances are not presented in balance array */
            if (abs($balanceAct) < Cfg::DEF_ZERO)
                continue;
            $sum += $balanceAct;
            $balanceExp = $balances[$accId];
            if (abs($balanceAct - $balanceExp) > Cfg::DEF_ZERO) {
                $this->logger->error("Account balance validation error: acc. #$accId, actual: $balanceAct, expected: $balanceExp.");
            }
        }
        if (abs($sum) > Cfg::DEF_ZERO) {
            $this->logger->error("Total summary for accounts balances is not equal to 0 (actual: $sum).");
        }
    }
}


<?php

namespace DCS\OpauthBundle\Controller;

use DCS\OpauthBundle\DCSOpauthEvents;
use DCS\OpauthBundle\Event\OpauthEvent;
use DCS\OpauthBundle\Event\OpauthResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

class ResponseController extends Controller
{
    /**
     * Parse the response of the provider
     */
    public function checkAction($strategy)
    {
        $config = $this->get('dcs_opauth.strategy_parser')->get($strategy);
        $opauth = new \Opauth($config, false);

        $this->dispatchEvent(DCSOpauthEvents::BEFORE_PARSE_RESPONSE, new OpauthEvent($opauth));

        $responseData = $this->get('dcs_opauth.response_parser')->parse($opauth);

        // Check if there are errors from the provider
        $isValid = !isset($responseData['error']);

        $event = new OpauthResponseEvent($opauth, $responseData, $isValid);
        $this->dispatchEvent(DCSOpauthEvents::AFTER_PARSE_RESPONSE, $event);

        // If there are no errors, and authentication is enabled, create the token with the data provider
        if ($isValid && $event->getAuthenticate()) {
            $this->get('dcs_opauth.authenticator')->authenticate($responseData);
        }

        // Verify if the response is set
        if (null === $response = $event->getResponse()) {
            if ($isValid) {
                if (null === $routeRedirect = $this->container->getParameter('dcs_opauth.redirect_after_response')) {
                    $url = '/'.ltrim($this->get('request')->getBaseUrl(), '/');
                } else {
                    // Check if route exists
                    try {
                        $url = $this->generateUrl($routeRedirect);
                    } catch (RouteNotFoundException $e) {
                        $url = $routeRedirect;
                    }
                }
                // Create default response
                $response = new RedirectResponse($url);
            } else {
                $response = $this->render($this->container->getParameter('dcs_opauth.error_view'), $responseData['error']);
            }
        }

        return $response;
    }

    /**
     * Dispatch event
     *
     * @param $eventName
     * @param $event
     */
    private function dispatchEvent($eventName, $event)
    {
        $this->get('event_dispatcher')->dispatch($eventName, $event);
    }
}


<?php
namespace Able\Prototypes;

use \Able\Helpers\Src;
use \Able\Helpers\Str;

trait TMutatable {

	/**
	 * Checks if mutator exists and returns the mutated value.
	 *
	 * @param string $prefix
	 * Any prefix like 'get' or 'set' to separate getters and setters for example.
	 *
	 * @param string $name
	 * It will be converted into the camel case
	 * via underscores like a separator.
	 *
	 * @param $value
	 * Some parameters if needed.
	 *
	 * @return mixed
	 * The value will be returned "as is" if the requested mutator doesn't exist.
	 */
	protected final function mutate(string $prefix, string $name, $value = null) {
		return method_exists($this, $method = Src::tcm(strtolower(Str::join('_', $prefix, $name , 'property'))))
			? call_user_func([$this, $method], $value) : $value;
	}
}