<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\BlockManager;

use RedKiteCms\Bridge\Dispatcher\Dispatcher;
use RedKiteCms\Bridge\Monolog\DataLogger;
use RedKiteCms\EventSystem\BlockEvents;
use RedKiteCms\EventSystem\Event\Block\BlockMovedAnotherSlotEvent;
use RedKiteCms\EventSystem\Event\Block\BlockMovedSameSlotEvent;
use RedKiteCms\EventSystem\Event\Block\BlockMovingAnotherSlotEvent;
use RedKiteCms\EventSystem\Event\Block\BlockMovingSameSlotEvent;
use RedKiteCms\Tools\FilesystemTools;
use RedKiteCms\Tools\JsonTools;
use Symfony\Component\Finder\Finder;

/**
 * Class BlockManagerMove is the object assigned to move a block both on the same slot or to another one
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\BlockManager
 */
class BlockManagerMove extends BlockManager
{
    /**
     * Moves the block
     *
     * @param string $sourceDir
     * @param array $options
     * @param string $username
     *
     * @return string The saved content
     */
    public function move($baseDir, array $options, $username)
    {
        $this->resolveMoveOptions($options);
        if (array_key_exists("targetSlot", $options)) {
            $options["slot"] = $options["targetSlot"];
            $block = $this->moveBlockToAnotherSlot($baseDir, $options, $username);

            return $block;
        }

        $options["slot"] = $options["sourceSlot"];
        $block = $this->moveBlockToSameSlot($baseDir, $options, $username);

        return $block;
    }

    /**
     * Defines the options required by the move method
     *
     * @param array $options
     */
    protected function resolveMoveOptions(array $options)
    {
        if ($this->optionsResolved) {
            // @codeCoverageIgnoreStart
            return;
            // @codeCoverageIgnoreEnd
        }

        $this->optionsResolver->clear();
        $this->optionsResolver->setRequired(
            array(
                'page',
                'language',
                'country',
                'sourceSlot',
                'position',
            )
        );

        $this->optionsResolver->setDefined(
            array(
                'targetSlot',
                'blockname',
                'oldName',
                'newName',
                'slot',
            )
        );

        $this->optionsResolver->resolve($options);
        $this->optionsResolved = true;
    }

    /**
     * Moves the block's archive dir to the new slot and adapts it according with the new block name
     *
     * @param string $archiveSourceFile
     * @param string $archiveTargetFile
     * @param string $blockName
     * @param string $slotName
     */
    private function moveArchiveDir($archiveSourceFile, $archiveTargetFile, $blockName, $slotName)
    {
        if (!is_dir($archiveSourceFile)) {
            return;
        }

        $this->filesystem->mirror($archiveSourceFile, $archiveTargetFile);
        $this->filesystem->remove($archiveSourceFile);

        $historyChanged = array();
        $historyFile = $archiveTargetFile . '/history.json';
        $history = json_decode(file_get_contents($historyFile), true);
        foreach($history as $key => $values) {
            $values["name"] = $blockName;
            $values["slot_name"] = $slotName;
            $historyChanged[$key] = $values;
        }
        file_put_contents($historyFile, json_encode($historyChanged));
    }

    /**
     * Changes the block and slot name when moving to another slot
     *
     * @param string $targetFile
     * @param string $blockName
     * @param string $slotName
     *
     * @return array The new block
     */
    private function changeBlockSlotAndName($targetFile, $blockName, $slotName)
    {
        $block = json_decode(FilesystemTools::readFile($targetFile), true);
        $block["name"] = $blockName;
        $block["slot_name"] = $slotName;
        $json = json_encode($block);
        FilesystemTools::writeFile($targetFile, $json);

        return $block;
    }

    private function moveBlockToAnotherSlot($baseDir, array $options, $username)
    {
        $sourceSlot = $options["sourceSlot"];
        $targetSlot = $options["targetSlot"];
        unset($options["sourceSlot"]);
        unset($options["targetSlot"]);

        $slotDirOptions = $options;
        $newName = $slotDirOptions["newName"];
        $slotDirOptions["blockname"] = $slotDirOptions["oldName"];
        unset($slotDirOptions["oldName"]);
        unset($slotDirOptions["newName"]);
        unset($slotDirOptions["position"]);
        $sourceDir = $this->fetchSlotDir($sourceSlot, $slotDirOptions, $baseDir, $username);
        $slotDirOptions["blockname"] = $newName;
        $targetDir = $this->fetchSlotDir($targetSlot, $slotDirOptions, $baseDir, $username);
        if (!is_dir($targetDir)) {
            $this->createContributorDir($baseDir, $options, $username);
        }

        Dispatcher::dispatch(
            BlockEvents::BLOCK_MOVING_ANOTHER_SLOT,
            new BlockMovingAnotherSlotEvent($this->serializer, $sourceSlot, $targetSlot)
        );

        $sourceFile = sprintf('%s/blocks/%s.json', $sourceDir, $options["oldName"]);
        $encodedBlock = $this->addSourceBlockToTargetSlot($sourceFile, $targetDir, $options);

        $archiveSourceFile = $sourceDir . '/archive/' . $options["oldName"];
        $archiveTargetFile = $targetDir . '/archive/' . $options["newName"];
        $this->moveArchiveDir($archiveSourceFile, $archiveTargetFile, $options["newName"], $options["slot"]);

        $options["blockname"] = $options["oldName"];
        $this->removeBlockFromSlotFile($options, $sourceDir);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_MOVED_ANOTHER_SLOT,
            new BlockMovedAnotherSlotEvent($this->serializer, $sourceSlot, $targetSlot)
        );
        DataLogger::log(
            sprintf(
                'Block "%s" has been moved from the "%s" slot to the "%s" slot, on page "%s" for the "%s_%s" language. It has been renamed as "%s"',
                $options["oldName"],
                $sourceSlot,
                $targetSlot,
                $options["page"],
                $options["language"],
                $options["country"],
                $options["newName"]
            )
        );

        return $encodedBlock;
    }

    private function fetchSlotDir($slot, $options, $baseDir, $username)
    {
        $options["slot"] = $slot;

        return $this
            ->init($baseDir, $options, $username)
            ->getDirInUse()
        ;
    }

    private function addSourceBlockToTargetSlot($sourceFile, $targetDir, $options)
    {
        $targetBlockName = $options["blockname"] = $options["newName"];
        $this->addBlockToSlot($targetDir, $options);
        $targetFile = sprintf('%s/blocks/%s.json', $targetDir, $targetBlockName);

        $this->filesystem->copy($sourceFile, $targetFile, true);
        $this->filesystem->remove($sourceFile);

        $this->changeBlockSlotAndName($targetFile, $targetBlockName, $options["slot"]);
        $encodedBlock = FilesystemTools::readFile($targetFile);

        return $encodedBlock;
    }

    private function moveBlockToSameSlot($baseDir, array $options, $username)
    {
        $sourceDir = $this
            ->init($baseDir, $options, $username)
            ->getDirInUse();

        $slotsFilename = sprintf('%s/slot.json', $sourceDir);
        $slot = JsonTools::jsonDecode(FilesystemTools::readFile($slotsFilename), true);
        $blocks = $slot["blocks"];
        $key = array_search($options["blockname"], $blocks);
        $blockName = $blocks[$key];
        unset($blocks[$key]);
        array_splice($blocks, $options["position"], 0, $blockName);
        $slot["blocks"] = $blocks;
        $encodedSlot = json_encode($slot);

        $targetFile = sprintf('%s/blocks/%s.json', $sourceDir, $options["blockname"]);
        $event = Dispatcher::dispatch(
            BlockEvents::BLOCK_MOVING_SAME_SLOT,
            new BlockMovingSameSlotEvent($this->serializer, $blocks, $options["position"], $targetFile, $encodedSlot)
        );
        $slotContent = $event->getFileContent();

        FilesystemTools::writeFile($slotsFilename, $slotContent);
        $block = FilesystemTools::readFile($targetFile);

        Dispatcher::dispatch(
            BlockEvents::BLOCK_MOVED_SAME_SLOT,
            new BlockMovedSameSlotEvent($this->serializer, $blocks, $options["position"], $targetFile, $encodedSlot)
        );
        DataLogger::log(
            sprintf(
                'Block "%s" has been moved to position "%s" on the slot "%s" on "%s" page for "%s_%s" language',
                $options["blockname"],
                $options["position"],
                $options["slot"],
                $options["page"],
                $options["language"],
                $options["country"]
            )
        );

        return $block;
    }
}


<?php

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

namespace ItePHP\Component\Form;

use ItePHP\Validator\NumberValidator;

/**
 * FormBuilder field
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class NumberField extends InputField{

    /**
     * {@inheritdoc}
     */
	public function __construct($options){
		$options['type']='number';

		if(!isset($options['validator'])){
			$this->setValidator(new NumberValidator());
		}

		if(isset($options['min'])){
			$this->setMin($options['min']);
			unset($options['min']);
		}

		if(isset($options['max'])){
			$this->setMax($options['max']);
			unset($options['max']);
		}

		parent::__construct($options);
	}

	/**
	 * Set html tag min
	 *
	 * @param int $value - value of tag min
	 */
	public function setMin($value){
		$this->setTag('min',$value);
		if($this->getValidator()){
			$this->getValidator()->setOption('min',$value);
		}
	}

	/**
	 * Get html tag min
	 *
	 * @return int - value of tag min
	 */
	public function getMin(){
		return $this->getTag('min');
	}

	/**
	 * Set html tag max
	 *
	 * @param int $value - value of tag max
	 */
	public function setMax($value){
		$this->setTag('max',$value);
		if($this->getValidator()){
			$this->getValidator()->setOption('max',$value);
		}
	}

	/**
	 * Get html tag max
	 *
	 * @return int - value of tag max
	 */
	public function getMax(){
		return $this->getTag('max');
	}

}


<?php
namespace app\manage\controller;

use think\App;
use think\Request;

class Loader
{

    /**
     * 调用module
     *
     * @param Request $request
     * @return mixed
     */
    public function run(Request $request)
    {

        // 模块变量
        define('_MODULE_', $request->param('_module_'));
        define('_CONTROLLER_', $request->param('_controller_'));
        define('_ACTION_', $request->param('_action_'));

        // 后台的view_path
        $manage_view_path = APP_PATH . 'manage/view/';
        define('MANAGE_VIEW_PATH', $manage_view_path);

        // 模块的view_path
        $module_view_path = APP_PATH . 'module/' . _MODULE_ . '/view/';
        define('MODULE_VIEW_PATH', $module_view_path);

        // 执行操作
        $class = 'module\\' . _MODULE_ . '\\controller\\' . ucfirst(_CONTROLLER_);
        return App::invokeMethod([
            $class,
            _ACTION_
        ]);
    }
}


<?php namespace Neonbug\User\Providers;

use App;
use Route;
use View;
use Config;
use Event;
use \Illuminate\Routing\Router as Router;

class ServiceProvider extends \Neonbug\Common\Providers\BaseServiceProvider {

	const PACKAGE_NAME     = 'user';
	const PREFIX           = 'user';
	const ROLE             = 'user';
	const TABLE_NAME       = 'user';
	const CONTROLLER       = '\Neonbug\User\Controllers\Controller';
	const ADMIN_CONTROLLER = '\Neonbug\User\Controllers\AdminController';

	/**
	 * Define your route model bindings, pattern filters, etc.
	 *
	 * @param    \Illuminate\Routing\Router  $router
	 * @return  void
	 */
	public function boot(Router $router)
	{
		//============
		//== ASSETS ==
		//============
		$this->loadViewsFrom(__DIR__.'/../resources/views', static::PACKAGE_NAME);
		$this->publishes([
			__DIR__.'/../resources/views' => base_path('resources/views/vendor/' . static::PACKAGE_NAME),
		]);

		$this->loadViewsFrom(__DIR__.'/../resources/admin_views', static::PACKAGE_NAME . '_admin');
		$this->publishesAdmin([
			__DIR__.'/../resources/admin_views' => base_path('resources/views/vendor/' . static::PACKAGE_NAME . '_admin'),
		]);

		$this->loadTranslationsFrom('/', static::PACKAGE_NAME);

		$this->publishes([
			__DIR__.'/../database/migrations/' => database_path('/migrations')
		], 'migrations');

		$this->publishes([
			__DIR__.'/../config/' . static::PACKAGE_NAME . '.php' => config_path('neonbug/' . static::PACKAGE_NAME . '.php'),
		]);

		//============
		//== ROUTES ==
		//============
		$language = App::make('Language');
		$locale = ($language == null ? Config::get('app.default_locale') : $language->locale);

		$admin_language = App::make('AdminLanguage');
		$admin_locale = ($admin_language == null ? Config::get('app.admin_default_locale') : $admin_language->locale);

		$resource_repo = App::make('ResourceRepository');

		//frontend
		$router->group([ 'middleware' => [ 'online' ], 'prefix' => $locale . '/' .
			trans(static::PACKAGE_NAME . '::frontend.route.prefix') ],
			function($router) use ($locale, $resource_repo, $language)
		{
			$router->get('/',             [ 'as' => static::PREFIX . '::index',   'uses' => static::CONTROLLER . '@index' ]);
			$router->get('index',         [                                       'uses' => static::CONTROLLER . '@index' ]);
			$router->get('item/{id}',     [ 'as' => static::PREFIX . '::item',    'uses' => static::CONTROLLER . '@item' ]);
			$router->get('preview/{key}', [ 'as' => static::PREFIX . '::preview', 'uses' => static::CONTROLLER . '@preview' ]);

			if ($language != null)
			{
				$slugs = $resource_repo->getSlugs($language->id_language, static::TABLE_NAME);
				foreach ($slugs as $slug)
				{
					// skip empty slugs
					if ($slug->value == '') continue;

					$router->get($slug->value, [ 'as' => static::PREFIX . '::slug::' . $slug->value,
						function() use ($slug) {
						$controller = App::make(static::CONTROLLER);
						return $controller->callAction('item', [ 'id' => $slug->id_row ]);
					} ]);
				}
			}
		});

		//admin
		$router->group([ 'prefix' => $admin_locale . '/admin/' . static::PREFIX,
			'middleware' => [ 'auth.admin', 'admin.menu' ], 'role' => static::ROLE,
			'menu.icon' => 'user', 'weight' => 7 ], function($router)
		{
			$router->get('list', [
				'as'   => static::PREFIX . '::admin::list',
				'uses' => static::ADMIN_CONTROLLER . '@adminList'
			]);

			$router->get('add', [
				'as'   => static::PREFIX . '::admin::add',
				'uses' => static::ADMIN_CONTROLLER . '@adminAdd'
			]);
			$router->post('add', [
				'as'   => static::PREFIX . '::admin::add-save',
				'uses' => static::ADMIN_CONTROLLER . '@adminAddPost'
			]);

			$router->get('edit/{id}', [
				'as'   => static::PREFIX . '::admin::edit',
				'uses' => static::ADMIN_CONTROLLER . '@adminEdit'
			]);
			$router->post('edit/{id}', [
				'as'   => static::PREFIX . '::admin::edit-save',
				'uses' => static::ADMIN_CONTROLLER . '@adminEditPost'
			]);
		});

		$router->group([ 'prefix' => $admin_locale . '/admin/' . static::PREFIX, 'middleware' => [ 'auth.admin' ],
			'role' => static::ROLE ], function($router)
		{
			$router->post('delete', [
				'as'   => static::PREFIX . '::admin::delete',
				'uses' => static::ADMIN_CONTROLLER . '@adminDeletePost'
			]);

			$router->post('check-slug', [
				'as'   => static::PREFIX . '::admin::check-slug',
				'uses' => static::ADMIN_CONTROLLER . '@adminCheckSlugPost'
			]);
		});

		//============
		//== EVENTS ==
		//============
		Event::subscribe('\\Neonbug\\User\\Handlers\\Events\\RoleEventHandler');

		parent::boot($router);
	}

	/**
	 * Register any application services.
	 *
	 * This service provider is a great spot to register your various container
	 * bindings with the application. As you can see, we are registering our
	 * "Registrar" implementation here. You can add your own bindings too!
	 *
	 * @return  void
	 */
	public function register()
	{
		//===========
		//== BINDS ==
		//===========
		if (!App::bound('\Neonbug\User\Repositories\UserRepository'))
		{
			App::singleton('\Neonbug\User\Repositories\UserRepository', '\Neonbug\User\Repositories\UserRepository');
		}
	}

}


<?php
namespace app\manage\controller;

use think\Url;
use think\Request;
use core\manage\logic\DatabaseLogic;

class DataBase extends Base
{

    /**
     * 数据表
     *
     * @return string
     */
    public function index()
    {
        $this->site_title = '备份数据';

        // 数据表
        $list = DatabaseLogic::instance()->getTableList();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 备份表
     *
     * @return mixed
     */
    public function bakup()
    {
        $res = DatabaseLogic::instance()->addBakup($this->user_id);
        if ($res['code'] == 1) {
            return $this->success($res['msg'], Url::build('database/bakupLog'));
        } else {
            return $this->error($res['msg']);
        }
    }

    /**
     * 优化表
     *
     * @return mixed
     */
    public function optimize()
    {
        DatabaseLogic::instance()->optimize();

        return $this->success('优化表成功', Url::build('database/index'));
    }

    /**
     * 修复表
     *
     * @return mixed
     */
    public function repair()
    {
        DatabaseLogic::instance()->repair();

        return $this->success('修复表成功', Url::build('database/index'));
    }

    /**
     * 备份记录
     *
     * @return string
     */
    public function bakupLog()
    {
        $this->site_title = '备份记录';

        // 备份记录
        $list = DatabaseLogic::instance()->getList();
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     * 删除记录
     */
    public function delBakup(Request $request)
    {
        $bakup_id = $request->param('bakup_id');
        if (empty($bakup_id)) {
            return $this->error('备份ID为空');
        }

        // 删除备份
        DatabaseLogic::instance()->delBakup($bakup_id);

        return $this->success('删除备份记录成功', Url::build('database/bakupLog'));
    }
}


<?php
namespace app\manage\controller;

use think\Config;
use think\Request;
use think\Session;
use cms\Controller;
use app\manage\logic\AuthLogic;
use app\manage\logic\LoginLogic;
use core\manage\logic\MenuLogic;

class Base extends Controller
{

    /**
     * 用户ID
     *
     * @var unknown
     */
    protected $user_id;

    /**
     * 每页条数
     *
     * @var unknown
     */
    protected $rows_num;

    /**
     * (non-PHPdoc)
     *
     * @see \app\common\controller\Root::_initialize()
     */
    protected function _initialize()
    {
        Session::boot();
        $public_action = Config::get('manage_public_action');
        if (! AuthLogic::isPublicAction($public_action)) {

            // 验证登录
            $this->verifyLogin();

            // 验证权限
            $this->verifyAuth();

            // 创建菜单
            Request::instance()->isAjax() || $this->buildMenu();

            // 每页条数
            $this->rows_num = Config::get('manage_rows_num') ?  : 12;
        }
    }

    /**
     * !CodeTemplates.overridecomment.nonjd!
     *
     * @see \app\common\controller\Root::fetch()
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        $view_path = dirname(dirname(__DIR__)) . '/' . Request::instance()->module() . '/view/' . Config::get('manage_theme') . '/';
        $this->view->config('view_path', $view_path);
        return parent::fetch($template, $vars, $replace, $config);
    }

    /**
     * 验证登录
     */
    protected function verifyLogin()
    {
        $user = LoginLogic::getLoginUser();
        if (empty($user)) {
            responseRedirect('start/login');
        } else {
            // 用户ID
            $this->user_id = $user['user_id'];

            // 用户信息
            if (! Request::instance()->isAjax()) {
                $manage_user = LoginLogic::gteLoginUserInfo();
                $this->assign('manage_user', $manage_user);

                // 管理首页
                $this->assign('manage_url', $user['manage_url']);
            }
        }
    }

    /**
     * 验证权限
     */
    protected function verifyAuth()
    {
        if (! AuthLogic::isAuthAction($this->user_id)) {
            $content = $this->error('你没有权限访问该页面');
            responseReturn($content, 'text');
        }
    }

    /**
     * 创建菜单
     */
    protected function buildMenu()
    {
        $menu_logic = MenuLogic::instance();

        // 主菜单
        $main_menu = $menu_logic->getMainMenu($this->user_id);
        $this->assign('main_menu', $main_menu);

        // 侧边菜单
        $sider_menu = $menu_logic->getSiderMenu($this->user_id);
        $this->assign('sider_menu', $sider_menu);
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Monitor;

use Predis\ClientInterface;
use Predis\Connection\AggregateConnectionInterface;
use Predis\NotSupportedException;

/**
 * Redis MONITOR consumer.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Consumer implements \Iterator
{
    private $client;
    private $valid;
    private $position;

    /**
     * @param ClientInterface $client Client instance used by the consumer.
     */
    public function __construct(ClientInterface $client)
    {
        $this->assertClient($client);

        $this->client = $client;

        $this->start();
    }

    /**
     * Automatically stops the consumer when the garbage collector kicks in.
     */
    public function __destruct()
    {
        $this->stop();
    }

    /**
     * Checks if the passed client instance satisfies the required conditions
     * needed to initialize a monitor consumer.
     *
     * @param ClientInterface $client Client instance used by the consumer.
     *
     * @throws NotSupportedException
     */
    private function assertClient(ClientInterface $client)
    {
        if ($client->getConnection() instanceof AggregateConnectionInterface) {
            throw new NotSupportedException(
                'Cannot initialize a monitor consumer over aggregate connections.'
            );
        }

        if ($client->getCommandFactory()->supportsCommand('MONITOR') === false) {
            throw new NotSupportedException("'MONITOR' is not supported by the current command factory.");
        }
    }

    /**
     * Initializes the consumer and sends the MONITOR command to the server.
     */
    protected function start()
    {
        $this->client->executeCommand(
            $this->client->createCommand('MONITOR')
        );
        $this->valid = true;
    }

    /**
     * Stops the consumer. Internally this is done by disconnecting from server
     * since there is no way to terminate the stream initialized by MONITOR.
     */
    public function stop()
    {
        $this->client->disconnect();
        $this->valid = false;
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        // NOOP
    }

    /**
     * Returns the last message payload retrieved from the server.
     *
     * @return object
     */
    public function current()
    {
        return $this->getValue();
    }

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

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        ++$this->position;
    }

    /**
     * Checks if the the consumer is still in a valid state to continue.
     *
     * @return bool
     */
    public function valid()
    {
        return $this->valid;
    }

    /**
     * Waits for a new message from the server generated by MONITOR and returns
     * it when available.
     *
     * @return object
     */
    private function getValue()
    {
        $database = 0;
        $client = null;
        $event = $this->client->getConnection()->read();

        $callback = function ($matches) use (&$database, &$client) {
            if (2 === $count = count($matches)) {
                // Redis <= 2.4
                $database = (int) $matches[1];
            }

            if (4 === $count) {
                // Redis >= 2.6
                $database = (int) $matches[2];
                $client = $matches[3];
            }

            return ' ';
        };

        $event = preg_replace_callback('/ \(db (\d+)\) | \[(\d+) (.*?)\] /', $callback, $event, 1);
        @list($timestamp, $command, $arguments) = explode(' ', $event, 3);

        return (object) array(
            'timestamp' => (float) $timestamp,
            'database' => $database,
            'client' => $client,
            'command' => substr($command, 1, -1),
            'arguments' => $arguments,
        );
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Bridge\Form;

use RedKiteCms\Configuration\ConfigurationHandler;
use RedKiteCms\Content\PageCollection\PagesCollectionParser;

/**
 * The object assigned to handle the Symfony form factory
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Form
 */
class FormFactory
{
    /**
     * @type ConfigurationHandler
     */
    private $configurationHandler;
    /**
     * @type \Symfony\Component\Form\FormFactory
     */
    private $formFactory;
    /**
     * @type PagesCollectionParser
     */
    private $pagesParser;

    /**
     * Constructor
     *
     * @param ConfigurationHandler $configurationHandler
     * @param \Symfony\Component\Form\FormFactory $formFactory
     * @param PagesCollectionParser $pagesParser
     */
    public function __construct(
        ConfigurationHandler $configurationHandler,
        \Symfony\Component\Form\FormFactory $formFactory,
        PagesCollectionParser $pagesParser
    ) {
        $this->configurationHandler = $configurationHandler;
        $this->formFactory = $formFactory;
        $this->pagesParser = $pagesParser;
    }

    /**
     * Creates the form
     *
     * @param string $className
     * @param string $username
     * @return \Symfony\Component\Form\FormView
     */
    public function create($className, $username)
    {
        $reflectionClass = new \ReflectionClass($className);

        $permalinks = $this->pagesParser
            ->contributor($username)
            ->parse()
            ->permalinksByLanguage(
                $this->configurationHandler->language() . '_' . $this->configurationHandler->country()
            );
        $permalinksForSelect = (!empty($permalinks)) ? array_combine($permalinks, $permalinks) : array();
        $params = array($permalinksForSelect);

        $form = $this->formFactory->create($reflectionClass->newInstanceArgs($params));

        return $form->createView();
    }
}


<?php
namespace AuthModule;

use AuthModule\Adapter\ModelAdapter;
use AuthModule\Identity\IdentityObjectInterface;
use AuthModule\Identity\ObjectInterface;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\AuthenticationService as BaseAuthService;
use Zend\Authentication\Result;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;
use Zend\EventManager\EventManagerInterface;

/**
 * Class AuthenticationService
 */
class AuthenticationService extends BaseAuthService implements EventManagerAwareInterface, IdentityObjectInterface
{
    use EventManagerAwareTrait;

    /**
     * @var ObjectInterface
     */
    protected $identityObject;

    /**
     * @var AuthenticationEvent
     */
    protected $event;

    /**
     * @return AuthenticationEvent
     */
    public function getEvent()
    {
        if (!$this->event) {
            $this->event = new AuthenticationEvent();
            $this->event->setTarget($this);
        }
        return $this->event;
    }

    protected function attachDefaultListener()
    {
        $events = $this->getEventManager();
        $events->attach(AuthenticationEvent::EVENT_AUTH, [$this, 'dispatchAuthentication']);
    }

    /**
     * @param AuthenticationEvent $e
     */
    public function dispatchAuthentication(AuthenticationEvent $e)
    {
        $e->setResult(parent::authenticate($e->getAdapter()));
    }

    /**
     * Set the event manager instance used by this context
     *
     * @param  EventManagerInterface $events
     * @return $this
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $identifiers = [__CLASS__, get_class($this)];
        if (isset($this->eventIdentifier)) {
            if ((is_string($this->eventIdentifier))
                || (is_array($this->eventIdentifier))
                || ($this->eventIdentifier instanceof \Traversable)
            ) {
                $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier));
            } elseif (is_object($this->eventIdentifier)) {
                $identifiers[] = $this->eventIdentifier;
            }
            // silently ignore invalid eventIdentifier types
        }
        $events->setIdentifiers($identifiers);
        $this->events = $events;
        $this->attachDefaultListener();
        return $this;
    }

    /**
     * @return ObjectInterface|null
     * @throws Exception\RuntimeException
     */
    public function getIdentityObject()
    {
        if ($this->hasIdentity()) {
            if (!$this->identityObject) {
                /** @var $modelAdapter ModelAdapter */
                $modelAdapter = $this->getAdapter();
                if ($modelAdapter) {
                    $this->identityObject = $modelAdapter->getIdentityObjectByIdentity($this->getIdentity());
                } else {
                    throw new Exception\RuntimeException('An adapter must be set or passed prior to calling getIdentityObject()');
                }
            }
            return $this->identityObject;
        }
        return null;
    }

    /**
     * @return ObjectInterface|null
     * @throws Exception\RuntimeException
     */
    public function reloadIdentityObject()
    {
        $this->identityObject = null;
        return $this->getIdentityObject();
    }

    /**
     * Authenticates against the supplied adapter
     *
     * @param  AdapterInterface $adapter
     * @return Result
     */
    public function authenticate(AdapterInterface $adapter = null)
    {
        $event = clone $this->getEvent();
        $event->setName(AuthenticationEvent::EVENT_AUTH);

        if (!$adapter) {
            $adapter = $this->getAdapter();
        }

        if ($adapter) {
            $event->setAdapter($adapter);
        }

        $this->getEventManager()->trigger($event);

        return $event->getResult();
    }
}


<?php
namespace Poirot\Queue\Queue;

use Poirot\Queue\Exception\exIOError;
use Poirot\Queue\Interfaces\iPayloadQueued;
use Poirot\Queue\Interfaces\iQueueDriver;
use Poirot\Std\Type\StdArray;

/**
 * Used To Implement Cron Likes Tasks
 * that run each n time cycle
 *
 */
class SteadyQueue
    extends InMemoryQueue
    implements iQueueDriver
{
    protected $queues    = [];
    protected $_defaults = [];

    /**
     * SteadyQueue constructor.
     *
     * @param array|null $defaultQueues
     */
    function __construct(array $defaultQueues = null)
    {
        if ($defaultQueues !== null)
            $this->setDefaultQueues($defaultQueues);

    }

    /**
     * Pop From Queue
     *
     * note: when you pop a message from queue you have to
     *       release it when worker done with it.
     *
     *
     * @param string $queue
     *
     * @return iPayloadQueued|null
     * @throws exIOError
     */
    function pop($queue = null)
    {
        if ( null === $j = parent::pop($queue) && !empty($this->queues) )
            // Set Default Once The Queue Is Empty
            $this->setDefaultQueues($this->_defaults);

        else return $j;

        // Try To Pop Again; With defaults queue values ...
        return parent::pop($queue);
    }

    // Options:

    /**
     * Set Default Jobs In Queue
     *
     * @param array $defaultQueues
     *
     * @return $this
     */
    function setDefaultQueues(array $defaultQueues)
    {
        $this->_defaults = $defaultQueues;

        $queues = StdArray::of($this->queues)->withMergeRecursive($defaultQueues, true);
        $this->queues = $queues->value;

        return $this;
    }

    // ..

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

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


<?php namespace Versatile\Introspection;

use UnexpectedValueException;
use Symfony\Component\Translation\TranslatorInterface as Translator;
use Illuminate\Database\Eloquent\Model;
use Versatile\Introspection\Contracts\TypeIntrospector;
use Versatile\Introspection\Contracts\PathIntrospector;
use Versatile\Query\Contracts\SyntaxParser;
use XType\AbstractType;
use XType\TemporalType;

class EloquentTypeIntrospector implements TypeIntrospector
{

    protected $pathIntrospector;

    protected $parser;

    protected $manualKeyTypes = [];

    protected $defaultDateFormat = 'Y-m-d H:i:s';

    public function __construct(PathIntrospector $introspector,
                                SyntaxParser $parser){
        $this->pathIntrospector = $introspector;
        $this->parser = $parser;
    }

    /**
     * {@inheritdoc}
     *
     * @param string|object $class The class or an object of it
     * @param string $path A key name. Can be dotted like address.street.name
     * @return \Xtype\AbstractType
     **/
    public function keyType($class, $path)
    {

        // Allows manual overwrites if titles
        if ($type = $this->getManualKeyType($this->getClassName($class),$path)) {
            return $type;
        }

        try{

            // First check if path is a related key (account.owner.id)
            if ($this->parser->isRelatedKey($path)) {

                list($join, $key) = $this->parser->toJoinAndKey($path);
                $className = $this->pathIntrospector->classOfPath($class, $join);

            } else { // No related key

                $className = $this->getClassName($class);
                $key = $path;

            }

            if ($type = $this->getManualKeyType($className, $key)) {
                return $type;
            }

            if ($this->isDate($className, $key)) {
                $type = new TemporalType();
                $type->setFormat($this->defaultDateFormat);
                return $type;
            }

        }
        catch(UnexpectedValueException $e){
            return;
        }

    }

    protected function getClassName($class){
        if(is_object($class)){
            return get_class($class);
        }
        else{
            return $class;
        }
    }

    public function setDefaultDateFormat($format)
    {
        $this->defaultDateFormat = $format;
        return $this;
    }

    /**
     * @param object|string $class
     * @param string $column
     * @return \Xtype\AbstractType
     **/
    public function getManualKeyType($class, $column){

        $class = ltrim($this->getClassName($class),'\\');
        if(isset($this->manualKeyTypes[$class.'|'.$column])){
            return $this->manualKeyTypes[$class.'|'.$column];
        }
    }

    public function setKeyType($class, $column, AbstractType $type){

        $class = ltrim($this->getClassName($class),'\\');
        $this->manualKeyTypes[$class.'|'.$column] = $type;
        return $this;

    }

    protected function isDate($class, $key)
    {
        $model = new $class;
        return in_array($key, $model->getDates());
    }

}


<?php
namespace app\manage\logic;

use cms\Auth;
use core\manage\logic\MenuLogic;
use core\manage\logic\MemberLogic;

class AuthLogic extends Auth
{

    /**
     * 是否授权操作
     *
     * @param number $user_id
     * @return boolean
     */
    public static function isAuthAction($user_id)
    {
        $user_logic = MemberLogic::instance();

        // 超级管理员
        if ($user_logic->isAdmin($user_id)) {
            return true;
        }

        // 菜单不存在
        $current_menu = MenuLogic::instance()->getMenuByFlag();
        if (empty($current_menu)) {
            return false;
        }

        // 授权菜单
        $auth_menu = $user_logic->getUserMenu($user_id);
        return in_array($current_menu['id'], $auth_menu);
    }
}


<?php
/**
 * Behavior for make ActiveRecord model taggable
 *
 * @link https://github.com/inblank/yii2-taggable
 * @copyright Copyright (c) 2016 Pavel Aleksandrov <inblank@yandex.ru>
 * @license http://opensource.org/licenses/MIT
 */

namespace inblank\taggable;

use yii\base\Behavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\db\Query;

/**
 * Behavior for make ActiveRecord model taggable
 *
 * @property ActiveRecord $owner
 *
 * @author Pavel Aleksandrov <inblank@yandex.ru>
 */
class TaggableBehavior extends Behavior
{
    /**
     * @var string[] list of tags
     */
    protected $_tagsList;

    /**
     * @var bool sign that owner has attribute `tags`
     */
    protected $_hasTagAttribute;

    /**
     * @var int[] store tag ids for delete when owner deleting
     */
    private $_tagsForDelete;

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
            ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
        ];
    }

    /**
     * Add tags
     * @param string|string[] $tags list of tags added to the current. If specified as a string, the tags must be separated by commas
     */
    public function addTags($tags)
    {
        $this->_tagsList = array_unique(array_merge($this->getTagValues(), $this->parseTags($tags)));
        $this->updateOwnerTags();
    }

    /**
     * Get tags list
     * @param bool $asString sign get a list of tags as string
     * @return string[]|string
     */
    public function getTagValues($asString = false)
    {
        if ($this->_tagsList === null && !$this->owner->getIsNewRecord()) {
            // the list of tags is not initialized
            $this->_tagsList = [];
            // trying to obtain related models
            $relation = $this->owner->getRelation('tagsList', false);
            if ($relation instanceof ActiveQuery) {
                $this->_tagsList = array_unique($relation->select('text')->column());
            }
        }
        return $asString === true ? implode(',', $this->_tagsList) : $this->_tagsList;
    }

    /**
     * Parse tags list into array
     * @param string|string[] $tags list of tags. If specified as a string, the tags must be separated by commas
     * @return string[]
     */
    protected function parseTags($tags)
    {
        return array_unique(is_array($tags) ? array_filter($tags) : preg_split('/\s*,\s*/', $tags, -1, PREG_SPLIT_NO_EMPTY));
    }

    /**
     * Update the attribute `tags` of the owner
     */
    public function updateOwnerTags()
    {
        if ($this->ownerHasTagAttribute()) {
            $this->owner->setAttribute('tags', $this->getTagValues(true));
        }
    }

    /**
     * check that the owner has the attribute `tags`
     * @return bool
     */
    protected function ownerHasTagAttribute()
    {
        if ($this->_hasTagAttribute === null) {
            $this->_hasTagAttribute = $this->owner->hasAttribute('tags');
        }
        return $this->_hasTagAttribute;
    }

    /**
     * Set tags. All old tags will be replaced with new
     * @param string|string[] $tags a new list of tags. If specified as a string, the tags must be separated by commas
     */
    public function setTagValues($tags)
    {
        $this->_tagsList = $this->parseTags($tags);
        $this->updateOwnerTags();
    }

    /**
     * Remove all values from tags list
     */
    public function removeAllTagValues()
    {
        $this->_tagsList = [];
        $this->updateOwnerTags();
    }

    /**
     * Returns a value indicating whether tags exists
     * @param string|string[] $tags
     * @return boolean
     */
    public function hasTags($tags)
    {
        return empty(array_diff($this->parseTags($tags), $this->getTagValues()));
    }

    /**
     * Removes the specified tags from the list
     * @param string|string[] $tags the list of removed tags. If specified as a string, the tags must be separated by commas
     */
    public function removeTagValues($tags)
    {
        $this->_tagsList = array_diff($this->getTagValues(), $this->parseTags($tags));
        $this->updateOwnerTags();
    }

    /**
     * After owner save action
     */
    public function afterSave()
    {
        if ($this->_tagsList === null) {
            return;
        }
        $relation = $this->owner->getRelation('tagsList', false);
        if (!($relation instanceof ActiveQuery)) {
            return;
        }
        if (!$this->owner->getIsNewRecord()) {
            // clear old tags
            $this->beforeDelete();
            $this->afterDelete();
        }
        /** @var ActiveRecord $relationClass */
        $relationClass = $relation->modelClass;
        $ownerTagsList = [];
        foreach ($this->_tagsList as $tagText) {
            /* @var ActiveRecord $tag */
            $tag = $relationClass::findOne(['text' => $tagText]);
            if ($tag === null) {
                $tag = new $relationClass();
                $tag->setAttribute('text', $tagText);
            }
            $tag->setAttribute('count', $tag->getAttribute('count') + 1);
            if ($tag->save()) {
                $ownerTagsList[] = [$this->owner->getPrimaryKey(), $tag->getPrimaryKey()];
            }
        }
        if (!empty($ownerTagsList)) {
            $this->owner->getDb()
                ->createCommand()
                ->batchInsert($relation->via->from[0], [key($relation->via->link), current($relation->link)], $ownerTagsList)
                ->execute();
        }
    }

    /**
     * Before delete event
     */
    public function beforeDelete()
    {
        // store tag ids list
        $this->_tagsForDelete = [];
        $relation = $this->owner->getRelation('tagsList', false);
        if ($relation instanceof ActiveQuery) {
            $this->_tagsForDelete = (new Query())
                ->select(current($relation->link))
                ->from($relation->via->from[0])
                ->where([key($relation->via->link) => $this->owner->getPrimaryKey()])
                ->column($this->owner->getDb());
        }
    }

    /**
     * After delete event
     */
    public function afterDelete()
    {
        // after complete owner delete delete tags links
        if (!empty($this->_tagsForDelete)) {
            $relation = $this->owner->getRelation('tagsList', false);
            if ($relation instanceof ActiveQuery) {
                /** @var ActiveRecord $class */
                $class = $relation->modelClass;
                // decrease counters
                $class::updateAllCounters(['count' => -1], ['in', $class::primaryKey(), $this->_tagsForDelete]);
                // delete links
                $this->owner->getDb()
                    ->createCommand()
                    ->delete($relation->via->from[0], [key($relation->via->link) => $this->owner->getPrimaryKey()])
                    ->execute();
            }
            $this->_tagsForDelete = [];
        }
    }
}


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

namespace Praxigento\BonusHybrid\Service\Calc\Bonus;

use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Request as AGetPeriodRequest;
use Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent\Response as AGetPeriodResponse;
use Praxigento\BonusBase\Repo\Data\Log\Customers as ELogCust;
use Praxigento\BonusBase\Repo\Data\Log\Opers as ELogOper;
use Praxigento\BonusHybrid\Config as Cfg;

/**
 * Calculate Team Bonus.
 */
class Team
    implements \Praxigento\Core\Api\App\Service\Process
{
    /** Calculation scheme (DEFAULT or EU) */
    const CTX_IN_SCHEME = 'in.scheme';

    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper */
    private $hlpOper;
    /** @var  \Praxigento\Core\Api\Helper\Period */
    private $hlpPeriod;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans */
    private $hlpTrans;
    /** @var \Praxigento\Core\Api\App\Logger\Main */
    private $logger;
    /** @var \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent */
    private $servPeriodGet;
    /** @var \Praxigento\BonusBase\Repo\Dao\Calculation */
    private $daoCalc;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Customers */
    private $daoLogCust;
    /** @var \Praxigento\BonusBase\Repo\Dao\Log\Opers */
    private $daoLogOper;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Team\CalcDef */
    private $subCalcDef;
    /** @var \Praxigento\BonusHybrid\Service\Calc\Bonus\Team\CalcEu */
    private $subCalcEu;

    public function __construct(
        \Praxigento\Core\Api\App\Logger\Main $logger,
        \Praxigento\Core\Api\Helper\Period $hlpPeriod,
        \Praxigento\BonusBase\Repo\Dao\Calculation $daoCalc,
        \Praxigento\BonusBase\Repo\Dao\Log\Customers $daoLogCust,
        \Praxigento\BonusBase\Repo\Dao\Log\Opers $daoLogOper,
        \Praxigento\BonusBase\Api\Service\Period\Calc\Get\Dependent $servPeriodGet,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\PrepareTrans $hlpTrans,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Z\Helper\CreateOper $hlpOper,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Team\CalcDef $subCalcDef,
        \Praxigento\BonusHybrid\Service\Calc\Bonus\Team\CalcEu $subCalcEu
    ) {
        $this->logger = $logger;
        $this->hlpPeriod = $hlpPeriod;
        $this->daoCalc = $daoCalc;
        $this->daoLogCust = $daoLogCust;
        $this->daoLogOper = $daoLogOper;
        $this->servPeriodGet = $servPeriodGet;
        $this->hlpTrans = $hlpTrans;
        $this->hlpOper = $hlpOper;
        $this->subCalcDef = $subCalcDef;
        $this->subCalcEu = $subCalcEu;
    }

    public function exec(\Praxigento\Core\Data $ctx)
    {
        /* get working data from context */
        $scheme = $ctx->get(self::CTX_IN_SCHEME) ?? Cfg::SCHEMA_DEFAULT;
        /**
         * perform processing
         */
        $ctx->set(self::CTX_OUT_SUCCESS, false);
        $this->logger->info("Team bonus ('$scheme' scheme) is started.");
        /**
         * get dependent calculation data
         *
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $teamPeriod
         * @var \Praxigento\BonusBase\Repo\Data\Calculation $teamCalc
         */
        list($compressCalc, $teamPeriod, $teamCalc) = $this->getCalcData($scheme);
        $compressCalcId = $compressCalc->getId();
        $teamCalcId = $teamCalc->getId();
        /* calculate bonus according to given SCHEME */
        if ($scheme == Cfg::SCHEMA_EU) {
            $bonus = $this->subCalcEu->exec($compressCalcId);
        } else {
            $bonus = $this->subCalcDef->exec($compressCalcId);
        }
        /* convert calculated bonus to transactions */
        $trans = $this->getTransactions($bonus, $teamPeriod);
        /* register bonus operation */
        $operRes = $this->hlpOper->exec(Cfg::CODE_TYPE_OPER_BONUS_TEAM, $trans, $teamPeriod);
        $operId = $operRes->getOperationId();
        $transIds = $operRes->getTransactionsIds();
        /* register transactions in log */
        $this->saveLogCustomers($transIds);
        /* register operation in log */
        $this->saveLogOper($operId, $teamCalcId);
        /* mark this calculation complete */
        $this->daoCalc->markComplete($teamCalcId);
        /* mark process as successful */
        $ctx->set(self::CTX_OUT_SUCCESS, true);
        $this->logger->info("Team bonus ('$scheme' scheme) is completed.");
    }

    /**
     * Get period and calculation data for all related calculation types.
     *
     * @param string $scheme see \Praxigento\BonusHybrid\Config::SCHEMA_XXX
     * @return array [$compressCalc, $teamPeriod, $teamCalc]
     * @throws \Exception
     */
    private function getCalcData($scheme)
    {
        $calcTypeCode = ($scheme == Cfg::SCHEMA_EU)
            ? Cfg::CODE_TYPE_CALC_BONUS_TEAM_EU
            : Cfg::CODE_TYPE_CALC_BONUS_TEAM_DEF;
        /**
         * Get period & calc data for Team bonus & TV Volumes Calculation.
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV);
        $req->setDepCalcTypeCode($calcTypeCode);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Period $teamPeriod */
        $teamPeriod = $resp->getDepPeriodData();
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $teamCalc */
        $teamCalc = $resp->getDepCalcData();
        /**
         * Get period and calc data for compression calc (basic for TV volumes).
         */
        $req = new AGetPeriodRequest();
        $req->setBaseCalcTypeCode(Cfg::CODE_TYPE_CALC_COMPRESS_PHASE1);
        $req->setDepCalcTypeCode(Cfg::CODE_TYPE_CALC_VALUE_TV);
        $req->setDepIgnoreComplete(true);
        /** @var AGetPeriodResponse $resp */
        $resp = $this->servPeriodGet->exec($req);
        /** @var \Praxigento\BonusBase\Repo\Data\Calculation $compressCalc */
        $compressCalc = $resp->getBaseCalcData();
        /**
         * Compose result.
         */
        $result = [$compressCalc, $teamPeriod, $teamCalc];
        return $result;
    }

    /**
     * @param array $bonus [custId => bonusValue]
     * @param \Praxigento\BonusBase\Repo\Data\Period $period
     * @return \Praxigento\Accounting\Repo\Data\Transaction[]
     */
    private function getTransactions($bonus, $period)
    {
        $dsEnd = $period->getDstampEnd();
        $dateApplied = $this->hlpPeriod->getTimestampUpTo($dsEnd);
        $yyyymm = substr($dsEnd, 0, 6);
        $note = "Team ($yyyymm)";
        $result = $this->hlpTrans->exec($bonus, $dateApplied, $note);
        return $result;
    }

    /**
     * Save customers log for Team bonus transactions (DEFAULT scheme).
     *
     * @param array $transIds [$transId => $custId]
     */
    private function saveLogCustomers($transIds)
    {
        foreach ($transIds as $transId => $custId) {
            $this->daoLogCust->create([
                ELogCust::A_TRANS_ID => $transId,
                ELogCust::A_CUSTOMER_ID => $custId

            ]);
        }
    }

    /**
     * Bind operation with calculation.
     *
     * @param int $operId
     * @param int $calcId
     */
    private function saveLogOper($operId, $calcId)
    {
        $entity = new ELogOper();
        $entity->setOperId($operId);
        $entity->setCalcId($calcId);
        $this->daoLogOper->create($entity);
    }
}


<?php

/*
 * This file is part of the Predis package.
 *
 * (c) Daniele Alessandri <suppakilla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Predis\Configuration\Option;

use Predis\Command\FactoryInterface;
use Predis\Command\RedisFactory;
use Predis\Configuration\OptionInterface;
use Predis\Configuration\OptionsInterface;

/**
 * Configures a connection factory to be used by the client.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class Commands implements OptionInterface
{
    /**
     * {@inheritdoc}
     */
    public function filter(OptionsInterface $options, $value)
    {
        if (is_callable($value)) {
            $value = call_user_func($value, $options);
        }

        if (is_array($value)) {
            $commands = $this->getDefault($options);

            foreach ($value as $commandID => $classFQN) {
                $commands->defineCommand($commandID, $classFQN);
            }

            return $commands;
        }

        if (!$value instanceof FactoryInterface) {
            $class = get_called_class();

            throw new \InvalidArgumentException("$class expects a valid command factory");
        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefault(OptionsInterface $options)
    {
        $commands = new RedisFactory();

        if (isset($options->prefix)) {
            $commands->setProcessor($options->prefix);
        }

        return $commands;
    }
}


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

namespace cascade\components\dataInterface\connectors\generic;

use Exception;
use canis\base\language\Verb;

/**
 * DataItem [[@doctodo class_description:cascade\components\dataInterface\connectors\generic\DataItem]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class DataItem extends \cascade\components\dataInterface\DataItem
{
    /**
     * @var [[@doctodo var_type:_isLoadingForeignObject]] [[@doctodo var_description:_isLoadingForeignObject]]
     */
    protected $_isLoadingForeignObject = false;
    /**
     * @var [[@doctodo var_type:_isLoadingLocalObject]] [[@doctodo var_description:_isLoadingLocalObject]]
     */
    protected $_isLoadingLocalObject = false;

    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->on(self::EVENT_LOAD_FOREIGN_OBJECT, [$this, 'loadForeignObject']);
        $this->on(self::EVENT_LOAD_LOCAL_OBJECT, [$this, 'loadLocalObject']);
        parent::init();
    }

    /**
     * @inheritdoc
     */
    protected function handleForeign($baseAttributes = [])
    {
        if ($this->ignoreForeignObject) {
            return;
        }

        // foreign to local

        // find or start up local object
        $localModel = $this->dataSource->localModel;
        if (!isset($this->localObject)) {
            $this->localObject = new $localModel();
        }
        $isNewRecord = $this->localObject->isNewRecord;
        $actionVerb = new Verb('create');
        if (!$isNewRecord) {
            $actionVerb = new Verb('update');
        }
        // $this->localObject->auditAgent = $this->module->collectorItem->interfaceObject->primaryKey;
        $this->localObject->auditDataInterface = $this->module->collectorItem->interfaceObject->primaryKey;

        $attributes = $this->dataSource->buildLocalAttributes($this->foreignObject, $this->localObject);
        if (empty($attributes)) {
            return false;
        }

        if ($this->localModelError) {
            $this->dataSource->task->addError('Unable to match local ' . $this->dataSource->descriptor . ' object', ['attributes' => $attributes]);

            return false;
        }

        $relations = [];
        // load local object
        foreach ($attributes as $key => $value) {
            $this->localObject->{$key} = $value;
        }

        foreach (array_merge($this->dataSource->baseAttributes, $baseAttributes) as $key => $value) {
            $this->localObject->{$key} = $value;
        }

        // save local object
        if (!$this->localObject->save()) {
            $this->dataSource->task->addError('Unable to ' . $actionVerb->getSimplePresent(false) . ' local ' . $this->dataSource->descriptor . ' object: ' . $this->localObject->descriptor, ['errors' => $this->localObject->errors, 'attributes' => $this->localObject->attributes]);

            return false;
        }
        $dirtyAttributes = $this->localObject->getDirtyAttributes();
        $oldAttributes = $this->localObject->getOldAttributes();

        if ($this->localObject->getBehavior('Auditable') !== null) {
            foreach ($this->localObject->getBehavior('Auditable')->ignoreAttributes as $ignore) {
                unset($dirtyAttributes[$ignore]);
            }
        }

        if ($this->localObject->getBehavior('Date') !== null) {
            $oldAttributes = $this->localObject->getBehavior('Date')->convertToDatabaseDate($oldAttributes);
            $dirtyAttributes = $this->localObject->getBehavior('Date')->convertToDatabaseDate($dirtyAttributes);
            foreach ($dirtyAttributes as $key => $value) {
                if (isset($oldAttributes[$key]) && $value === $oldAttributes[$key]) {
                    unset($dirtyAttributes[$key]);
                }
            }
        }

        if ($isNewRecord || !empty($dirtyAttributes)) {
            $infoData = [];
            if (!$isNewRecord) {
                $infoData = ['newValues' => $dirtyAttributes, 'oldValues' => []];

                foreach ($dirtyAttributes as $key => $newValue) {
                    $oldValue = null;
                    if (isset($oldAttributes[$key])) {
                        $oldValue = $oldAttributes[$key];
                    }
                    $infoData['oldValues'][$key] = $oldValue;
                }
            }
            $this->dataSource->task->addInfo($actionVerb->getPast(true) . ' local ' . $this->dataSource->descriptor . ' object: ' . $this->localObject->descriptor, $infoData);
        }

        // save foreign key map
        if (!$this->dataSource->saveKeyTranslation($this->foreignObject, $this->localObject)) {
            throw new Exception("Unable to save key translation!");
        }

        // loop through children
        // some interfaces ask the foreignObject for children
        foreach ($this->foreignObject->children as $table => $children) {
            $dataSource = $this->module->getDataSource($table);
            if (empty($dataSource) || !$dataSource->isReady()) {
                continue;
            }
            foreach ($children as $childId) {
                // let the handler figure it out
                if (!($dataItem = $dataSource->getForeignDataItem($childId))) {
                    continue;
                }
                $childLocalObject = $dataItem->handle(true, ['indirectObject' => $this->localObject, 'relationModels' => [['parent_object_id' => $this->localObject->primaryKey]]]);
            }
        }
        foreach ($this->foreignChildren as $modelName => $children) {
            $dataSource = $this->module->getDataSource($modelName);
            if (empty($dataSource) || !$dataSource->isReady()) {
                continue;
            }
            foreach ($children as $relationSet) {
                // let the handler figure it out
                if (!($dataItem = $dataSource->getForeignDataItem($relationSet['foreignId']))) {
                    continue;
                }
                $relationSet['parent_object_id'] = $this->localObject->primaryKey;
                unset($relationSet['foreignId']);
                $childLocalObject = $dataItem->handle(true, ['indirectObject' => $this->localObject, 'relationModels' => [$relationSet]]);
            }
        }
        foreach ($this->foreignParents as $modelName => $parents) {
            $dataSource = $this->module->getDataSource($modelName);
            if (empty($dataSource) || !$dataSource->isReady()) {
                \d($dataSource);
                \d("$modelName isn't ready");
                exit;
                continue;
            }
            foreach ($parents as $relationSet) {
                // let the handler figure it out
                if (!($dataItem = $dataSource->getForeignDataItem($relationSet['foreignId']))) {
                    continue;
                }
                $relationSet['child_object_id'] = $this->localObject->primaryKey;
                unset($relationSet['foreignId']);
                $parentLocalObject = $dataItem->handle(true, ['indirectObject' => $this->localObject, 'relationModels' => [$relationSet]]);
            }
        }

        return $this->localObject;
    }

    /**
     * Get foreign parents.
     *
     * @return [[@doctodo return_type:getForeignParents]] [[@doctodo return_description:getForeignParents]]
     */
    public function getForeignParents()
    {
        $parents = [];
        foreach ($this->dataSource->foreignParentKeys as $keySet) {
            $model = $keySet['foreignModel'];
            unset($keySet['foreignModel']);
            if (!empty($this->foreignObject->{$keySet['foreignId']})) {
                $keySet['foreignId'] = $this->foreignObject->{$keySet['foreignId']};
                if (!isset($parents[$model])) {
                    $parents[$model] = [];
                }
                $parents[$model][] = $keySet;
            }
        }

        return $parents;
    }

    /**
     * Get foreign children.
     *
     * @return [[@doctodo return_type:getForeignChildren]] [[@doctodo return_description:getForeignChildren]]
     */
    public function getForeignChildren()
    {
        $children = [];
        foreach ($this->dataSource->foreignChildKeys as $keySet) {
            $model = $keySet['foreignModel'];
            unset($keySet['foreignModel']);
            if (!empty($this->foreignObject->{$keySet['foreignId']})) {
                $keySet['foreignId'] = $this->foreignObject->{$keySet['foreignId']};
                if (!isset($children[$model])) {
                    $children[$model] = [];
                }
                $children[$model][] = $keySet;
            }
        }

        return $children;
    }

    /**
     * [[@doctodo method_description:loadForeignObject]].
     */
    abstract protected function loadForeignObject();

    /**
     * [[@doctodo method_description:loadLocalObject]].
     */
    abstract protected function loadLocalObject();
}


<?php

namespace Loevgaard\Dandomain\Pay\Model;

use Money\Currency;
use Money\Money;
use Psr\Http\Message\ServerRequestInterface;

class Payment
{
    /**
     * @var string
     */
    protected $apiKey;

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

    /**
     * @var int
     */
    protected $orderId;

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

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

    /**
     * @var Money
     */
    protected $totalAmount;

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

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

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

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

    /**
     * @var int
     */
    protected $languageId;

    /**
     * @var bool
     */
    protected $testMode;

    /**
     * @var int
     */
    protected $paymentGatewayCurrencyCode;

    /**
     * @var int
     */
    protected $cardTypeId;

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

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

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

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

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

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

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

    /**
     * @var int
     */
    protected $customerCountryId;

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

    /**
     * This is the ISO 3166 country code
     *
     * @var string
     */
    protected $customerCountryCode;

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

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

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

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

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

    /**
     * @var int
     */
    protected $customerCustTypeId;

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @var int
     */
    protected $deliveryCountryID;

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

    /**
     * This is the ISO 3166 country code
     *
     * @var string
     */
    protected $deliveryCountryCode;

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

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

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

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

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

    /**
     * @var int
     */
    protected $shippingMethodId;

    /**
     * @var Money
     */
    protected $shippingFee;

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

    /**
     * @var int
     */
    protected $paymentMethodId;

    /**
     * @var Money
     */
    protected $paymentFee;

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

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

    /**
     * @var PaymentLine[]
     */
    protected $paymentLines;

    public function __construct()
    {
        $this->paymentLines = [];
    }

    public static function createFromRequest(ServerRequestInterface $request) : Payment
    {
        $payment = new static();
        $payment->populateFromRequest($request);
        return $payment;
    }

    public function populateFromRequest(ServerRequestInterface $request)
    {
        $body = $request->getParsedBody();
        $body = is_array($body) ? $body : [];

        // set currency because we use it to create Money objects
        $this->setCurrencySymbol($body['APICurrencySymbol'] ?? '');

        $totalAmount = $this->createMoneyFromFloat($body['APITotalAmount'] ?? '0.00');
        if ($totalAmount) {
            $this->setTotalAmount($totalAmount);
        }

        $shippingFee = $this->createMoneyFromFloat($body['APIShippingFee'] ?? '0.00');
        if ($shippingFee) {
            $this->setShippingFee($shippingFee);
        }

        $paymentFee = $this->createMoneyFromFloat($body['APIPayFee'] ?? '0.00');
        if ($paymentFee) {
            $this->setPaymentFee($paymentFee);
        }

        $this->setApiKey($body['APIkey'] ?? '');
        $this->setMerchant($body['APIMerchant'] ?? '');
        $this->setOrderId($body['APIOrderID'] ?? 0);
        $this->setSessionId($body['APISessionID'] ?? '');
        $this->setCallBackUrl($body['APICallBackUrl'] ?? '');
        $this->setFullCallBackOkUrl($body['APIFullCallBackOKUrl'] ?? '');
        $this->setCallBackOkUrl($body['APICallBackOKUrl'] ?? '');
        $this->setCallBackServerUrl($body['APICallBackServerUrl'] ?? '');
        $this->setLanguageId((int)($body['APILanguageID'] ?? 0));
        $this->setTestMode(isset($body['APITestMode']) && 'True' === $body['APITestMode']);
        $this->setPaymentGatewayCurrencyCode((int)($body['APIPayGatewayCurrCode'] ??  0));
        $this->setCardTypeId((int)($body['APICardTypeID'] ?? 0));
        $this->setCustomerRekvNr($body['APICRekvNr'] ?? '');
        $this->setCustomerName($body['APICName'] ?? '');
        $this->setCustomerCompany($body['APICCompany'] ?? '');
        $this->setCustomerAddress($body['APICAddress'] ?? '');
        $this->setCustomerAddress2($body['APICAddress2'] ?? '');
        $this->setCustomerZipCode($body['APICZipCode'] ?? '');
        $this->setCustomerCity($body['APICCity'] ?? '');
        $this->setCustomerCountryId((int)($body['APICCountryID'] ?? 0));
        $this->setCustomerCountry($body['APICCountry'] ?? '');
        $this->setCustomerCountryCode($body['APICCountryCode'] ?? '');
        $this->setCustomerPhone($body['APICPhone'] ?? '');
        $this->setCustomerFax($body['APICFax'] ?? '');
        $this->setCustomerEmail($body['APICEmail'] ?? '');
        $this->setCustomerNote($body['APICNote'] ?? '');
        $this->setCustomerCvrnr($body['APICcvrnr'] ?? '');
        $this->setCustomerCustTypeId((int)($body['APICCustTypeID'] ?? 0));
        $this->setCustomerEan($body['APICEAN'] ?? '');
        $this->setCustomerRes1($body['APICres1'] ?? '');
        $this->setCustomerRes2($body['APICres2'] ?? '');
        $this->setCustomerRes3($body['APICres3'] ?? '');
        $this->setCustomerRes4($body['APICres4'] ?? '');
        $this->setCustomerRes5($body['APICres5'] ?? '');
        $this->setDeliveryName($body['APIDName'] ?? '');
        $this->setDeliveryCompany($body['APIDCompany'] ?? '');
        $this->setDeliveryAddress($body['APIDAddress'] ?? '');
        $this->setDeliveryAddress2($body['APIDAddress2'] ?? '');
        $this->setDeliveryZipCode($body['APIDZipCode'] ?? '');
        $this->setDeliveryCity($body['APIDCity'] ?? '');
        $this->setDeliveryCountryID((int)($body['APIDCountryID'] ?? 0));
        $this->setDeliveryCountry($body['APIDCountry'] ?? '');
        $this->setDeliveryCountryCode($body['APIDCountryCode'] ?? '');
        $this->setDeliveryPhone($body['APIDPhone'] ?? '');
        $this->setDeliveryFax($body['APIDFax'] ?? '');
        $this->setDeliveryEmail($body['APIDEmail'] ?? '');
        $this->setDeliveryEan($body['APIDean'] ?? '');
        $this->setShippingMethod($body['APIShippingMethod'] ?? '');
        $this->setShippingMethodId((int)($body['APIShippingMethodID'] ?? 0));
        $this->setPaymentMethod($body['APIPayMethod'] ?? '');
        $this->setPaymentMethodId((int)($body['APIPayMethodID'] ?? 0));
        $this->setCustomerIp($body['APICIP'] ?? '');
        $this->setLoadBalancerRealIp($body['APILoadBalancerRealIP'] ?? '');
        $this->setReferrer($request->hasHeader('referer') ? $request->getHeaderLine('referer') : '');

        // populate order lines
        $i = 1;
        while (isset($body['APIBasketProdAmount'.$i])) {
            $qty = (int)$body['APIBasketProdAmount'.$i];
            $productNumber = $body['APIBasketProdNumber'.$i] ?? '';
            $name = $body['APIBasketProdName'.$i] ?? '';
            $price = $this->createMoneyFromFloat($body['APIBasketProdPrice'.$i] ?? '0.00');
            $vat = (int)($body['APIBasketProdVAT'.$i] ?? 0);

            $this->addPaymentLine(static::createPaymentLine($productNumber, $name, $qty, $price, $vat));

            ++$i;
        }
    }

    public static function createPaymentLine(string $productNumber, string $name, int $quantity, Money $price, int $vat)
    {
        return new PaymentLine($productNumber, $name, $quantity, $price, $vat);
    }

    /**
     * Takes strings like
     * - 1.000,50
     * - 1,000.50
     * - 1000.50
     * - 1000,50.
     *
     * and returns 100050
     *
     * @param string $str
     * @param string $propertyPath
     *
     * @return int
     */
    public static function priceStringToInt(string $str, string $propertyPath = '') : int
    {
        $str = trim($str);

        // verify format of string
        if (!preg_match('/(\.|,)[0-9]{2}$/', $str)) {
            throw new \InvalidArgumentException(($propertyPath ? $propertyPath.' (value: "'.$str.'")' : $str).
                ' does not match the currency string format');
        }
        $str = preg_replace('/[^0-9]+/', '', $str);

        return intval($str);
    }

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

    /**
     * @param string $apiKey
     *
     * @return Payment
     */
    public function setApiKey(string $apiKey): self
    {
        $this->apiKey = $apiKey;

        return $this;
    }

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

    /**
     * @param string $merchant
     *
     * @return Payment
     */
    public function setMerchant(string $merchant): self
    {
        $this->merchant = $merchant;

        return $this;
    }

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

    /**
     * @param int $orderId
     *
     * @return Payment
     */
    public function setOrderId(int $orderId): self
    {
        $this->orderId = $orderId;

        return $this;
    }

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

    /**
     * @param string $sessionId
     *
     * @return Payment
     */
    public function setSessionId(string $sessionId): self
    {
        $this->sessionId = $sessionId;

        return $this;
    }

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

    /**
     * @param string $currencySymbol
     *
     * @return Payment
     */
    public function setCurrencySymbol(string $currencySymbol): self
    {
        $conversions = [
            '€' => 'EUR',
            '$' => 'USD',
            '£' => 'GBP',
            '¥' => 'JPY'
        ];

        $currencySymbol = $conversions[$currencySymbol] ?? $currencySymbol;

        $this->currencySymbol = $currencySymbol;

        return $this;
    }

    /**
     * @return Money
     */
    public function getTotalAmount(): ?Money
    {
        return $this->totalAmount;
    }

    /**
     * @param Money $totalAmount
     *
     * @return Payment
     */
    public function setTotalAmount(Money $totalAmount): self
    {
        $this->totalAmount = $totalAmount;

        return $this;
    }

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

    /**
     * @param string $callBackUrl
     *
     * @return Payment
     */
    public function setCallBackUrl(string $callBackUrl): self
    {
        $this->callBackUrl = $callBackUrl;

        return $this;
    }

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

    /**
     * @param string $fullCallBackOkUrl
     *
     * @return Payment
     */
    public function setFullCallBackOkUrl(string $fullCallBackOkUrl): self
    {
        $this->fullCallBackOkUrl = $fullCallBackOkUrl;

        return $this;
    }

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

    /**
     * @param string $callBackOkUrl
     *
     * @return Payment
     */
    public function setCallBackOkUrl(string $callBackOkUrl): self
    {
        $this->callBackOkUrl = $callBackOkUrl;

        return $this;
    }

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

    /**
     * @param string $callBackServerUrl
     *
     * @return Payment
     */
    public function setCallBackServerUrl(string $callBackServerUrl): self
    {
        $this->callBackServerUrl = $callBackServerUrl;

        return $this;
    }

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

    /**
     * @param int $languageId
     *
     * @return Payment
     */
    public function setLanguageId(int $languageId): self
    {
        $this->languageId = $languageId;

        return $this;
    }

    /**
     * @return bool
     */
    public function isTestMode(): ?bool
    {
        return $this->testMode;
    }

    /**
     * @param bool $testMode
     *
     * @return Payment
     */
    public function setTestMode(bool $testMode): self
    {
        $this->testMode = $testMode;

        return $this;
    }

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

    /**
     * @param int $paymentGatewayCurrencyCode
     *
     * @return Payment
     */
    public function setPaymentGatewayCurrencyCode(int $paymentGatewayCurrencyCode): self
    {
        $this->paymentGatewayCurrencyCode = $paymentGatewayCurrencyCode;

        return $this;
    }

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

    /**
     * @param int $cardTypeId
     *
     * @return Payment
     */
    public function setCardTypeId(int $cardTypeId): self
    {
        $this->cardTypeId = $cardTypeId;

        return $this;
    }

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

    /**
     * @param string $customerRekvNr
     *
     * @return Payment
     */
    public function setCustomerRekvNr(string $customerRekvNr): self
    {
        $this->customerRekvNr = $customerRekvNr;

        return $this;
    }

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

    /**
     * @param string $customerName
     *
     * @return Payment
     */
    public function setCustomerName(string $customerName): self
    {
        $this->customerName = $customerName;

        return $this;
    }

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

    /**
     * @param string $customerCompany
     *
     * @return Payment
     */
    public function setCustomerCompany(string $customerCompany): self
    {
        $this->customerCompany = $customerCompany;

        return $this;
    }

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

    /**
     * @param string $customerAddress
     *
     * @return Payment
     */
    public function setCustomerAddress(string $customerAddress): self
    {
        $this->customerAddress = $customerAddress;

        return $this;
    }

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

    /**
     * @param string $customerAddress2
     *
     * @return Payment
     */
    public function setCustomerAddress2(string $customerAddress2): self
    {
        $this->customerAddress2 = $customerAddress2;

        return $this;
    }

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

    /**
     * @param string $customerZipCode
     *
     * @return Payment
     */
    public function setCustomerZipCode(string $customerZipCode): self
    {
        $this->customerZipCode = $customerZipCode;

        return $this;
    }

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

    /**
     * @param string $customerCity
     *
     * @return Payment
     */
    public function setCustomerCity(string $customerCity): self
    {
        $this->customerCity = $customerCity;

        return $this;
    }

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

    /**
     * @param int $customerCountryId
     *
     * @return Payment
     */
    public function setCustomerCountryId(int $customerCountryId): self
    {
        $this->customerCountryId = $customerCountryId;

        return $this;
    }

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

    /**
     * @param string $customerCountry
     *
     * @return Payment
     */
    public function setCustomerCountry(string $customerCountry): self
    {
        $this->customerCountry = $customerCountry;

        return $this;
    }

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

    /**
     * @param string $customerCountryCode
     * @return Payment
     */
    public function setCustomerCountryCode(string $customerCountryCode): self
    {
        $this->customerCountryCode = $customerCountryCode;
        return $this;
    }

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

    /**
     * @param string $customerPhone
     *
     * @return Payment
     */
    public function setCustomerPhone(string $customerPhone): self
    {
        $this->customerPhone = $customerPhone;

        return $this;
    }

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

    /**
     * @param string $customerFax
     *
     * @return Payment
     */
    public function setCustomerFax(string $customerFax): self
    {
        $this->customerFax = $customerFax;

        return $this;
    }

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

    /**
     * @param string $customerEmail
     *
     * @return Payment
     */
    public function setCustomerEmail(string $customerEmail): self
    {
        $this->customerEmail = $customerEmail;

        return $this;
    }

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

    /**
     * @param string $customerNote
     *
     * @return Payment
     */
    public function setCustomerNote(string $customerNote): self
    {
        $this->customerNote = $customerNote;

        return $this;
    }

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

    /**
     * @param string $customerCvrnr
     *
     * @return Payment
     */
    public function setCustomerCvrnr(string $customerCvrnr): self
    {
        $this->customerCvrnr = $customerCvrnr;

        return $this;
    }

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

    /**
     * @param int $customerCustTypeId
     *
     * @return Payment
     */
    public function setCustomerCustTypeId(int $customerCustTypeId): self
    {
        $this->customerCustTypeId = $customerCustTypeId;

        return $this;
    }

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

    /**
     * @param string $customerEan
     *
     * @return Payment
     */
    public function setCustomerEan(string $customerEan): self
    {
        $this->customerEan = $customerEan;

        return $this;
    }

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

    /**
     * @param string $customerRes1
     *
     * @return Payment
     */
    public function setCustomerRes1(string $customerRes1): self
    {
        $this->customerRes1 = $customerRes1;

        return $this;
    }

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

    /**
     * @param string $customerRes2
     *
     * @return Payment
     */
    public function setCustomerRes2(string $customerRes2): self
    {
        $this->customerRes2 = $customerRes2;

        return $this;
    }

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

    /**
     * @param string $customerRes3
     *
     * @return Payment
     */
    public function setCustomerRes3(string $customerRes3): self
    {
        $this->customerRes3 = $customerRes3;

        return $this;
    }

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

    /**
     * @param string $customerRes4
     *
     * @return Payment
     */
    public function setCustomerRes4(string $customerRes4): self
    {
        $this->customerRes4 = $customerRes4;

        return $this;
    }

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

    /**
     * @param string $customerRes5
     *
     * @return Payment
     */
    public function setCustomerRes5(string $customerRes5): self
    {
        $this->customerRes5 = $customerRes5;

        return $this;
    }

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

    /**
     * @param string $customerIp
     *
     * @return Payment
     */
    public function setCustomerIp(string $customerIp): self
    {
        $this->customerIp = $customerIp;

        return $this;
    }

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

    /**
     * @param string $deliveryName
     *
     * @return Payment
     */
    public function setDeliveryName(string $deliveryName): self
    {
        $this->deliveryName = $deliveryName;

        return $this;
    }

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

    /**
     * @param string $deliveryCompany
     *
     * @return Payment
     */
    public function setDeliveryCompany(string $deliveryCompany): self
    {
        $this->deliveryCompany = $deliveryCompany;

        return $this;
    }

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

    /**
     * @param string $deliveryAddress
     *
     * @return Payment
     */
    public function setDeliveryAddress(string $deliveryAddress): self
    {
        $this->deliveryAddress = $deliveryAddress;

        return $this;
    }

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

    /**
     * @param string $deliveryAddress2
     *
     * @return Payment
     */
    public function setDeliveryAddress2(string $deliveryAddress2): self
    {
        $this->deliveryAddress2 = $deliveryAddress2;

        return $this;
    }

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

    /**
     * @param string $deliveryZipCode
     *
     * @return Payment
     */
    public function setDeliveryZipCode(string $deliveryZipCode): self
    {
        $this->deliveryZipCode = $deliveryZipCode;

        return $this;
    }

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

    /**
     * @param string $deliveryCity
     *
     * @return Payment
     */
    public function setDeliveryCity(string $deliveryCity): self
    {
        $this->deliveryCity = $deliveryCity;

        return $this;
    }

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

    /**
     * @param int $deliveryCountryID
     *
     * @return Payment
     */
    public function setDeliveryCountryID(int $deliveryCountryID): self
    {
        $this->deliveryCountryID = $deliveryCountryID;

        return $this;
    }

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

    /**
     * @param string $deliveryCountry
     *
     * @return Payment
     */
    public function setDeliveryCountry(string $deliveryCountry): self
    {
        $this->deliveryCountry = $deliveryCountry;

        return $this;
    }

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

    /**
     * @param string $deliveryCountryCode
     * @return Payment
     */
    public function setDeliveryCountryCode(string $deliveryCountryCode)
    {
        $this->deliveryCountryCode = $deliveryCountryCode;
        return $this;
    }

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

    /**
     * @param string $deliveryPhone
     *
     * @return Payment
     */
    public function setDeliveryPhone(string $deliveryPhone): self
    {
        $this->deliveryPhone = $deliveryPhone;

        return $this;
    }

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

    /**
     * @param string $deliveryFax
     *
     * @return Payment
     */
    public function setDeliveryFax(string $deliveryFax): self
    {
        $this->deliveryFax = $deliveryFax;

        return $this;
    }

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

    /**
     * @param string $deliveryEmail
     *
     * @return Payment
     */
    public function setDeliveryEmail(string $deliveryEmail): self
    {
        $this->deliveryEmail = $deliveryEmail;

        return $this;
    }

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

    /**
     * @param string $deliveryEan
     *
     * @return Payment
     */
    public function setDeliveryEan(string $deliveryEan): self
    {
        $this->deliveryEan = $deliveryEan;

        return $this;
    }

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

    /**
     * @param string $shippingMethod
     *
     * @return Payment
     */
    public function setShippingMethod(string $shippingMethod): self
    {
        $this->shippingMethod = $shippingMethod;

        return $this;
    }

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

    /**
     * @param int $shippingMethodId
     * @return Payment
     */
    public function setShippingMethodId(int $shippingMethodId) : self
    {
        $this->shippingMethodId = $shippingMethodId;
        return $this;
    }

    /**
     * @return Money
     */
    public function getShippingFee(): ?Money
    {
        return $this->shippingFee;
    }

    /**
     * @param Money $shippingFee
     *
     * @return Payment
     */
    public function setShippingFee(Money $shippingFee): self
    {
        $this->shippingFee = $shippingFee;

        return $this;
    }

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

    /**
     * @param string $paymentMethod
     *
     * @return Payment
     */
    public function setPaymentMethod(string $paymentMethod): self
    {
        $this->paymentMethod = $paymentMethod;

        return $this;
    }

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

    /**
     * @param int $paymentMethodId
     * @return Payment
     */
    public function setPaymentMethodId(int $paymentMethodId) : self
    {
        $this->paymentMethodId = $paymentMethodId;
        return $this;
    }

    /**
     * @return Money
     */
    public function getPaymentFee(): ?Money
    {
        return $this->paymentFee;
    }

    /**
     * @param Money $paymentFee
     *
     * @return Payment
     */
    public function setPaymentFee(Money $paymentFee): self
    {
        $this->paymentFee = $paymentFee;

        return $this;
    }

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

    /**
     * @param string $loadBalancerRealIp
     *
     * @return Payment
     */
    public function setLoadBalancerRealIp(string $loadBalancerRealIp): self
    {
        $this->loadBalancerRealIp = $loadBalancerRealIp;

        return $this;
    }

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

    /**
     * @param string $referrer
     *
     * @return Payment
     */
    public function setReferrer(string $referrer): self
    {
        $this->referrer = $referrer;

        return $this;
    }

    /**
     * @return PaymentLine[]|iterable
     */
    public function getPaymentLines(): iterable
    {
        return $this->paymentLines;
    }

    /**
     * @param PaymentLine[]|iterable $paymentLines
     *
     * @return Payment
     */
    public function setPaymentLines(iterable $paymentLines): self
    {
        $this->paymentLines = $paymentLines;

        return $this;
    }

    /**
     * @param PaymentLine $paymentLine
     *
     * @return Payment
     */
    public function addPaymentLine(PaymentLine $paymentLine): self
    {
        $paymentLine->setPayment($this);
        $this->paymentLines[] = $paymentLine;

        return $this;
    }

    /**
     * Returns the default currency for this payment
     *
     * @return null|string
     */
    protected function getCurrency() : ?string
    {
        return $this->currencySymbol;
    }

    /**
     * A helper method for creating a Money object from a float based on the shared currency
     *
     * @param int $amount
     * @return Money|null
     */
    protected function createMoney(int $amount = 0) : ?Money
    {
        if (!$this->getCurrency()) {
            return null;
        }

        return new Money($amount, new Currency($this->getCurrency()));
    }

    /**
     * A helper method for creating a Money object from a float based on the shared currency
     *
     * The float can be any format, i.e. 1.50 or 1,50
     *
     * @param string $amount
     * @return Money|null
     */
    protected function createMoneyFromFloat(string $amount = '0.00') : ?Money
    {
        $amount = static::priceStringToInt((string)$amount);
        return $this->createMoney($amount);
    }
}


<?php

namespace Lab123\Odin;

use Lab123\Odin\Entities\Entity;
use Lab123\Odin\Contracts\IObserver;

abstract class Observer implements IObserver
{

    /**
     * Entity Reference (App\Entities\Entity::class)
     */
    protected $entity;

    /**
     * Observers available
     */
    protected $observers = [
        'creating',
        'created',
        'saving',
        'saved',
        'updating',
        'updated',
        'deleting',
        'deleted'
    ];

    /**
     * Create a new Observer instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->activeObservers();
    }

    /**
     * Active observers
     *
     * @return void
     */
    protected function activeObservers()
    {
        foreach ($this->observers as $observer) {

            $entity = $this->entity;

            $entity::$observer(function ($entity) use ($observer) {
                $this->$observer($entity);
            });
        }
    }

    /**
     * Active observer in trigger creating
     */
    public function creating($entity)
    {}

    /**
     * Active observer in trigger created
     */
    public function created($entity)
    {}

    /**
     * Active observer in trigger saving
     */
    public function saving($entity)
    {}

    /**
     * Active observer in trigger saved
     */
    public function saved($entity)
    {}

    /**
     * Active observer in trigger updating
     */
    public function updating($entity)
    {}

    /**
     * Active observer in trigger updated
     */
    public function updated($entity)
    {}

    /**
     * Active observer in trigger deleting
     */
    public function deleting($entity)
    {}

    /**
     * Active observer in trigger deleted
     */
    public function deleted($entity)
    {}
}


<?php

declare(strict_types=1);

namespace Ruwork\RunetIdBundle\Basket\Basket\Filter;

use RunetId\Client\Result\Pay\ItemResult;
use RunetId\Client\Result\Pay\OrderResult;

final class ProductIdFilter extends AbstractBinaryFilter
{
    private $id;

    public function __construct(int $id, int $priority = 0)
    {
        $this->id = $id;
        parent::__construct($priority);
    }

    /**
     * {@inheritdoc}
     */
    protected function vote(ItemResult $item, ?OrderResult $order): bool
    {
        return $this->id === $item->Product->Id;
    }
}