<?php declare(strict_types=1);

namespace Roquie\Database\Seed;

use Invoker\Invoker;
use Invoker\ParameterResolver\Container\ParameterNameContainerResolver;
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\ResolverChain;
use League\Flysystem\FilesystemInterface;
use Psr\Container\ContainerInterface;
use Roquie\Database\Notify\NotifyInterface;
use Roquie\Database\Seed\Exception\InvalidArgumentException;

final class Seeder
{
    /**
     * @var mixed|\PDO
     */
    private $database;

    /**
     * @var \Psr\Container\ContainerInterface
     */
    private $container;

    /**
     * @var \League\Flysystem\FilesystemInterface
     */
    private $filesystem;

    /**
     * @var \Roquie\Database\Notify\NotifyInterface
     */
    private $notify;

    /**
     * @var \Invoker\Invoker
     */
    private $invoker;

    /**
     * Seeder constructor.
     *
     * @param $database
     * @param \Psr\Container\ContainerInterface $container
     * @param \League\Flysystem\FilesystemInterface $filesystem
     * @param \Roquie\Database\Notify\NotifyInterface $notify
     */
    public function __construct(
        $database,
        FilesystemInterface $filesystem,
        NotifyInterface $notify,
        ContainerInterface $container = null
    )
    {
        $invoker = is_null($container)
            ? null
            : $this->invoker($container);

        $this->database = $database;
        $this->filesystem = $filesystem;
        $this->notify = $notify;
        $this->invoker = $invoker;
        $this->container = $container;
    }

    /**
     * Start seeds!
     *
     * @param string|null $name
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotCallableException
     * @throws \Invoker\Exception\NotEnoughParametersException
     * @throws \League\Flysystem\FileNotFoundException
     */
    public function seed(?string $name = null): void
    {
        $this->notify->note('');

        $files = $this->all($name);

        if (count($files) < 1) {
            $this->notify->note("<info>Seed files not found.</info>");
            return;
        }

        foreach ($files as [$file, $content]) {
            $this->load($content);
            $this->resolve($file['filename'])->run();

            $this->notify->note("<comment>Seed</comment> {$file['basename']} <comment>executed</comment>");
        }
    }

    /**
     * Call seeder once.
     *
     * @param string $class
     * @return void
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotCallableException
     * @throws \Invoker\Exception\NotEnoughParametersException
     * @throws \League\Flysystem\FileNotFoundException
     * @throws \Roquie\Database\Seed\Exception\InvalidArgumentException
     */
    public function call(string $class): void
    {
        $files = $this->all($class);

        if (count($files) < 1) {
            throw InvalidArgumentException::forNotFoundSeeder();
        }

        foreach ($files as [$file, $content]) {
            $this->load($content);
            $this->resolve($file['filename'])->run();
        }
    }

    /**
     * Resolve loaded Seed class.
     *
     * @param string $class
     * @return \Roquie\Database\Seed\AbstractSeed
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotCallableException
     * @throws \Invoker\Exception\NotEnoughParametersException
     */
    private function resolve(string $class): AbstractSeed
    {
        /** @var $instance \Roquie\Database\Seed\AbstractSeed */
        $instance = $this->autowire($class);
        $instance->setDatabase($this->database);
        $instance->setSeeder($this);

        if (! is_null($this->container)) {
            $instance->setContainer($this->container);
        }

        return $instance;
    }

    /**
     * Database seed files do not contain user input.
     * So, use eval, in this case, is a normal solution
     * if you want to use Flysystem package.
     *
     * @param string $code
     * @return void
     */
    private function load(string $code): void
    {
        eval($this->removeTags($code));
    }

    /**
     * Remove PHP tags from code for executing in the eval function.
     *
     * @param string $code
     * @return string
     */
    private function removeTags(string $code): string
    {
        return str_replace(['<?php', '?>'], '', $code);
    }

    /**
     * Find all seed's in the default Flysystem path.
     *
     * @param string|null $name
     * @return array
     * @throws \League\Flysystem\FileNotFoundException
     */
    private function all(?string $name): array
    {
        $array = [];
        foreach ($this->filesystem->listContents() as $file) {
            if (is_null($name)) {
                $array[] = [$file, $this->filesystem->read($file['path'])];
            } else {
                if ($file['filename'] === ($name ?: Seed::DEFAULT_SEED)) {
                    $array[] = [$file, $this->filesystem->read($file['path'])];
                    break;
                }
            }
        }

        return $array;
    }

    /**
     * Automatically resolve dependencies
     *
     * @param string $class
     * @return mixed
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotCallableException
     * @throws \Invoker\Exception\NotEnoughParametersException
     */
    private function autowire(string $class): AbstractSeed
    {
        if (is_null($this->container)) {
            return new $class();
        }

        return $this->invoker->call($class);
    }

    /**
     * Create Invoker instance for constructor autowiring.
     *
     * @param \Psr\Container\ContainerInterface $container
     * @return \Invoker\Invoker
     */
    private function invoker(ContainerInterface $container)
    {
        $resolvers = new ResolverChain([
            new ParameterNameContainerResolver($container),
            new DefaultValueResolver(),
        ]);

        $invoker = new Invoker($resolvers, $container);

        return $invoker;
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Roquie\Database\Migration\Migrate;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class MigrateDownCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('migrate:down')
            ->setAliases(['migrate:rollback'])
            ->setDescription('Rollback the last database migration')
            ->setHelp('Example of usage: rdb migrate:down --dsn pgsql:dbname=test;host=localhost;user=root');

        $this
            ->addOption('dsn', 'd', InputOption::VALUE_REQUIRED, 'DNS string for connect with database.')
            ->addOption('step', null, InputOption::VALUE_OPTIONAL, 'Force the migrations to be run so they can be rolled back individually')
            ->addOption('path', null, InputOption::VALUE_OPTIONAL, 'The path to the migrations files to use', Migrate::DEFAULT_PATH);
    }

    /**
     * Execute command, captain.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $options = [
            'step' => $input->getOption('step')
        ];

        $migrate = Migrate::new($input->getOption('dsn'), $input->getOption('path'), $output);
        $migrate
            ->rollback($options)
            ->close();
    }
}


<?php

namespace DreamFactory\Core\Email\Components;

use DreamFactory\Core\Email\Models\EmailServiceParameterConfig;
use DreamFactory\Core\Exceptions\BadRequestException;

trait SupportsEmailParameters
{
    /**
     * @return array|null
     */
    public static function getConfigSchema()
    {
        $schema = parent::getConfigSchema();
        $schema[] = [
            'name'        => 'parameters',
            'label'       => 'Parameters',
            'description' => 'Supply additional parameters to be replace in the email body.',
            'type'        => 'array',
            'required'    => false,
            'allow_null'  => true,
            'items'       => EmailServiceParameterConfig::getConfigSchema(),
        ];

        return $schema;
    }

    /**
     * {@inheritdoc}
     */
    public static function getConfig($id, $local_config = null, $protect = true)
    {
        $config = parent::getConfig($id, $local_config, $protect);

        /** @var EmailServiceParameterConfig $params */
        $params = EmailServiceParameterConfig::whereServiceId($id)->get();
        $config['parameters'] = $params->toArray();

        return $config;
    }

    /**
     * {@inheritdoc}
     */
    public static function setConfig($id, $config, $local_config = null)
    {
        if (isset($config['parameters'])) {
            $params = $config['parameters'];
            if (!is_array($params)) {
                throw new BadRequestException('Web service parameters must be an array.');
            }
            EmailServiceParameterConfig::whereServiceId($id)->delete();
            foreach ($params as $param) {
                EmailServiceParameterConfig::setConfig($id, $param, $local_config);
            }
            unset($config['parameters']);
        }

        return parent::setConfig($id, $config, $local_config);
    }

    /**
     * {@inheritdoc}
     */
    public static function storeConfig($id, $config)
    {
        if (isset($config['parameters'])) {
            $params = (array)$config['parameters'];
            EmailServiceParameterConfig::whereServiceId($id)->delete();
            foreach ($params as $param) {
                EmailServiceParameterConfig::storeConfig($id, $param);
            }
            unset($config['parameters']);
        }

        return parent::storeConfig($id, $config);
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Psr\Container\ContainerInterface;
use Roquie\Database\Migration\Migrate;
use Roquie\Database\Seed\Seed;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Roquie\Database\Migration\Creator\MigrationCreatorInterface as M;

class MigrateFreshCommand extends Command
{
    /**
     * @var \Psr\Container\ContainerInterface
     */
    private $container;

    /**
     * MigrateFreshCommand constructor.
     *
     * @param \Psr\Container\ContainerInterface $container
     */
    public function __construct(ContainerInterface $container = null)
    {
        $this->container = $container;
        parent::__construct();
    }

    protected function configure()
    {
        $this
            ->setName('migrate:fresh')
            ->setDescription('Drop all tables and re-run all migrations')
            ->setHelp('Example of usage: rdb migrate:fresh --dsn pgsql:dbname=test;host=localhost;user=root');

        $this
            ->addOption('dsn', 'd', InputOption::VALUE_REQUIRED, 'DNS string for connect with database.')
            ->addOption('seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.')
            ->addOption('path', null, InputOption::VALUE_OPTIONAL, 'The path to the migrations files to use', Migrate::DEFAULT_PATH);
    }

    /**
     * Execute command, captain.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|null|void
     * @throws \Invoker\Exception\InvocationException
     * @throws \Invoker\Exception\NotCallableException
     * @throws \Invoker\Exception\NotEnoughParametersException
     * @throws \League\Flysystem\FileNotFoundException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $migrate = Migrate::new($input->getOption('dsn'), $input->getOption('path'), $output);

        $files = $migrate->getMigrator()->getMigrationFiles(M::TYPE_UP);
        $migrate->drop();

        if (count($files) < 1) {
            $output->writeln('');
            $output->writeln('<comment>Migration files not found</comment>');
            return;
        }

        $migrate
            ->install()
            ->run()
            ->close();

        if ($input->getOption('seed')) {
            $this->getSeed($input, $output)
                 ->run()
                 ->close();
        }

        $output->writeln('');
        $output->writeln('<comment>Completed.</comment>');
    }

    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return \Roquie\Database\Seed\Seed
     */
    private function getSeed(InputInterface $input, OutputInterface $output)
    {
        $seed = Seed::new($input->getOption('dsn'), Seed::DEFAULT_PATH, $output);
        if ($this->container instanceof ContainerInterface) {
            $seed->setContainer($this->container);
        }

        return $seed;
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\VariableSummaryModal;

use Propel\Runtime\Collection\ObjectCollection;
use Wakers\BaseModule\Component\Frontend\BaseControl;
use Wakers\StructureModule\Database\Recipe;
use Wakers\StructureModule\Database\RecipeVariable;
use Wakers\StructureModule\Repository\RecipeRepository;
use Wakers\StructureModule\Repository\RecipeVariableRepository;

class VariableSummaryModal extends BaseControl
{
    /**
     * @var RecipeRepository
     */
    protected $recipeRepository;

    /**
     * @var RecipeVariableRepository
     */
    protected $variableRepository;

    /**
     * @var callable
     */
    public $onOpen = [];

    /**
     * Entita
     * @var Recipe
     */
    protected $recipe;

    /**
     * Variables z Entity $recipe
     * @var ObjectCollection|RecipeVariable[]
     */
    protected $variables;

    /**
     * @var int
     * @persistent
     */
    public $recipeId;

    /**
     * VariableSummaryModal constructor.
     * @param RecipeRepository $recipeRepository
     * @param RecipeVariableRepository $recipeVariableRepository
     */
    public function __construct(RecipeRepository $recipeRepository, RecipeVariableRepository $recipeVariableRepository)
    {
        $this->recipeRepository = $recipeRepository;
        $this->variableRepository = $recipeVariableRepository;
    }

    /**
     * Render
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function render() : void
    {
        if ($this->recipeId)
        {
            $this->recipe = $this->recipeRepository->findOneById($this->recipeId);
            $this->variables = $this->variableRepository->findByRecipe($this->recipe);
        }

        $this->template->recipe = $this->recipe;
        $this->template->variables = $this->variables;
        $this->template->setFile(__DIR__.'/templates/variableSummaryModal.latte');
        $this->template->render();
    }

    /**
     * Handle Open
     * @param int $recipeId
     */
    public function handleOpen(int $recipeId) : void
    {
        if ($this->presenter->isAjax())
        {
            $this->recipeId = $recipeId;
            $this->presenter->handleModalToggle('show', '#wakers_structure_variable_summary_modal', FALSE);
            $this->onOpen();
        }
    }
}


<?php

namespace PhalApi\Request\Formatter;

use PhalApi\Contracts\Request\Formatter;
use PhalApi\Exceptions\InternalServerError;

class CallableFormatter extends BaseFormatter implements Formatter
{
    /**
     * 对回调类型进行格式化
     *
     * @param mixed $value 变量值
     * @param array $rule ['callback' => '回调函数', 'params' => '第三个参数']
     * @throws InternalServerError
     * @return boolean|string 格式化后的变量
     */
    public function parse($value, $rule)
    {
        if (!isset($rule['callback']) || !is_callable($rule['callback'])) {
            throw new InternalServerError(
                T('invalid callback for rule: {name}', ['name' => $rule['name']])
            );
        }

        if (isset($rule['params'])) {
            return call_user_func($rule['callback'], $value, $rule, $rule['params']);
        } else {
            return call_user_func($rule['callback'], $value, $rule);
        }
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Aware;

/**
 * TagAwareTrait
 *
 * One implementation of TagAwareInterface
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @see     TagAwareInterface
 * @version 2.0.0
 * @since   2.0.0 added
 */
trait TagAwareTrait
{
    /**
     * associate array (for speed consideration) of tags
     *
     * @var    array
     * @access private
     */
    private $tags = [];

    /**
     * Add a single tag
     *
     * @param  string $tag
     * @return $this
     * @access public
     * @api
     */
    public function addTag(/*# string */ $tag)
    {
        $this->tags[(string) $tag] = true;
        return $this;
    }

    /**
     * Has this tag ?
     *
     * @param  string $tag
     * @return bool
     * @access public
     * @api
     */
    public function hasTag(/*# string */ $tag)/*# : bool */
    {
        return isset($this->tags[(string) $tag]);
    }

    /**
     * Remove one tag
     *
     * @param  string $tag
     * @return $this
     * @access public
     * @api
     */
    public function removeTag(/*# string */ $tag)
    {
        unset($this->tags[(string) $tag]);
        return $this;
    }

    /**
     * Set/replace all tags, empty array to clear all tags
     *
     * @param  array $tags like ['apple', 'orange']
     * @return $this
     * @access public
     * @api
     */
    public function setTags(array $tags)
    {
        $this->tags = array_flip($tags);
        return $this;
    }

    /**
     * Get all tags in array
     *
     * @return array
     * @access public
     * @api
     */
    public function getTags()/*# : array */
    {
        return array_keys($this->tags);
    }

    /**
     * Return array of tags existed, return empty [] if no match found
     *
     * @param  array $tags tags to match against
     * @return array
     * @access public
     * @api
     */
    public function hasTags(array $tags)/*# : array */
    {
        $x = [];
        foreach ($tags as $tag) {
            if ($this->hasTag($tag)) {
                $x[] = $tag;
            }
        }
        return $x;
    }
}


<?php

/**
 * ExtDirect\Annotations\Collections\RemotableCollection
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to version 3 of the GPL license,
 * that is bundled with this package in the file LICENSE, and is
 * available online at http://www.gnu.org/licenses/gpl.txt
 *
 * PHP version 5
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

namespace ExtDirect\Annotations\Collections;

use ExtDirect\Collections\Collection;
use ExtDirect\Annotations\Interfaces\MethodInterface;
use ExtDirect\Exceptions\ExtDirectException;

/**
 * class RemotableCollection
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

class RemotableCollection extends Collection implements \IteratorAggregate
{
    /**
     * Adds a remote able instance to the collection
     *
     * @param MethodInterface $method the remote able instance
     *
     * @return void
     * @throws ExtDirectException
     */
    public function add(MethodInterface $method)
    {
        if ($this->isUnique($method)) {
            $this->collection[] = $method;
        } else {
            throw new ExtDirectException("Remotable methodname {$method->getAnnotatedName()} already exists, but have to be unique");
        }
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Roquie\Database\Migration\Migrate;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class MigrateRefreshCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('migrate:refresh')
            ->setDescription('Reset and re-run all migrations')
            ->setHelp('Example of usage: rdb migrate:refresh --dsn pgsql:dbname=test;host=localhost;user=root');

        $this
            ->addOption('dsn', 'd', InputOption::VALUE_REQUIRED, 'DNS string for connect with database.')
            ->addOption('step', null, InputOption::VALUE_OPTIONAL, 'Force the migrations to be run so they can be rolled back individually', 0)
            ->addOption('path', null, InputOption::VALUE_OPTIONAL, 'The path to the migrations files to use', Migrate::DEFAULT_PATH);
    }

    /**
     * Execute command, captain.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $migrate = Migrate::new($input->getOption('dsn'), $input->getOption('path'), $output);

        if (! $migrate->exists()) {
            $output->writeln('<info>Migration table not found.</info>');
            return;
        }

        $step = $input->getOption('step');

        $step > 0 ? $migrate->rollback(compact('step')) : $migrate->reset();

        $migrate
            ->run()
            ->close();

        $output->writeln('');
        $output->writeln('<comment>Done</comment>');
    }
}


<?php
namespace Volantus\FlightBase\Src\General\FlightController;

use Volantus\FlightBase\Src\Server\Messaging\IncomingMessage;
use Volantus\FlightBase\Src\Server\Messaging\MessageFactory;
use Volantus\FlightBase\Src\Server\Network\NetworkRawMessage;

/**
 * Class PIDFrequencyStatusMessageFactory
 *
 * @package Volantus\FlightBase\Src\General\FlightController
 */
class PIDFrequencyStatusMessageFactory extends MessageFactory
{
    /**
     * @var string
     */
    protected $type = PIDFrequencyStatus::TYPE;

    /**
     * @param NetworkRawMessage $rawMessage
     *
     * @return IncomingPIDFrequencyStatus|IncomingMessage
     */
    public function create(NetworkRawMessage $rawMessage): IncomingMessage
    {
        $data = $rawMessage->getData();
        $this->validateNumeric($data, 'desired');
        $this->validateNumeric($data, 'current');

        return new IncomingPIDFrequencyStatus($rawMessage->getSender(), new PIDFrequencyStatus($data['desired'], $data['current']));
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Psr\Container\ContainerInterface;
use Roquie\Database\Migration\Whois;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\ConsoleOutput;

final class Console
{
    /**
     * Run console application.
     *
     * @param $argv
     * @param \Psr\Container\ContainerInterface|null $container
     * @throws \Exception
     */
    public static function main($argv, ContainerInterface $container = null)
    {
        $output = self::cyanLine($argv);

        $app = new Application('');
        $app->add(new MigrateMakeCommand());
        $app->add(new MigrateUpCommand($container));
        $app->add(new MigrateDownCommand());
        $app->add(new MigrateResetCommand());
        $app->add(new MigrateStatusCommand());
        $app->add(new MigrateRefreshCommand());
        $app->add(new MigrateFreshCommand($container));
        $app->add(new MigrateDropCommand());
        $app->add(new SeedRunCommand($container));
        $app->add(new SeedMakeCommand());
        $app->add(new BinMakeCommand());

        $app->run(null, $output);
    }

    /**
     * @param $argv
     * @return \Symfony\Component\Console\Output\ConsoleOutput
     */
    private static function cyanLine($argv): ConsoleOutput
    {
        $output = new ConsoleOutput();
        $output->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan'));

        if (self::isPrint($argv)) {
            $output->writeln(Whois::WHOIS);
            $output->writeln('');
        }

        return $output;
    }

    /**
     * @param $argv
     * @return bool
     */
    private static function isPrint($argv): bool
    {
        return (isset($argv[1]) && in_array($argv[1], ['list', 'help'], true))
            || empty($argv[1]);
    }
}


<?php
namespace Volantus\FlightBase\Src\General\Motor;

use Volantus\FlightBase\Src\General\GyroStatus\GyroStatus;
use Volantus\FlightBase\Src\Server\Messaging\IncomingMessage;
use Volantus\FlightBase\Src\Server\Messaging\MessageFactory;
use Volantus\FlightBase\Src\Server\Network\NetworkRawMessage;

/**
 * Class MotorControlMessageFactory
 *
 * @package Volantus\FlightBase\Src\General\Motor
 */
class MotorControlMessageFactory extends MessageFactory
{
    /**
     * @var string
     */
    protected $type = MotorControlMessage::TYPE;

    /**
     * @param NetworkRawMessage $rawMessage
     *
     * @return IncomingMessage|IncomingMotorControlMessage
     */
    public function create(NetworkRawMessage $rawMessage): IncomingMessage
    {
        $data = $rawMessage->getData();
        $this->validateArray($data, 'desiredPosition');
        $this->validateNumeric($data['desiredPosition'], 'yaw');
        $this->validateNumeric($data['desiredPosition'], 'roll');
        $this->validateNumeric($data['desiredPosition'], 'pitch');

        $this->validateNumeric($data, 'horizontalThrottle');
        $this->validateNumeric($data, 'verticalThrottle');
        $this->validateBool($data, 'motorsStarted');

        $gyroStatus = new GyroStatus($data['desiredPosition']['yaw'], $data['desiredPosition']['roll'], $data['desiredPosition']['pitch']);
        $motorControl = new MotorControlMessage($gyroStatus, $data['horizontalThrottle'], $data['verticalThrottle'], $data['motorsStarted']);

        return new IncomingMotorControlMessage($rawMessage->getSender(), $motorControl);
    }
}


<?php

/**
 * ExtDirect\Collections\Collection
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to version 3 of the GPL license,
 * that is bundled with this package in the file LICENSE, and is
 * available online at http://www.gnu.org/licenses/gpl.txt
 *
 * PHP version 5
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

namespace ExtDirect\Collections;

/**
 * class Collection
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

class Collection
{
    /**
     * Holds the entities
     *
     * @var array
     */
    protected $collection = array();

    /**
     * Returns the collection iterator
     *
     * @return CollectionIterator
     */
    public function getIterator()
    {
        return new CollectionIterator($this->collection);
    }

    /**
     * checks if annotated name does not exist already
     *
     * @param mixed $instance the direct instance
     *
     * @return bool
     */
    protected function isUnique($instance)
    {
        foreach ($this->getCollection() as $entry) {
            if ($entry->getAnnotatedName() === $instance->getAnnotatedName()) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns the collection array
     *
     * @return array
     */
    protected function getCollection()
    {
        return $this->collection;
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Player_Guide
{
	public static function addPublicMessage ($template, $data, $character = 'guide', $mood = 'neutral', $highlight = '')
	{
		$db = Neuron_DB_Database::getInstance ();

		$data = Neuron_GameServer_LogSerializer::encode ($data);

		$players = $db->query
		("
			SELECT
				plid
			FROM
				n_players
			WHERE
				removalDate IS NULL
		");

		foreach ($players as $v)
		{
			$db->query
			("
				INSERT INTO
					n_players_guide
				SET
					plid = {$v['plid']},
					pg_template = '{$db->escape ($template)}',
					pg_character = '{$db->escape ($character)}',
					pg_mood = '{$db->escape ($mood)}',
					pg_data = '{$db->escape ($data)}',
					pg_highlight = '{$db->escape ($highlight)}'
			");
		}
	}

	public function __construct (Neuron_GameServer_Player $profile)
	{
		$this->objProfile = $profile;
	}

	/*
		Quests
	*/
	public function addMessage ($template, $data, $character = 'guide', $mood = 'neutral', $highlight = '')
	{
		$db = Neuron_DB_Database::getInstance ();

		$data = Neuron_GameServer_LogSerializer::encode ($data);

		$db->query
		("
			INSERT INTO
				n_players_guide
			SET
				plid = {$this->objProfile->getId ()},
				pg_template = '{$db->escape ($template)}',
				pg_character = '{$db->escape ($character)}',
				pg_mood = '{$db->escape ($mood)}',
				pg_data = '{$db->escape ($data)}',
				pg_highlight = '{$db->escape ($highlight)}'
		");
	}

	public function setAllRead ()
	{
		$db = Neuron_DB_Database::getInstance ();

		$db->query
		("
			UPDATE
				n_players_guide
			SET
				pg_read = '1'
			WHERE
				plid = {$this->objProfile->getId ()}
		");
	}

	public function removeMessages ()
	{
		$db = Neuron_DB_Database::getInstance ();

		$db->query
		("
			DELETE FROM
				n_players_guide
			WHERE
				plid = {$this->objProfile->getId ()}
		");
	}

	public function __destruct ()
	{
		unset ($this->objProfile);
	}
}
?>


<?php
namespace Cora;

class Load extends Framework
{
    protected $neverOutput;
    public function __construct($neverOutput = false)
    {
        parent::__construct(); // Call parent constructor too so we don't lose functionality.

        $this->neverOutput = $neverOutput;
    }

    /**
     *  For echo'ing data in Views only if that data is set.
     */
    public function ifset(&$property)
    {
        if (isset($property))
            echo $property;
        else
            echo '';
    }

    /**
     *  For echo'ing data in Views that repeats.
     */
    public function repeat(&$property, $repeatTag, $classes = '', $outerTag = false, $outerClasses = '')
    {
        if (isset($property)) {
            $output = '';
            if ($outerTag) { $output .= '<'.$outerTag.' class="'.$outerClasses.'">'; }
            if (is_array($property)) {
                foreach ($property as $value) {
                    $output .= '<'.$repeatTag.' class="'.$classes.'">';
                    $output .= $value;
                    $output .= '</'.$repeatTag.'>';
                }
            }
            else {
                $output .= '<'.$repeatTag.' class="'.$classes.'">';
                $output .= $property;
                $output .= '</'.$repeatTag.'>';
            }
            if ($outerTag) { $output .= '</'.$outerTag.'>'; }
            echo $output;
        }
        else
            echo '';
    }

    /**
     *  Include specified model.
     *
     *  This is included for people that like to specifically load their classes.
     *  It's recommended you not use this and just let the autoloader handle
     *  model loading.
     */
    public function model($pathname) {
        $fullPath = $this->config['pathToModels'] .
                    $this->getPath($pathname) .
                    $this->config['modelsPrefix'] .
                    $this->getName($pathname) .
                    $this->config['modelsPostfix'] .
                    '.php';
        include_once($fullPath);
    }

    /**
     *  Include specified library. - Depreciated. Now let's autoloading handle the file include.
     *
     *  if a reference to the calling class is passed in, then the specified library
     *  will be invoked and a reference passed back to the calling class.
     *
     *  If $exposeToView is set to true along with a reference to the calling class,
     *  then the library will be loaded into the calling controller's Data field
     *  for use within a View file.
     */
    public function library($pathname, &$caller = false, $exposeToView = false) {

        $name = $this->getName($pathname);
        $path = $this->getPath($pathname);

        // If a reference to the calling object was passed, set an instance of
        // the library as one of its members.
        if ($caller) {

            // If no namespace is given, default to Cora namespace.
            if ($this->getPathBackslash($pathname) == '') {
                $lib = '\\Cora\\'.$name;
            }
            else {
                $lib = $pathname;
            }

            $libObj = new $lib($caller);

            // Set library to be available within a class via "$this->$libraryName"
            $caller->$name = $libObj;

            // Set library to also be available via "$this->load->$libraryName"
            // This is so this library will be available within View files as $libraryName.
            if ($exposeToView)
                $caller->setData($name, $libObj);
        }

    }

    /**
     *  Load view OR return view depending on 2nd parameter.
     */
    public function view($pathname = '', $data = false, $return = false) {

        if (is_array($data) || is_object($data)) {
            foreach ($data as $key => $value) {
                $$key = $value;
            }
        }

        // If no pathname specified, grab template name.
        if ($pathname == '') {
            $pathname = $this->config['template'];
        }

        $fullPath = $this->config['pathToViews'] .
                    $this->getPath($pathname);
        $path = $this->getPath($pathname);

        $this->debug('Full Path: '.$fullPath);

        $fileName = $this->config['viewsPrefix'] .
                    $this->getName($pathname) .
                    $this->config['viewsPostfix'] .
                    '.php';

        // Determine full filepath to View
        //$filePath = $fullPath . $fileName;

        $filePath = $this->_getFilePath($pathname, $fileName);

        // Debug
        $this->debug('');
        $this->debug( 'Searching for View: ');
        $this->debug( 'View Name: ' . $this->getName($pathname) );
        $this->debug( 'View Path: ' . $this->getPath($pathname) );
        $this->debug( 'File Path: ' . $filePath);
        $this->debug('');

        // Either return the view for storage in a variable, or output to browser.
        if ($return || $this->neverOutput) {
            ob_start();
            $inc = include($filePath);

            // If in dev mode and the include failed, throw an exception.
            if ($inc == false && $this->config['mode'] == 'development') {
                throw new \Exception("Can't find file '$fileName' using path '$filePath'");
            }
            return ob_get_clean();
        }
        else {
            $inc = include($filePath);

            // If in dev mode and the include failed, throw an exception.
            if ($inc == false && $this->config['mode'] == 'development') {
                throw new \Exception("Can't find file '$fileName' using path '$filePath'");
            }
        }
    }

    protected function _getFilePath($pathname, $fileName)
    {
        $path_steps = explode('/', $this->getPath($pathname));
        do {
            $path = implode('/', $path_steps);
            if (file_exists($this->config['pathToViews'] . $this->getPath($path) . $fileName)) {
                return $this->config['pathToViews'] . $this->getPath($path) . $fileName;
            }
            array_pop($path_steps);
        } while (count($path_steps) > 0);
    }
} // end class


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Attribute;

/**
 * StaticVarTrait
 *
 * Dealing with class' static array variable
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @version 2.0.28
 * @since   2.0.28 added
 */
trait StaticVarTrait
{
    /**
     * Get MERGED/REPLACED static variable for CURRENT class
     *
     * @param  string $staticVarName static variable name
     * @return array
     * @access protected
     * @static
     */
    protected static function getStaticVar($staticVarName)/*# : array */
    {
        $class = get_called_class();
        $parent = get_parent_class($class);

        // get current class' static variable
        $res = $class::${$staticVarName};

        // merge with ancestor class' same static variable
        if ($parent && property_exists($parent, $staticVarName)) {
            $res = $parent::getStaticVar($staticVarName);
            if ($class::${$staticVarName} != $parent::${$staticVarName}) {
                $res = array_replace_recursive($res, $class::${$staticVarName});
            }
        }

        return $res;
    }

    /**
     * Merge/replace static var with given array of values
     *
     * @param  array $var given values
     * @param  string $staticVarName static variable name
     * @return array
     * @access protected
     */
    protected function initStaticVar(
        array $var,
        /*# string */ $staticVarName
    )/*# : array */ {
        return array_replace_recursive(
            static::getStaticVar($staticVarName),
            $var
        );
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Migration;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use Roquie\Database\Migration\Creator\CreatorFactory;
use Roquie\Database\Migration\Creator\MigrationCreatorInterface;
use Roquie\Database\Notify\NotifyFactory;
use Roquie\Database\Notify\NotifyInterface;

class Creator
{
    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    /**
     * @var MigrationCreatorInterface
     */
    private $creator;

    /**
     * @var \Roquie\Database\Notify\NotifyInterface|string
     */
    private $notify;

    /**
     * Creator constructor.
     *
     * @param MigrationCreatorInterface $creator
     * @param FilesystemInterface $filesystem
     * @param \Roquie\Database\Notify\NotifyInterface|string $notify
     */
    public function __construct(
        MigrationCreatorInterface $creator,
        FilesystemInterface $filesystem,
        $notify = NotifyInterface::LOGGER
    )
    {
        $note = $notify instanceof NotifyInterface
            ? $notify
            : NotifyFactory::create($notify);

        $this->creator = $creator;
        $this->filesystem = $filesystem;
        $this->notify = $note;
    }

    /**
     * Create a Creator object with default values.
     *
     * @param string $type
     * @param string $path
     * @param \Roquie\Database\Notify\NotifyInterface|string $notify
     * @return \Roquie\Database\Migration\Creator
     */
    public static function new(
        string $type = 'default',
        string $path = Migrate::DEFAULT_PATH,
        $notify = NotifyInterface::LOGGER
    ): Creator
    {
        $fs = new Filesystem(new Local($path));
        $note = NotifyFactory::create($notify);

        return new static(CreatorFactory::create($type, $note), $fs, $note);
    }

    /**
     * Create a new migration.
     *
     * @param string $name
     * @param null|string $table
     * @param bool $create
     * @return void
     */
    public function create(string $name, ?string $table = null, bool $create = false): void
    {
        Whois::print($this->getNotify());

        $this->creator->create($this->filesystem, ...func_get_args());
    }

    /**
     * @return \Roquie\Database\Notify\NotifyInterface|string
     */
    public function getNotify()
    {
        return $this->notify;
    }

    /**
     * @return MigrationCreatorInterface
     */
    public function getCreator(): MigrationCreatorInterface
    {
        return $this->creator;
    }

    /**
     * @return FilesystemInterface
     */
    public function getFilesystem(): FilesystemInterface
    {
        return $this->filesystem;
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Map_Pathfinder
{
	private $map;

	public function __construct ()
	{

	}

	/**
	*	Set the map in an assoc array.
	*/
	public function setMap ($assocMapArray)
	{
		$this->map = $assocMapArray;
	}

	/**
	*	Check if a this location is passable
	*/
	private function isPassable ($x, $y)
	{
		return $this->getCost ($x, $y) > 0;
	}

	/**
	*	Get the amount of points required to
	*	pass this point (or zero if impassable)
	*/
	private function getCost ($x, $y)
	{
		return isset ($this->map[$y]) && isset ($this->map[$y][$x])
			? $this->map[$y][$x] : 0;
	}

	/**
	*	Calculate and return the path
	*/
	public function getPath
	(
		Neuron_GameServer_Map_Location $start,
		Neuron_GameServer_Map_Location $end
	)
	{
		// Start here :-)
		$x1 = $start[0];
		$y1 = $start[1];

		$x2 = $end[0];
		$y2 = $end[1];

		if (!$this->isPassable ($x2, $y2))
		{
			return false;
		}

		$astar = $this->astar ($start, $end);

		//var_dump ($astar);
		//exit;

		return $astar;
	}

	private function getHeuristics ($loc1, $loc2)
	{
		$h = $this->distance ($loc1[0], $loc1[1], $loc2[0], $loc2[1]);
		return $h;
	}

	private function distance ($x1, $y1, $x2, $y2)
	{
		return sqrt (pow ($x1 - $x2, 2) + pow ($y1 - $y2, 2) );
	}

	private function astar (Neuron_GameServer_Map_Location $start, Neuron_GameServer_Map_Location $destination)
	{
		$came_from = array ();

		$g = array ();
		$h = array ();
		$f = array ();
		$d = array ();

		$start = array ($start[0], $start[1]);
		$destination = array ($destination[0], $destination[1]);

		$k = $this->getKeyName ($start);

		$closed = array ();
		$open = array ($k => $start);

		$g[$k] = 0;
		$h[$k] = $this->distance ($start[0], $start[1], $destination[0], $destination[1]);
		$f[$k] = $h[$k];
		$d[$k] = 0;

		$i = 0;

		while (count ($open) > 0)
		{
			// Fetch the lowest $f
			$tmp = array_keys ($open);
			$fk = $tmp[0];

			foreach ($open as $k => $v)
			{
				if ($f[$k] < $f[$fk])
				{
					$fk = $k;
				}
			}

			$x = $open[$fk];

			// This is the end... my only friend, the end.
			if ($x[0] == $destination[0] && $x[1] == $destination[1])
			{
				$route = array ($destination);
				$route[0]['d'] = 0;

				$this->getRoute ($came_from, $fk, $route);

				//return array ($g[$fk], $route);
				return new Neuron_GameServer_Map_Path ($route, $g[$fk]);
			}

			else
			{
				// Remove from open, put in closed.
				unset ($open[$fk]);
				$closed[$fk] = $x;

				$neighbours = $this->getNeighbourNodes ($x, $destination);

				foreach ($neighbours as $k => $v)
				{
					$cost = $g[$fk] + $v['cost'];

					if (isset ($open[$k]) && $cost < $g[$k])
					{
						unset ($open[$k]);
					}

					if (isset ($closed[$k]) && $cost < $g[$k])
					{
						unset ($closed[$k]);
					}

					if (!isset ($open[$k]) && !isset ($closed[$k]))
					{
						$g[$k] = $cost;
						$open[$k] = $v['key'];
						$f[$k] = $g[$k] + $v['heuristics'];

						$came_from[$k] = $x;
						$came_from[$k]['d'] = $v['cost'];
					}
				}
			}

			$i ++;
		}

		return false;
	}

	private function getNeighbourNodes ($l, $destination)
	{
		$out = array ();

		$x = $l[0];
		$y = $l[1];

		$this->addNeighbourNode ($out, $x + 1, $y + 0, $destination);
		$this->addNeighbourNode ($out, $x - 1, $y + 0, $destination);
		$this->addNeighbourNode ($out, $x + 0, $y + 1, $destination);
		$this->addNeighbourNode ($out, $x + 0, $y - 1, $destination);

		return $out;
	}

	private function addNeighbourNode (&$out, $x, $y, $destination)
	{
		$c = $this->getCost ($x, $y);
		if ($c > 0)
		{
			$out[$this->getKeyName (array ($x, $y))] = array (
				'key' => array ($x, $y),
				'cost' => $c,
				'heuristics' => $this->getHeuristics (array ($x, $y), $destination)
			);
		}
	}

	private function getRoute ($came_from, $k, &$array)
	{
		if (isset ($came_from[$k]))
		{
			$array[] = $came_from[$k];
			$this->getRoute ($came_from, $this->getKeyName ($came_from[$k]), $array);
		}
		return;
	}

	private function getKeyName ($loc)
	{
		return $loc[0] . '|' . $loc[1];
	}

	private function straightline (Neuron_GameServer_Map_Location $start, Neuron_GameServer_Map_Location $end)
	{
		// Make array of path and calculate the total cost
		$path = array ();

		// Start here :-)
		$x1 = $start[0];
		$y1 = $start[1];

		$x2 = $end[0];
		$y2 = $end[1];

		$x = $x1;
		$y = $y1;

		while (($x != $x2 || $y != $y2) && count ($path) < 2500)
		{
			$tx = $x - $x2;
			$ty = $y - $y2;

			if (abs ($tx) > abs ($ty))
			{
				$x -= $tx > 0 ? 1 : -1;
			}
			else
			{
				$y -= $ty > 0 ? 1 : -1;
			}

			$path[] = array ($x, $y);
		}

		$cost = count ($path);

		return new Neuron_GameServer_Map_Path ($path, $cost);
	}
}


<?php

namespace Herrera\Template;

use ArrayObject;
use Exception;
use Herrera\FileLocator\Collection;
use Herrera\FileLocator\Locator\FileSystemLocator;
use Herrera\FileLocator\Locator\LocatorInterface;
use Herrera\Template\Exception\TemplateNotFoundException;

/**
 * Renders content using regular PHP scripts.
 *
 * @author Kevin Herrera <kevin@herrera.io>
 */
class Engine extends ArrayObject
{
    /**
     * The template file locator.
     *
     * @var LocatorInterface
     */
    private $locator;

    /**
     * Sets the template file locator.
     *
     * @param LocatorInterface $locator The locator.
     */
    public function __construct(LocatorInterface $locator = null)
    {
        if (null === $locator) {
            $locator = new Collection();
        }

        $this->locator = $locator;
    }

    /**
     * Creates a new instance for the directory path(s).
     *
     * @param array|string The directory path(s).
     *
     * @return Engine The new instance.
     */
    public static function create($path)
    {
        $engine = new self();

        /** @var $locator Collection*/
        $locator = $engine->getLocator();

        $locator->add(new FileSystemLocator($path));

        return $engine;
    }

    /**
     * Renders a template and displays the result.
     *
     * @param string  $template The name of the template.
     * @param array   $vars     The template variables.
     *
     * @throws TemplateNotFoundException If the template does not exist.
     */
    public function display($template, array $vars = array())
    {
        if (null === ($path = $this->locator->locate($template))) {
            throw TemplateNotFoundException::format(
                'The template "%s" does not exist.',
                $template
            );
        }

        $this->renderInScope(
            $path,
            array_replace($this->getArrayCopy(), $vars)
        );
    }

    /**
     * Returns the template file locator.
     *
     * @return LocatorInterface The locator.
     */
    public function getLocator()
    {
        return $this->locator;
    }

    /**
     * Renders a template and returns the result.
     *
     * @param string  $template The name of the template.
     * @param array   $vars     The template variables.
     *
     * @return string The template rendering.
     */
    public function render($template, array $vars = array())
    {
        ob_start();

        try {
            $this->display($template, $vars);
        } catch (Exception $exception) {
            ob_end_clean();

            throw $exception;
        }

        return ob_get_clean();
    }

    /**
     * Sets the template file locator.
     *
     * @param LocatorInterface $locator The locator.
     */
    public function setLocator(LocatorInterface $locator)
    {
        $this->locator = $locator;
    }

    /**
     * Renders the template in its own scope.
     *
     * @param string $__file__ The template file path.
     * @param array  $var      The template variables.
     */
    private function renderInScope($__file__, $var)
    {
        extract($var, EXTR_SKIP);

        include $__file__;
    }
}


<?php
namespace Volantus\FlightBase\Src\General\Motor;

use Volantus\FlightBase\Src\Server\Messaging\IncomingMessage;
use Volantus\FlightBase\Src\Server\Messaging\MessageFactory;
use Volantus\FlightBase\Src\Server\Network\NetworkRawMessage;

/**
 * Class MotorStatusMessageFactory
 * @package Volantus\FlightBase\Src\General\Motor
 */
class MotorStatusMessageFactory extends MessageFactory
{
    /**
     * @var string
     */
    protected $type = MotorStatus::TYPE;

    /**
     * @param NetworkRawMessage $rawMessage
     *
     * @return IncomingMotorStatusMessage|IncomingMessage
     */
    public function create(NetworkRawMessage $rawMessage): IncomingMessage
    {
        $data = $rawMessage->getData();
        $this->validateArray($data, 'motors');

        $motors = [];
        foreach ($data['motors'] as $motor) {
            $this->validateNumeric($motor, 'id');
            $this->validateNumeric($motor, 'pin');
            $this->validateNumeric($motor, 'power');

            $motors[] = new Motor($motor['id'], $motor['power'], $motor['pin']);
        }

        return new IncomingMotorStatusMessage($rawMessage->getSender(), new MotorStatus($motors));
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Shareable;

use Phossa2\Shared\Message\Message;
use Phossa2\Shared\Exception\RuntimeException;

/**
 * Implementation of ShareableInterface
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @see     ShareableInterface
 * @version 2.0.10
 * @since   2.0.10 added
 */
trait ShareableTrait
{
    /**
     * Shareables' pool
     *
     * @var    ShareableInstance[]
     * @access protected
     * @staticvar
     */
    protected static $shareables = [];

    /**
     * Is this shared instance, store its $scope here
     *
     * @var    string
     * @access protected
     */
    protected $shared_in;

    /**
     * Scopes of this instance belongs to
     *
     * @var    string[]
     * @access protected
     */
    protected $scopes = [];

    /*
     * {@inheritDoc}
     */
    public static function getShareable(
        /*# string */ $scope = ''
    )/*# : ShareableInterface */ {
        if (!static::hasShareable($scope)) {
            (new static())->setShareable($scope);
        }
        return self::$shareables[get_called_class()][$scope];
    }

    /**
     * {@inheritDoc}
     */
    public static function getScopes()/*# : array */
    {
        if (isset(self::$shareables[get_called_class()])) {
            return array_keys(self::$shareables[get_called_class()]);
        } else {
            return [];
        }
    }

    /**
     * {@inheritDoc}
     */
    public function setShareable(/*# string */ $scope = '')
    {
        // this $scope has shareable already or $this is a shareable
        if (static::hasShareable($scope) || $this->isShareable() !== false) {
            throw new RuntimeException(
                Message::get(Message::MSG_SHAREABLE_FAIL, $scope),
                Message::MSG_SHAREABLE_FAIL
            );
        }

        $this->shared_in = $scope;
        self::$shareables[get_class($this)][$scope] = $this;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function isShareable()
    {
        return is_null($this->shared_in) ? false : $this->shared_in;
    }

    /**
     * {@inheritDoc}
     */
    public function addScope(/*# string */ $scope)
    {
        if ($this->isShareable() === false &&
            !in_array($scope, $this->scopes)
        ) {
            $this->scopes[] = $scope;
        }
        return $this;
    }

    /**
     * Checking with $scope explicitly
     *
     * {@inheritDoc}
     */
    public function hasScope(/*# string */ $scope = '')/*# : bool */
    {
        return in_array($scope, $this->getOwnScopes());
    }

    /**
     * {@inheritDoc}
     */
    public function getShareables()/*# : array */
    {
        $result = [];
        if (false === $this->isShareable()) {
            foreach ($this->getOwnScopes() as $scope) {
                $result[] = static::getShareable($scope);
            }
        }
        return $result;
    }

    /**
     * Test existense of shareable in $scope
     *
     * @param  string $scope
     * @return bool
     * @access protected
     */
    protected static function hasShareable(
        /*# string */ $scope = ''
    )/*# : bool */ {
        return isset(self::$shareables[get_called_class()][$scope]);
    }

    /**
     * Get all unique scopes for $this
     *
     * @return array
     * @access protected
     */
    protected function getOwnScopes()/*# : array */
    {
        // alway add global scope ''
        if (!in_array('', $this->scopes)) {
            $this->addScope('');
        }
        return $this->scopes;
    }
}


<?php

namespace Shapecode\Twig\Extensions\Collector;

/**
 * Class Collector
 *
 * @package Shapecode\Twig\Extensions\Collector
 * @author  Nikita Loges
 */
class Collector
{

    /** @var array */
    protected $collections = [];

    /** @var Collector */
    protected static $instance;

    /**
     */
    protected function __construct()
    {

    }

    /**
     * @return Collector
     */
    public function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Collector();
        }

        return self::$instance;
    }

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

    /**
     * @param $name
     *
     * @return string
     */
    public function get($name)
    {
        if (!isset($this->collections[$name])) {
            return '';
        }

        return implode(' ', $this->collections[$name]);
    }
}


<?php
/**
 * NotFound
 *
 * PHP version 7+
 *
 * Copyright (c) 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
 *
 * @category  Resty
 * @package   Resty\Handler
 * @author    Federico Lozada Mosto <mosto.federico@gmail.com>
 * @copyright 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * @license   MIT License (http://www.opensource.org/licenses/mit-license.php)
 * @link      http://www.mostofreddy.com.ar
 */
namespace Resty\Slim\Handler;
// Resty
use Resty\Slim\Handler\AbstracErrorHandler;
// PSR
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
// Resty - JsonApiError
use Resty\JsonApiError\Message;

/**
 * NotFound
 *
 * @category  Resty
 * @package   Resty\Handler
 * @author    Federico Lozada Mosto <mosto.federico@gmail.com>
 * @copyright 2016 Federico Lozada Mosto <mosto.federico@gmail.com>
 * @license   MIT License (http://www.opensource.org/licenses/mit-license.php)
 * @link      http://www.mostofreddy.com.ar
 *
 * @codeCoverageIgnore
 */
class NotAllowed extends AbstracErrorHandler
{
    const HTTP_STATUS = 405;
    const TITLE = 'Method Not Allowed';

    /**
     * Invoca la respuesta
     *
     * @param ServerRequestInterface $request  Instancia de ServerRequestInterface
     * @param ResponseInterface      $response Instancia de ResponseInterface
     * @param array                  $methods  Array de metodos http disponibles
     *
     * @return mixed
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods = [])
    {
        return $this->response(
            $response,
            $this->render($request, $methods)
        );
    }
    /**
     * Renderiza el mensaje de error
     *
     * @param ServerRequestInterface $request Instancia de Request
     * @param array                  $methods Array de metodos http disponibles
     *
     * @return Message
     */
    protected function render(ServerRequestInterface $request, array $methods):Message
    {
        $detail = 'Request => '.$request->getMethod().":".$request->getUri()->__toString()
            .'. Method not allowed. Must be one of '.implode(", ", $methods);
        $message = new Message();
        $message->add(static::TITLE, $detail)
            ->setStatus(static::HTTP_STATUS);

        return $message;
    }
}


<?php

namespace MASNathan\APICaller;

use MASNathan\Parser\Parser;
use Psr\Http\Message\ResponseInterface;

/**
 * Class Caller
 *
 * @package MASNathan\APICaller
 */
abstract class Caller
{
    /**
     * @var Client
     */
    protected $client;

    /**
     * Caller constructor.
     *
     * @param Client $client APICaller Client Instance
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
        $this->client->init();
    }

    /**
     * Handles the body content of a response
     *
     * @param ResponseInterface $response    Response instance
     * @param string|null       $contentType Content Type
     *
     * @return array|string
     */
    protected function handleResponseContent(ResponseInterface $response, $contentType = null)
    {
        $contents = $response->getBody()->getContents();

        if (!$contentType) {
            $contentTypeHeaderLine = $response->getHeaderLine('Content-Type');

            if (stripos($contentTypeHeaderLine, 'application/json') !== false) {
                $contentType = 'json';
            } elseif (stripos($contentTypeHeaderLine, 'application/xml') !== false) {
                $contentType = 'xml';
            }
        }

        if ($contentType) {
            return Parser::data($contents)->from($contentType)->toArray();
        }

        return $contents;
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }
}


<?php

namespace MASNathan\APICaller\Clients;

use Http\Client\Common\HttpMethodsClient as HttpMethodsClientParent;
use MASNathan\APICaller\Operation;
use Psr\Http\Message\RequestInterface;

class HttpMethodsClient extends HttpMethodsClientParent
{
    /**
     * @var Operation
     */
    protected $lastOperation;

    /**
     * Forward to the underlying HttpClient.
     *
     * {@inheritdoc}
     */
    public function sendRequest(RequestInterface $request)
    {
        $this->lastOperation = new Operation($request);

        $response = parent::sendRequest($request);

        $this->lastOperation->setResponse($response);

        return $response;
    }

    /**
     * @return Operation
     */
    public function getLastOperation()
    {
        return $this->lastOperation;
    }
}


<?php

namespace Renegare\SilexCSH;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;

class CookieSessionHandler implements \SessionHandlerInterface {

    /** @var Request */
    protected $request;

    /** @var string */
    protected $name;
    protected $path;
    protected $domain;

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

    /** @var bool */
    protected $secure;
    protected $httpOnly;

    /**
     * @var mixed(false|null|Cookie) - effects getCookie return value
     * > false - means no cookie was accessed|written too and therefore no cookie will be returned
     * > null - means cookie was destroyed
     * > Cookie - means some data has been written and a cookie will be returned
     */
    protected $cookie = false;

    /**
     * @param string $cookieName - name of the cookie that will used to store the session
     * @param int             $lifeTime
     * @param string          $path
     * @param string          $domain
     * @param bool            $secure
     * @param bool            $httpOnly
     */
    public function __construct($cookieName, $lifeTime = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true) {
        $this->name = $cookieName;
        $this->lifeTime = $lifeTime;
        $this->path = $path;
        $this->domain = $domain;
        $this->secure = $secure;
        $this->httpOnly = $httpOnly;
    }

    /**
     * {@inheritdoc}
     */
    public function close() {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function destroy($sessionId) {
        $this->cookie = new Cookie(
            $this->name,
            null,
            strtotime('-1 hour'),
            $this->path,
            $this->domain,
            $this->secure,
            $this->httpOnly
        );

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function gc($maxLifetime) {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function open($savePath, $sessionId) {
        return $this->getRequest()
            ->cookies->has($this->name);
    }

    /**
     * {@inheritdoc}
     */
    public function read($sessionId) {
        $cookies = $this->getRequest()->cookies;

        $content = @unserialize($cookies->get($this->name, ''));

        if ($content === false || count($content) !== 2 ||
            !isset($content[0]) || !isset($content[1])) {
            $content = [time(), ''];
        }

        list($expire, $data) = $content;

        if($expire !== 0 && $expire < strtotime('now')) {
            return '';
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function write($sessionId, $sessionData) {
        $expire = $this->lifeTime === 0 ? 0 : strtotime('now') + $this->lifeTime;

        $this->cookie = new Cookie(
            $this->name,
            serialize([$expire, $sessionData]),
            $expire,
            $this->path,
            $this->domain,
            $this->secure,
            $this->httpOnly
        );

        return true;
    }

    /**
     * set request that holds the current cookie session
     * @param Request $request
     */
    public function setRequest(Request $request) {
        $this->request = $request;
    }

    /**
     * get request that holds the current cookie session
     * @throws RuntimeException
     * @return Request
     */
    protected function getRequest() {
        if(!$this->request) {
            throw new \RuntimeException('You cannot access the session without a Request object set');
        }
        return $this->request;
    }

    /**
     * get written cookie or a delete cookie if no cookie has been written
     * @return mixed false|null|Cookie
     */
    public function getCookie() {
        return $this->cookie;
    }

    /**
     * get cookie name
     * @return string
     */
    public function getCookieName() {
        return $this->name;
    }
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Extension;

use Phossa2\Shared\Base\ObjectAbstract;

/**
 * ExtensionAbstract
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @see     ObjectAbstract
 * @see     ExtensionInterface
 * @version 2.0.23
 * @since   2.0.23 added
 */
abstract class ExtensionAbstract extends ObjectAbstract implements ExtensionInterface
{
    /**
     * The server object
     *
     * @var    ExtensionAwareInterface
     * @access protected
     */
    protected $server;

    /**
     * The lazy boot flag
     *
     * @var    bool
     * @access protected
     */
    protected $booted = false;

    /**
     * {@inheritDoc}
     */
    public function methodsAvailable()/*# : array */
    {
        return [];
    }

    /**
     * {@inheritDoc}
     */
    public function boot(ExtensionAwareInterface $server)
    {
        if (!$this->booted) {
            // bind server
            $this->server = $server;

            // call user defined boot
            $this->bootExtension();

            // call your own bootMethod here
            $this->booted = true;
        }
    }

    /**
     * The real boot method
     *
     * @access protected
     */
    abstract protected function bootExtension();
}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa2\Shared
 * @copyright Copyright (c) 2016 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa2\Shared\Globbing;

/**
 * GlobbingTrait
 *
 * Matches exact name like 'user.login' with 'user.*', 'u*.*' etc.
 *
 * @package Phossa2\Shared
 * @author  Hong Zhang <phossa@126.com>
 * @version 2.0.25
 * @since   2.0.20 added
 * @since   2.0.25 ending '*' now matches everything
 */
trait GlobbingTrait
{
    /**
     * Returns all names matches with $exactName
     *
     * e.g.
     * 'user.login' matches '*', 'u*.*', 'user.*', 'user.l*', 'user.login' etc.
     *
     * @param  string $exactName
     * @param  array $names
     * @return array
     * @access protected
     */
    protected function globbingNames(
        /*# string */ $exactName,
        array $names
    )/*# : array */ {
        $result = [];
        foreach ($names as $name) {
            if ($this->nameGlobbing($exactName, $name)) {
                $result[] = $name;
            }
        }
        return $result;
    }

    /**
     * Check to see if $name matches with $exactName
     *
     *  e.g.
     *  ```php
     *  // true
     *  $this->nameGlobbing('user.*', 'user.login');
     *
     *  // true
     *  $this->nameGlobbing('*', 'user.login');
     *
     *  // false
     *  $this->nameGLobbing('blog.*', 'user.login');
     *  ```
     *
     * @param  string $exactName
     * @param  string $name
     * @return bool
     * @access protected
     */
    protected function nameGlobbing(
        /*# string */ $exactName,
        /*# string */ $name
    )/*# : bool */ {
        if ($name === $exactName) {
            return true;
        } elseif (false !== strpos($name, '*')) {
            $pat = str_replace(array('.', '*'), array('[.]', '[^.]*+'), $name);
            // last '*' should be different
            $pat = substr($pat, -6) != '[^.]*+' ? $pat : (substr($pat, 0, -6) . '.*+');
            return (bool) preg_match('~^' . $pat . '$~', $exactName);
        } else {
            return false;
        }
    }
}


<?php

namespace DreamFactory\Core\Email\Services;

use DreamFactory\Core\Exceptions\InternalServerErrorException;
use GuzzleHttp\Client;
use Illuminate\Mail\Transport\SparkPostTransport;

class SparkPost extends BaseService
{
    protected function setTransport($config)
    {
        $key = array_get($config, 'key');
        $options = (array)array_get($config, 'options');
        $this->transport = static::getTransport($key, $options);
    }

    /**
     * @param $key
     * @param $options
     *
     * @return \Illuminate\Mail\Transport\SparkPostTransport
     * @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
     */
    public static function getTransport($key, $options = [])
    {
        if (empty($key)) {
            throw new InternalServerErrorException('Missing key for SparkPost service.');
        }

        return new SparkPostTransport(new Client(), $key, $options);
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Migration;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use Roquie\Database\Notify\NotifyFactory;
use Roquie\Database\Notify\NotifyInterface;
use Roquie\Database\DatabaseFactory;
use Roquie\Database\Migration\Repository\MigrationRepositoryFactory;
use Roquie\Database\Migration\Repository\MigrationRepositoryInterface;

class Migrate
{
    public const DEFAULT_PATH = 'database/migrations';
    public const CHANNEL = 'Rdb';

    /**
     * @var FilesystemInterface
     */
    private $filesystem;

    /**
     * @var \Roquie\Database\Migration\Repository\MigrationRepositoryInterface
     */
    private $migrationRepository;

    /**
     * @var \Roquie\Database\Notify\NotifyInterface
     */
    private $notify;

    /**
     * Migrate constructor.
     *
     * @param string|object $database
     * @param \League\Flysystem\FilesystemInterface|null $filesystem
     * @param \Roquie\Database\Notify\NotifyInterface|string $notify
     */
    public function __construct($database, FilesystemInterface $filesystem, $notify = 'logger')
    {
        $this->migrationRepository = $this->repo($database);
        $this->filesystem = $filesystem;
        $this->notify = NotifyFactory::create($notify);
    }

    /**
     * @param $database
     * @param null|string $source
     * @param NotifyInterface|string|null $notify
     * @return \Roquie\Database\Migration\Migrate
     */
    public static function new($database, ?string $source = self::DEFAULT_PATH, $notify = 'logger')
    {
        $migrator = new static($database, new Filesystem(new Local($source)), $notify);

        return $migrator;
    }

    /**
     * Returns true if migrations table exists.
     *
     * @return bool
     */
    public function exists(): bool
    {
        Whois::print($this->getNotify());

        return $this->migrationRepository->repositoryExists();
    }

    /**
     * Drop all tables and views in the database.
     *
     * @return \Roquie\Database\Migration\Migrate
     */
    public function drop(): Migrate
    {
        Whois::print($this->getNotify());

        $this->getMigrator()->drop();

        return $this;
    }

    /**
     * Create the migration repository if table does not exists.
     */
    public function install(): Migrate
    {
        Whois::print($this->getNotify());

        // Create a migration table in the
        // database if it does not exist.
        $this->exists() || $this->migrationRepository->createRepository();

        return $this;
    }

    /**
     * @param array $options
     * @return \Roquie\Database\Migration\Migrate
     */
    public function run(array $options = []): Migrate
    {
        Whois::print($this->getNotify());

        $this->getMigrator()->migrate($options);

        return $this;
    }

    /**
     * @param array $options
     * @return \Roquie\Database\Migration\Migrate
     */
    public function rollback(array $options = []): Migrate
    {
        Whois::print($this->getNotify());

        $this->getMigrator()->rollback($options);

        return $this;
    }

    /**
     * @return \Roquie\Database\Migration\Migrate
     */
    public function reset(): Migrate
    {
        Whois::print($this->getNotify());

        $this->getMigrator()->reset();

        return $this;
    }

    /**
     * Close database connection after all operations.
     */
    public function close(): void
    {
        $this->getMigrationRepository()->close();
    }

    /**
     * @return \Roquie\Database\Notify\NotifyInterface
     */
    public function getNotify(): NotifyInterface
    {
        return $this->notify;
    }

    /**
     * @return \Roquie\Database\Migration\Repository\MigrationRepositoryInterface
     */
    public function getMigrationRepository(): MigrationRepositoryInterface
    {
        return $this->migrationRepository;
    }

    /**
     * @return FilesystemInterface
     */
    public function getFilesystem(): FilesystemInterface
    {
        return $this->filesystem;
    }

    /**
     * @return \Roquie\Database\Migration\Migrator
     */
    public function getMigrator()
    {
        return new Migrator(
            $this->getMigrationRepository(),
            $this->getFilesystem(),
            $this->getNotify()
        );
    }

    /**
     * @param $database
     * @return \Roquie\Database\Migration\Repository\MigrationRepositoryInterface
     * @throws \Roquie\Database\Exception\InvalidArgumentException
     * @throws \Roquie\Database\Migration\Exception\InvalidArgumentException
     */
    protected function repo($database): MigrationRepositoryInterface
    {
        if (is_object($database)) {
            return MigrationRepositoryFactory::create($database);
        }

        return MigrationRepositoryFactory::create(
            DatabaseFactory::create($database)
        );
    }
}


<?php

/**
 * ExtDirect\ExtDirectResponse
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to version 3 of the GPL license,
 * that is bundled with this package in the file LICENSE, and is
 * available online at http://www.gnu.org/licenses/gpl.txt
 *
 * PHP version 5
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

namespace ExtDirect;

/**
 * class ExtDirectResponse
 *
 * @category  ExtDirect
 * @package   ExtDirect
 * @author    Philipp Dittert <philipp.dittert@gmail.com>
 * @copyright 2015 Philipp Dittert
 * @license   http://www.gnu.org/licenses/gpl.txt GNU General Public License, version 3 (GPL-3.0)
 * @link      https://github.com/dittertp/ExtDirect
 */

class ExtDirectResponse extends AbstractExtDirect
{
    /**
     * @var array
     */
    protected $result;

    /**
     * constructor to overwrite abstract constructor
     */
    public function __construct()
    {
    }

    /**
     * Sets request result
     *
     * @param array $result the request result as array
     *
     * @return void
     */
    public function setResult($result)
    {
        $this->result = $result;
    }

    /**
     * Returns request result
     *
     * @return array
     */
    protected function getResult()
    {
        return $this->result;
    }

    /**
     * Returns response as array
     *
     * @return array
     */
    public function getResultAsArray()
    {
        return $this->buildResponse();
    }

    /**
     * build a valid ext direct response and returns as array
     *
     * @return array
     */
    protected function buildResponse()
    {
        $res = array();
        $res['type'] = $this->getParameters()->getType();
        $res['tid'] = $this->getParameters()->getTid();
        $res['action'] = $this->getParameters()->getAction();
        $res['method'] = $this->getParameters()->getMethod();
        $res['result'] = $this->getResult();

        return $res;
    }
}


<?php
/**
 * Copyright (c) 2018 Wakers.cz
 *
 * @author Jiří Zapletal (http://www.wakers.cz, zapletal@wakers.cz)
 *
 */

namespace Wakers\StructureModule\Component\Frontend\RecipeSlugRemoveModal;

trait Create
{
    /**
     * @var IRecipeSlugRemoveModal
     * @inject
     */
    public $IStructure_RecipeSlugRemoveModal;

    /**
     * Modální okno pro odstranění
     * @return RecipeSlugRemoveModal
     */
    protected function createComponentStructureRecipeSlugRemoveModal() : object
    {
        $control = $this->IStructure_RecipeSlugRemoveModal->create();

        $control->onRemove[] = function ()
        {
            $this->getComponent('structureRecipeSlugModal')->redrawControl('modal'); // SA
            $this->getComponent('structureRecipeSlugModal')->redrawControl('slugForm');
            $this->getComponent('structureRecipeSlugModal')->redrawControl('slugSummary');

            $this->getComponent('structureRecipeSummaryModal')->redrawControl('modal');
        };

        $control->onOpen[] = function () use ($control)
        {
            $control->redrawControl('modal');
        };

        return $control;
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Console;

use Roquie\Database\Migration\Creator;
use Roquie\Database\Migration\Migrate;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class MigrateMakeCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('make:migration')
            ->setDescription('Create a new migration files')
            ->setHelp('Example of usage: rdb make:migration create_users_table --create users');

        $this
            ->addArgument('name', InputArgument::REQUIRED, 'The name of the migration')
            ->addOption('type', null, InputOption::VALUE_OPTIONAL, 'Database type.', 'default')
            ->addOption('create', 'c', InputOption::VALUE_OPTIONAL, 'The table to be created', false)
            ->addOption('table', 't', InputOption::VALUE_OPTIONAL, 'The table to migrate')
            ->addOption('path', 'p', InputOption::VALUE_OPTIONAL, 'The location where the migration file should be created', Migrate::DEFAULT_PATH);
    }

    /**
     * Execute command, captain.
     *
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return int|null|void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = trim($input->getArgument('name'));
        $table = $input->getOption('table');
        $create = $input->getOption('create') ?: false;
        $path = $input->getOption('path');
        $type = $input->getOption('type');

        // If no table was given as an option but a create option is given then we
        // will use the "create" option as the table name. This allows the devs
        // to pass a table name into this option as a short-cut for creating.
        if (! $table && is_string($create)) {
            $table = $create;

            $create = true;
        }

        $creator = Creator::new($type, $path, $output);
        $creator->create($name, $table, $create);
    }
}


<?php declare(strict_types=1);

namespace Roquie\Database\Migration\Creator;

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemInterface;
use Roquie\Database\Migration\Creator\MigrationCreatorInterface as M;
use Roquie\Database\Notify\NotifyInterface;

class MigrationCreator implements MigrationCreatorInterface
{
    /**
     * @var \League\Flysystem\FilesystemInterface
     */
    private $stubs;

    /**
     * @var \Roquie\Database\Notify\NotifyInterface
     */
    private $notify;

    /**
     * MigrationCreator constructor.
     *
     * @param \Roquie\Database\Notify\NotifyInterface $notify
     */
    public function __construct(NotifyInterface $notify)
    {
        $this->stubs = new Filesystem(new Local($this->stubPath()));
        $this->notify = $notify;
    }

    /**
     * Create a new migration.
     *
     * @param \League\Flysystem\FilesystemInterface $filesystem
     * @param string $name
     * @param string $table
     * @param bool $create
     * @return void
     * @throws \League\Flysystem\FileNotFoundException
     */
    public function create(FilesystemInterface $filesystem, string $name, ?string $table = null, bool $create = false): void
    {
        foreach ($this->getStubs($table, $create) as $type => $stub) {
            $filesystem->put(
                $filename = $this->getFilename($name, $type),
                $this->populateStub($filename, $stub, $table)
            );

            $this->notify->note("<comment>Migration</comment> {$filename} <comment>created</comment>");
        }
    }

    /**
     * Get the migration stub file.
     *
     * @param  string $table
     * @param  bool $create
     * @return iterable
     * @throws \League\Flysystem\FileNotFoundException
     */
    protected function getStubs(?string $table = null, bool $create = false): iterable
    {
        if (is_null($table)) {
            yield M::TYPE_UP => $this->stubs->read('blank.sql.stub');
            yield M::TYPE_DOWN => $this->stubs->read('blank.sql.stub');
            return;
        }

        $first = [M::TYPE_UP => 'create.sql.stub', M::TYPE_DOWN => 'down.sql.stub'];
        $second = [M::TYPE_UP => 'update.sql.stub', M::TYPE_DOWN => 'update.sql.stub'];

        $stubs = $create ? $first : $second;

        foreach ($stubs as $type => $stub) {
            yield $type => $this->stubs->read($stub);
        }
    }

    /**
     * Populate the place-holders in the migration stub.
     *
     * @param  string  $filename
     * @param  string  $stub
     * @param  string  $table
     * @return string
     */
    protected function populateStub(string $filename, string $stub, ?string $table = null): string
    {
        $search = ['{name}', '{table}'];
        $replace = [$filename, $table ?: 'dummy_table'];

        return str_replace($search, $replace, $stub);
    }

    /**
     * Get the migrations file names.
     *
     * @param  string $name
     * @param string $type
     * @return string
     */
    protected function getFilename(string $name, string $type): string
    {
        return $this->getDatePrefix() . "_{$name}.{$type}.sql";
    }

    /**
     * Get the date prefix for the migration.
     *
     * @return string
     */
    protected function getDatePrefix(): string
    {
        return date('Y_m_d_His');
    }

    /**
     * Get the path to the stubs.
     *
     * @return string
     */
    protected function stubPath(): string
    {
        return __DIR__ . '/stubs';
    }
}


<?php

namespace DreamFactory\Core\Email\Components;

use DreamFactory\Core\Exceptions\BadRequestException;

trait EmailUtilities
{
    public static function sanitizeAndValidateEmails($emails, $return_format = '')
    {
        if (is_array($emails)) {
            if (isset($emails[0])) // multiple
            {
                $out = array();
                foreach ($emails as $info) {
                    if (is_array($info)) {
                        $email = array_get($info, 'email');
                        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
                        if (false === filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            throw new BadRequestException("Invalid email - '$email'.");
                        }
                        if (empty($email)) {
                            throw new BadRequestException('Email can not be empty.');
                        }
                        $name = array_get($info, 'name');
                        if (empty($name)) {
                            $out[] = $email;
                        } else {
                            switch ($return_format) {
                                case 'swift':
                                    $out[$email] = $name;
                                    break;
                                case 'wrapped': // rfc2822
                                    $out[] = $name . '<' . $email . '>';
                                    break;
                                default:
                                    $out[] = $info;
                            }
                        }
                    } else // simple email addresses
                    {
                        $info = filter_var($info, FILTER_SANITIZE_EMAIL);
                        if (false === filter_var($info, FILTER_VALIDATE_EMAIL)) {
                            throw new BadRequestException("Invalid email - '$info'.");
                        }
                        $out[] = $info;
                    }
                }
            } else // single pair
            {
                $email = array_get($emails, 'email');
                $email = filter_var($email, FILTER_SANITIZE_EMAIL);
                if (false === filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    throw new BadRequestException("Invalid email - '$email'.");
                }
                if (empty($email)) {
                    throw new BadRequestException('Email can not be empty.');
                }
                $name = array_get($emails, 'name');
                if (empty($name)) {
                    $out = $email;
                } else {
                    switch ($return_format) {
                        case 'swift':
                            $out = array($email => $name);
                            break;
                        case 'wrapped': // rfc2822
                            $out = $name . '<' . $email . '>';
                            break;
                        default:
                            $out = $emails;
                    }
                }
            }
        } else {
            // simple single email
            $emails = filter_var($emails, FILTER_SANITIZE_EMAIL);
            if (false === filter_var($emails, FILTER_VALIDATE_EMAIL)) {
                throw new BadRequestException("Invalid email - '$emails'.");
            }
            $out = $emails;
        }

        return $out;
    }

    /**
     * Applies data to email view
     *
     * @param string $view
     * @param array  $data
     *
     * @return string
     */
    public static function applyDataToView($view, $data)
    {
        // do placeholder replacement, currently {xxx}
        if (!empty($data)) {
            foreach ($data as $name => $value) {
                if (is_string($value)) {
                    // replace {xxx} in subject
                    $view = str_replace('{' . $name . '}', $value, $view);
                }
            }
        }

        return $view;
    }
}


<?php

/*
 * This file is part of the Worker package.
 *
 * (c) EXSyst
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace EXSyst\Component\Worker\Internal;

use EXSyst\Component\Worker\Exception;
use Symfony\Component\Process\ExecutableFinder;

final class IdentificationHelper
{
    private function __construct()
    {
    }

    /**
     * @param string $socketAddress
     *
     * @return bool
     */
    public static function isUnixAddress($socketAddress)
    {
        return substr_compare($socketAddress, 'unix://', 0, 7) === 0;
    }

    /**
     * @param string $socketAddress
     *
     * @return bool
     */
    public static function isLocalAddress($socketAddress)
    {
        static $localAddresses = null;
        if (self::isUnixAddress($socketAddress)) {
            return true;
        }
        if ($localAddresses === null) {
            $localAddresses = array_merge([
                '0.0.0.0',
                '127.0.0.1',
                '[::]',
                '[::1]',
            ], gethostbynamel(gethostname()));
        }
        foreach ($localAddresses as $address) {
            if (strpos($socketAddress, $address) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param string $socketAddress
     *
     * @return bool
     */
    public static function isNetworkExposedAddress($socketAddress)
    {
        if (self::isUnixAddress($socketAddress)) {
            return false;
        }
        if (strpos($socketAddress, '127.0.0.1') !== false || strpos($socketAddress, '[::1]') !== false) {
            return false;
        }

        return true;
    }

    /**
     * @param string $socketAddress
     *
     * @return string|null
     */
    public static function getSocketFile($socketAddress)
    {
        return self::isUnixAddress($socketAddress) ? substr($socketAddress, 7) : null;
    }

    /**
     * @param string $socketAddress
     *
     * @return string
     */
    public static function stripScheme($socketAddress)
    {
        $pos = strpos($socketAddress, '://');

        return ($pos === false) ? $socketAddress : substr($socketAddress, $pos + 3);
    }

    /**
     * @param string $socketAddress
     *
     * @throws Exception\RuntimeException
     *
     * @return int|null
     */
    public static function getListeningProcessId($socketAddress)
    {
        if (!self::isLocalAddress($socketAddress)) {
            return;
        }
        $lsofPath = self::findLsof();
        $unix = self::isUnixAddress($socketAddress);
        $lsofArgs = self::buildLsofArgs($socketAddress, $unix);
        exec(escapeshellarg($lsofPath).' '.$lsofArgs.' 2>/dev/null', $output, $exitCode);
        if ($exitCode !== 0 || $output === null) {
            return;
        }
        if ($unix) {
            return self::findProcessIdFromLsofOutput($output);
        } else {
            return self::findListeningProcessIdFromLsofOutput($output);
        }
    }

    /**
     * @param bool $includeStdIO
     *
     * @throws Exception\RuntimeException
     *
     * @return array
     */
    public static function getMyFileDescriptors($includeStdIO = true)
    {
        $lsofPath = self::findLsof();
        exec(escapeshellarg($lsofPath).' -F f -p '.getmypid(), $output, $exitCode);
        if ($exitCode !== 0 || $output === null) {
            return [];
        }
        $output = array_map('trim', $output);
        $output = array_values(array_filter($output, function ($line) {
            return preg_match('#^f\\d+$#', $line);
        }));
        $fds = array_map(function ($line) {
            return intval(substr($line, 1));
        }, $output);
        sort($fds);
        if (!$includeStdIO) {
            $fds = self::removeStdIO($fds);
        }

        return $fds;
    }

    /**
     * @throws Exception\RuntimeException
     *
     * @return string
     */
    private static function findLsof()
    {
        $finder = new ExecutableFinder();
        $lsofPath = $finder->find('lsof', null, ['/sbin', '/usr/sbin']);
        if ($lsofPath === null) {
            throw new Exception\RuntimeException('Unable to find the "lsof" executable.');
        }

        return $lsofPath;
    }

    /**
     * @param string $socketAddress
     * @param bool   $unix
     *
     * @return string
     */
    private static function buildLsofArgs($socketAddress, $unix)
    {
        $schemeless = self::stripScheme($socketAddress);

        return $unix ? ('-F p0 '.escapeshellarg($schemeless)) : ('-F pT0 -i tcp@'.escapeshellarg($schemeless));
    }

    /**
     * @param array $output
     *
     * @return int|null
     */
    private static function findProcessIdFromLsofOutput(array $output)
    {
        foreach ($output as $line) {
            if (substr_compare($line, 'p', 0, 1) === 0) {
                return intval(substr($line, 1));
            }
        }
    }

    /**
     * @param array $output
     *
     * @return int|null
     */
    private static function findListeningProcessIdFromLsofOutput(array $output)
    {
        $pid = null;
        foreach ($output as $line) {
            if (substr_compare($line, 'p', 0, 1) === 0) {
                $pid = intval(substr($line, 1));
            }
            $record = explode("\0", $line);
            if (in_array('TST=LISTEN', $record)) {
                return $pid;
            }
        }
    }

    /**
     * @param array $fds
     *
     * @return array
     */
    private static function removeStdIO(array $fds)
    {
        foreach ($fds as $i => $fd) {
            if ($fd > 2) {
                return array_slice($fds, $i);
            }
        }

        return $fds;
    }
}


<?php
/**
 *  Dolumar engine, php/html MMORTS engine
 *  Copyright (C) 2009 Thijs Van der Schaeghe
 *  CatLab Interactive bvba, Gent, Belgium
 *  http://www.catlab.eu/
 *  http://www.dolumar.com/
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

class Neuron_GameServer_Player_Quests
{
	public function __construct (Neuron_GameServer_Player $profile)
	{
		$this->objProfile = $profile;
	}

	/*
		Quests
	*/
	public function addQuest (Neuron_GameServer_Quest $quest)
	{
		$db = Neuron_DB_Database::getInstance ();

		// Check if this is the only one
		$chk = $db->query
		("
			SELECT
				plid
			FROM
				n_players_quests
			WHERE
				plid = {$this->objProfile->getId ()} AND
				q_id = {$quest->getId ()}
		");

		if (count ($chk) == 0)
		{
			$db->query
			("
				INSERT INTO
					n_players_quests
				SET
					plid = {$this->objProfile->getId ()},
					q_id = {$quest->getId ()}
			");
		}

		$quest->onStart ($this->objProfile);
	}

	public function getPendingQuests ()
	{
		return $this->getQuests (true);
	}

	public function getFinishedQuests ()
	{
		return $this->getQuests (false);
	}

	public function getQuests ($pending = true)
	{
		$db = Neuron_DB_Database::getInstance ();

		$data = $db->query
		("
			SELECT
				*
			FROM
				n_players_quests
			WHERE
				plid = {$this->objProfile->getId ()} AND q_finished = '".($pending ? 0 : 1)."'
		");

		$out = array ();
		foreach ($data as $v)
		{
			$out[] = Neuron_GameServer_Quest::getFromId ($v['q_id']);
		}
		return $out;
	}

	public function removeQuests ()
	{
		$db = Neuron_DB_Database::getInstance ();

		$db->query
		("
			DELETE FROM
				n_players_quests
			WHERE
				plid = {$this->objProfile->getId ()}
		");
	}

	public function evaluate ()
	{
		$db = Neuron_DB_Database::getInstance ();

		foreach ($this->getPendingQuests () as $v)
		{
			if ($v->isFinished ($this->objProfile))
			{
				$v->onComplete ($this->objProfile);

				$db->query
				("
					UPDATE
						n_players_quests
					SET
						q_finished = '1'
					WHERE
						q_id = {$v->getId ()} AND
						plid = {$this->objProfile->getId ()}
				");
			}
		}
	}

	public function __destruct ()
	{
		unset ($this->objProfile);
	}
}
?>


<?php
namespace Cyberhouse\Phpstyle\Fixer;

/*
 * This file is (c) 2017 by Cyberhouse GmbH
 *
 * It is free software; you can redistribute it and/or
 * modify it under the terms of the MIT License (MIT)
 *
 * For the full copyright and license information see
 * <https://opensource.org/licenses/MIT>
 */

use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Utils;

/**
 * Base for custom fixers
 *
 * @author Georg Großberger <georg.grossberger@cyberhouse.at>
 */
abstract class BaseFixer implements FixerInterface
{
    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isMonolithicPhp();
    }

    /**
     * {@inheritdoc}
     */
    public function isRisky()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(\SplFileInfo $file)
    {
        return $file->getExtension() === 'php';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        $nameParts = explode('\\', get_called_class());
        $name = mb_substr(end($nameParts), 0, -mb_strlen('Fixer'));

        return 'Cyberhouse/' . Utils::camelCaseToUnderscore($name);
    }
}