<?php
/**
 * TeamSpeak Plugin - Connect to a TeamSpeak 3 server
 * Original work by refreshfr
 *
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLivePlugins\Standard\TeamSpeak;

use ManiaLive\Event\Dispatcher;
use ManiaLive\Application\Listener as AppListener;
use ManiaLive\Application\Event as AppEvent;
use ManiaLive\Features\Tick\Listener as TickListener;
use ManiaLive\Features\Tick\Event as TickEvent;
use ManiaLive\Threading\ThreadHandler;
use ManiaLivePlugins\Standard\TeamSpeak\Structures\Client;
use ManiaLivePlugins\Standard\TeamSpeak\Structures\Channel;
use ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\TeamSpeak3;

/**
 * Description of Connection
 */
class Connection extends \ManiaLib\Utils\Singleton implements AppListener, TickListener
{
	private $server;
	private $playersGroupId;
	private $privilegeKeys = array();

	private $processHandler;
	private $processId;

	private $tick = 0;

	function open()
	{
		$config = Config::getInstance();
		try
		{
			$this->server = TeamSpeak3::factory('serverquery://'.$config->queryLogin.':'.$config->queryPassword.'@'.$config->queryHost.':'.$config->queryPort.'/?server_port='.$config->voicePort.'&blocking=0#no_query_clients');
			$this->server->execute('instanceedit', array(
				'serverinstance_serverquery_flood_commands' => 20,
				'serverinstance_serverquery_flood_time' => 1,
				'serverinstance_serverquery_flood_ban_time' => 1));
		}
		catch(\Exception $e)
		{
			$this->server = null;
			return;
		}

		// Threading is really useful for this plugin !!!
		$this->processHandler = ThreadHandler::getInstance();
		$this->processId = $this->processHandler->launchThread();

		// Enable events (from ML and from TS)
		Dispatcher::register(AppEvent::getClass(), $this, AppEvent::ON_PRE_LOOP);
		Dispatcher::register(TickEvent::getClass(), $this);
		$this->server->notifyRegister('channel');

		// Find players group id or create a new group for privilege keys
		foreach($this->server->serverGroupList() as $group)
		{
			if($group['name'] == 'ManiaPlanet Player')
			{
				$this->playersGroupId = $group['sgid'];
				break;
			}
		}
		$this->server->serverGroupListReset();
		if(!$this->playersGroupId)
		{
			$this->playersGroupId = $this->server->serverGroupCreate('ManiaPlanet Player');
			foreach($config->groupPermissions as $permission => $value)
				$this->server->serverGroupPermAssign($this->playersGroupId, $permission, $value);
		}
		else
		{
			// Find existing tokens to avoid duplicates
			try
			{
				foreach($this->server->privilegeKeyList() as $token => $tokenInfo)
				{
					if(!$tokenInfo['token_type'] && $tokenInfo['token_id1'] == $this->playersGroupId
							&& preg_match('/`([a-z\._-]{1,25})`$/', $tokenInfo['token_description'], $matches))
						$this->privilegeKeys[$matches[1]] = $token;
				}
			}
			catch(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\ServerQuery\Exception $e)
			{
				/* thanks for launching exception instead of just returning an empty array... */
			}
		}

		// Populate
		foreach($this->server->channelList() as $channel)
			new Channel($channel, $this->getChannelPermissionList($channel));
		foreach($this->server->clientList() as $client)
			new Client($client, $this->getCustomInfo($client));

		// Handle default channels
		$this->createChannelsIFN();
	}

	function isConnected()
	{
		return $this->server != null;
	}

	function createChannelsIFN()
	{
		$config = Config::getInstance();
		if(Channel::$serverIds[Channel::FREE_TALK])
		{
			if(!Channel::$serverIds[Channel::COMMENTS])
				$this->processHandler->addTask(
						$this->processId,
						new Tasks\ChannelCreate($config, 'Comments', Channel::$serverIds[Channel::FREE_TALK], TeamSpeak::BASIC_POWER)
				);

			if(!Channel::$serverIds[Channel::TEAM_1])
				$this->processHandler->addTask(
						$this->processId,
						new Tasks\ChannelCreate($config, 'Team 1', Channel::$serverIds[Channel::FREE_TALK], 0, TeamSpeak::BASIC_POWER),
						array($this, 'onChannelCreated')
				);

			if(!Channel::$serverIds[Channel::TEAM_2])
				$this->processHandler->addTask(
						$this->processId,
						new Tasks\ChannelCreate($config, 'Team 2', Channel::$serverIds[Channel::FREE_TALK], 0, TeamSpeak::BASIC_POWER+1),
						array($this, 'onChannelCreated')
				);
		}
		else
			$this->processHandler->addTask(
					$this->processId,
					new Tasks\ChannelCreate($config, $config->serverChannelName),
					array($this, 'createChannelsIFN')
			);
	}

	// Hack because we can't set needed join power at channel creation
	// and no event is launched when needed join power is modified...
	function onChannelCreated($command)
	{
		$channelId = $command->getResult();
		$channel = $this->server->request('channelinfo cid='.$channelId)->toList();
		$channel['cid'] = $channelId;
		new Channel($channel, $this->getChannelPermissionList($channel));
	}

	function getCustomInfo($client)
	{
		try
		{
			$infoArray = $this->server->customInfo($client['client_database_id']);
			$customInfo = array();
			foreach($infoArray as $info)
				$customInfo[strval($info['ident'])] = strval($info['value']);

			return $customInfo;
		}
		catch(\Exception $e)
		{
			return array();
		}
	}

	function getChannelPermissionList($channel)
	{
		try
		{
			return $this->server->channelPermList($channel['cid'], true);
		}
		catch(\Exception $e)
		{
			return array();
		}
	}

	function getToken($login)
	{
		if(!isset($this->privilegeKeys[$login]))
			$this->privilegeKeys[$login] = $this->server->privilegeKeyCreate(
					TeamSpeak3::TOKEN_SERVERGROUP, $this->playersGroupId, 0,
					'Created by ManiaLive to authenticate `'.$login.'`',
					'ident=maniaplanet_login value='.$login);
		return $this->privilegeKeys[$login];
	}

	function useToken($login)
	{
		if(isset($this->privilegeKeys[$login]))
			unset($this->privilegeKeys[$login]);
	}

	function deleteToken($login)
	{
		if(isset($this->privilegeKeys[$login]))
		{
			$this->server->privilegeKeyDelete($this->privilegeKeys[$login]);
			unset($this->privilegeKeys[$login]);
		}
	}

	function moveClient($clientId, $channelId)
	{
		$this->processHandler->addTask(
				$this->processId,
				new Tasks\ClientMove(Config::getInstance(), $clientId, $channelId)
		);
	}

	function movePlayer($login, $channelId)
	{
		$client = Client::GetByLogin($login);
		if($client)
			$this->moveClient($client->clientId, $channelId);
	}

	function toggleClientComment($clientId, $enable=true)
	{
		$this->processHandler->addTask(
				$this->processId,
				new Tasks\ClientToggleComment(Config::getInstance(), $clientId, $enable)
		);
	}

	function close($onPurpose=true)
	{
		if($this->server)
		{
			if($onPurpose)
			{
				$this->server->notifyUnregister();
				foreach($this->privilegeKeys as $key)
					$this->server->privilegeKeyDelete($key);
			}
			$this->server->clientListReset();
			$this->server->channelListReset();
			$this->server = null;
			$this->playersGroupId = 0;
			$this->privilegeKeys = array();
		}
		if($this->processHandler && $this->processId)
		{
			$this->processHandler->killThread($this->processId);
			$this->processId = null;
		}
		Dispatcher::unregister(AppEvent::getClass(), $this);
		Dispatcher::unregister(TickEvent::getClass(), $this);
		// TODO something to avoid memory leaks when unloading the plugin
		// but the TS framework is f*cked up (plenty of circular references
		// which can't be unset from outside...)
	}

	// Events
	function onTick()
	{
		if(++$this->tick % 5 == 0)
		{
			try
			{
				if($this->tick % 60 == 0)
				{
					$this->server->request('whoami');
					$this->processHandler->addTask(
							$this->processId,
							new Tasks\ConnectionKeepAlive(Config::getInstance())
					);
				}
			}
			catch(\Exception $e)
			{
				$this->close(false);
			}
		}
	}

	function onPreLoop()
	{
		// Receiving TeamSpeak events
		try
		{
			if($this->server)
				$this->server->getAdapter()->readNotifications();
		}
		catch(\Exception $e)
		{
			$this->close(false);
		}
	}

	function onInit() {}
	function onRun() {}
	function onPostLoop() {}
	function onTerminate() {}
}

?>


<?php

namespace DevGroup\ExtensionsManager\helpers;

use cebe\markdown\GithubMarkdown;
use DevGroup\DeferredTasks\helpers\DeferredHelper;
use DevGroup\DeferredTasks\helpers\ReportingChain;
use DevGroup\DeferredTasks\helpers\ReportingTask;
use DevGroup\DeferredTasks\models\DeferredGroup;
use DevGroup\ExtensionsManager\components\ComposerInstalledSet;
use DevGroup\ExtensionsManager\ExtensionsManager;
use DevGroup\ExtensionsManager\models\Extension;
use Packagist\Api\Result\Package\Version;
use Yii;
use yii\base\Component;
use yii\helpers\Json;

class ExtensionDataHelper extends Component
{
    /** @var  string package current version */
    private static $currentVersion;

    /**
     * @param $data
     * @return string
     */
    public static function getType($data)
    {
        $type = '';
        if (true === isset($data['package']['type'])) {
            $type = $data['package']['type'];
        } elseif (true === isset($data['type'])) {
            $type = $data['type'];
        }
        return $type;
    }

    /**
     * @param array $data
     * @param $key
     * @param bool $asArray
     * @return array
     */
    public static function getInstalledExtraData($data, $key, $asArray = false)
    {
        $out = '';
        if (false === empty($data['extra'][$key])) {
            $out = $data['extra'][$key];
        }
        if (true === $asArray) {
            $out = is_array($out) ? $out : (empty($out) ? [] : [$out]);
        } else {
            $out = is_array($out) ? implode(', ', $out) : $out;
        }
        return $out;
    }

    /**
     * Fetching localized data from defined field according to package current version
     * @param $data
     * @param $type
     * @param string $field
     * @return string
     */
    public static function getLocalizedVersionedDataField($data, $type, $field)
    {
        $string = '';
        $langId = Yii::$app->language;
        if (false === empty($data['package']['versions'][self::$currentVersion]['extra'][$type][$field . '_' . $langId])) {
            $string = $data['package']['versions'][self::$currentVersion]['extra'][$type][$field . '_' . $langId];
        } elseif (false === empty($data['package']['versions'][self::$currentVersion]['extra'][$type][$field])) {
            $string = $data['package']['versions'][self::$currentVersion]['extra'][$type][$field];
        } elseif (false === empty($data['package']['versions'][self::$currentVersion][$field])) {
            $string = $data['package']['versions'][self::$currentVersion][$field];
        } elseif (false === empty($data['package'][$field])) {
            $string = $data['package'][$field];
        }
        return $string;
    }

    /**
     * Fetching localized data from defined field from for example installed.json file
     * data who has no 'versions' array inside
     * @param $data
     * @param $type
     * @param string $field
     * @return string
     */
    public static function getLocalizedDataField($data, $type, $field)
    {
        $string = '';
        $langId = Yii::$app->language;
        if (false === empty($data['extra'][$type][$field . '_' . $langId])) {
            $string = $data['extra'][$type][$field . '_' . $langId];
        } elseif (false === empty($data['extra'][$type][$field])) {
            $string = $data['extra'][$type][$field];
        } elseif (false === empty($data[$field])) {
            $string = $data[$field];
        }
        return $string;
    }

    /**
     * Fetching data from defined field according to package current version
     * @param $data
     * @param $key
     * @param bool $asArray
     * @return array
     */
    public static function getOtherPackageVersionedData($data, $key, $asArray = true)
    {
        $out = [];
        if (false === empty($data['package']['versions'][self::$currentVersion][$key])) {
            $out = $data['package']['versions'][self::$currentVersion][$key];
        }
        if (true === $asArray) {
            $out = is_array($out) ? $out : [$out];
        } else {
            $out = is_array($out) ? implode(', ', $out) : $out;
        }
        return $out;
    }

    /**
     * Fetching data from defined field from for example installed.json file
     * data who has no 'versions' array inside
     * @param $data
     * @param $key
     * @param bool $asArray
     * @return array | string
     */
    public static function getOtherPackageData($data, $key, $asArray = false)
    {
        $out = null;
        if (false === empty($data[$key])) {
            $out = $data[$key];
        }
        if (true === $asArray) {
            $out = is_array($out) ? $out : [$out];
        } else {
            $out = is_array($out) ? implode(', ', $out) : $out;
        }
        return $out;
    }

    /**
     * Humanizes github Readme.md file content
     * We adopt github retrieves Readme.md as json string where "content" field contains base64 encoded markdown
     * @param $data
     * @return string
     */
    public static function humanizeReadme($data)
    {
        $readme = '';
        $data = Json::decode($data);
        if (false === empty($data['content'])) {
            $content = base64_decode(str_replace('\n', '', $data['content']));
            $parser = new GithubMarkdown();
            $readme = $parser->parse($content);
        }
        return $readme;
    }

    /**
     * @param array $packagistVersions
     * @param array | null $gitCurrent can be item array of git releases or git tags
     * for other usages we need tag name not release name. If $gitCurrent item of releases, it must have 'tag_name' key
     * otherwise 'name' key. Release item has 'name' key too, but this is not the key we are looking for.
     * @return array
     */
    public static function getVersions($packagistVersions, $gitCurrent)
    {
        $versions = [];
        $current = '';
        if (null !== $gitCurrent) {
            if (false === empty($gitCurrent['tag_name'])) {
                $current = $gitCurrent['tag_name'];
            } elseif (false === empty($gitCurrent['name'])) {
                $current = $gitCurrent['name'];
            }
        }
        foreach ($packagistVersions as $name => $data) {
            /** @var Version $data */
            if ($current == $name) {
                $versions['current'] = $name;
            }
            $versions[$name] = $data->getTime();
        }
        if (true === empty($versions['current']) && false === empty($versions)) {
            reset($versions);
            $current = key($versions);
            $versions['current'] = $current;
        }
        self::$currentVersion = $current;
        return $versions;
    }

    /**
     * Prepares migration command
     *
     * @param array $ext
     * @param ReportingChain $chain
     * @param string $way
     * @param $group
     */
    public static function prepareMigrationTask(
        array $ext,
        ReportingChain $chain,
        $way = ExtensionsManager::MIGRATE_TYPE_UP,
        $group
    ) {

        if ($ext['composer_type'] == Extension::TYPE_DOTPLANT) {
            $extData = ComposerInstalledSet::get()->getInstalled($ext['composer_name']);
            $packageMigrations = ExtensionDataHelper::getInstalledExtraData($extData, 'migrationPath', true);
            $packagePath = '@vendor' . '/' . $ext['composer_name'] . '/';
            foreach ($packageMigrations as $migrationPath) {
                $migrateTask = self::buildTask(
                    [
                        realpath(Yii::getAlias('@app') . '/yii'),
                        'migrate/' . $way,
                        '--migrationPath=' . $packagePath . $migrationPath,
                        '--color=0',
                        '--interactive=0',
                        '--disableLookup=true',
                        (ExtensionsManager::MIGRATE_TYPE_DOWN == $way ? 68888 : ''),
                    ],
                    $group
                );
                $chain->addTask($migrateTask);
            }
        }
    }

    /**
     * Builds ReportingTask and places it into certain group. Also if group is not exists yet, it will be created
     * with necessary parameters, such as group_notifications=0.
     *
     * @param array $command
     * @param string $groupName
     * @return ReportingTask
     */
    public static function buildTask($command, $groupName)
    {
        $groupConfig = [
            'email_notification' => 0,
            'allow_parallel_run' => 0,
            'group_notifications' => 0,
            'run_last_command_only' => 0,
        ];
        if (null === $group = DeferredGroup::findOne(['name' => $groupName])) {
            $group = new DeferredGroup();
            $group->loadDefaultValues();
            $group->setAttributes($groupConfig);
            $group->name = $groupName;
            $group->save();
        }
        if ((int)$group->group_notifications !== 0) {
            // otherwise DeferredController 'deferred-queue-complete' event will not trigger
            // and we'll unable to write config
            $group->setAttributes($groupConfig);
            $group->save(array_keys($groupConfig));
        }
        $task = new ReportingTask();
        $task->model()->deferred_group_id = $group->id;
        $task->cliCommand(DeferredHelper::getPhpBinary(), $command);
        return $task;
    }
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\Entity\Follow;
use Shoko\TwitchApiBundle\Model\Entity\GameList;

/**
 * Class FollowFactory.
 */
class FollowFactory implements FactoryInterface
{
    /**
     * @param array $data
     * @param false|Follow $follow
     *
     * @return Follow
     */
    public function createEntity(array $data, $follow = false)
    {
        if (false === $follow) {
            $follow = Follow::create();
        }

        if (isset($data['notifications'])) {
            $follow = $follow->setNotifications($data['notifications']);
        }

        if (isset($data['created_at'])) {
            $follow = $follow->setCreatedAt(new \DateTime($data['created_at']));
        }

        if (isset($data['_links'])) {
            $follow = $follow->setLinks($data['_links']);
        }

        if (isset($data['channel'])) {
            $follow = $follow->setChannel((new ChannelFactory())->createEntity($data['channel']));
        }

        return $follow;
    }

    /**
     * @param array            $data
     * @param false|FollowList $followList
     *
     * @return FollowList
     */
    public function createList(array $data, $followList = false)
    {
        if (false === $followList) {
            $followList = FollowList::create();
        }

        if (isset($data['follows'])) {
            $followList = $followList->setFollows($this->createFollows($data['follows']));
        }

        if (isset($data['_links'])) {
            $followList = $followList->setLinks($data['_links']);
        }

        if (isset($data['_total'])) {
            $followList = $followList->setTotal($data['_total']);
        }

        return $followList;
    }

    /**
     * @param array $follows
     *
     * @return array
     */
    public function createFollows(array $follows)
    {
        $tmp = [];
        foreach ($follows as $entry) {
            $tmp[] = $this->createEntity($entry);
        }

        return $tmp;
    }

    /**
     * @param array            $data
     * @param false|GameList $gameList
     *
     * @return GameList
     */
    public function createGameList(array $data, $gameList = false)
    {
        if (false === $gameList) {
            $gameList = GameList::create();
        }

        if (isset($data['follows'])) {
            $gameList = $gameList->setGames((new TopFactory())->createRanks($data['follows']));
        }

        if (isset($data['_links'])) {
            $gameList = $gameList->setLinks($data['_links']);
        }

        if (isset($data['_total'])) {
            $gameList = $gameList->setTotal($data['_total']);
        }

        return $gameList;
    }
}


<?php declare(strict_types=1);
/**
 * HTTP Routing object.
 *
 * PHP version 7.0
 *
 * @category   fastpress
 *
 * @author     Simon Daniel <samayo@protonmail.ch>
 * @copyright  Copyright (c) 2017 Simon Daniel
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 *
 * @version    0.1.0
 */

namespace Fastpress\Routing;

/**
 * HTTP Routing object.
 *
 * @category   fastpress
 *
 * @author     Simon Daniel <samayo@protonmail.ch>
 */
class Router
{
    public $routes = [
      'GET' => [],
      'POST' => [],
      'PUT' => [],
      'DELETE' => [],
    ];

    public $patterns = [
      ':any' => '.*',
      ':id' => '[0-9]+',
      ':slug' => '[a-z-0-9\-]+',
      ':name' => '[a-zA-Z]+',
    ];

    const REGVAL = '/({:.+?})/';

    /**
     * Add new routes to $routes array.
     *
     * @param [type] $path
     * @param [type] $handler
     */
    public function any($path, $handler)
    {
        $this->addRoute('GET', $path, $handler);
        $this->addRoute('POST', $path, $handler);
        $this->addRoute('PUT', $path, $handler);
        $this->addRoute('DELETE', $path, $handler);
    }

    /**
     * Add a GET route.
     *
     * @param [type] $path
     * @param [type] $handler
     */
    public function get($path, $handler)
    {
        $this->addRoute('GET', $path, $handler);
    }

    /**
     * Add a POST route.
     *
     * @param [type] $path
     * @param [type] $handler
     */
    public function post($path, $handler)
    {
        $this->addRoute('POST', $path, $handler);
    }

    /**
     * Add a PUT route.
     *
     * @param [type] $path
     * @param [type] $handler
     */
    public function put($path, $handler)
    {
        $this->addRoute('PUT', $path, $handler);
    }

    /**
     * Add a DELETE route.
     *
     * @param [type] $path
     * @param [type] $handler
     */
    public function delete($path, $handler)
    {
        $this->addRoute('DELETE', $path, $handler);
    }

    /**
     * Add a route to $routes.
     *
     * @param [type] $method
     * @param [type] $path
     * @param [type] $handler
     */
    protected function addRoute($method, $path, $handler)
    {
        array_push($this->routes[$method], [$path => $handler]);
    }

    /**
     * Match if URL matches a route definition.
     *
     * @param array $server
     * @param array $post
     */
    public function match(array $server = [], array $post)
    {
        $requestMethod = $server['REQUEST_METHOD'];
        $requestUri = $server['REQUEST_URI'];

        $restMethod = $this->getRestfullMethod($post);

        // check if REST request is made
        if (null === $restMethod && !in_array($requestMethod, array_keys($this->routes))) {
            return false;
        }

        $method = $restMethod ?: $requestMethod;

        foreach ($this->routes[$method]  as $resource) {
            $args = [];
            $route = key($resource);
            $handler = reset($resource);

            if (preg_match(self::REGVAL, $route)) {
                list($args, , $route) = $this->parseRegexRoute($requestUri, $route);
            }

            if (!preg_match("#^$route$#", $requestUri)) {
                unset($this->routes[$method]);
                continue;
            }

            if (is_string($handler) && strpos($handler, '@')) {
                list($ctrl, $method) = explode('@', $handler);

                return ['controller' => $ctrl, 'method' => $method, 'args' => $args];
            }

            if (empty($args)) {
                return $handler();
            }

            return call_user_func_array($handler, $args);
        }
    }

    /**
     * Check and return a REST request (if defined).
     *
     * @param [type] $postVar
     */
    protected function getRestfullMethod($postVar)
    {
        if (array_key_exists('_method', $postVar)) {
            $method = strtoupper($postVar['_method']);
            if (in_array($method, array_keys($this->routes))) {
                return $method;
            }
        }
    }

    /**
     * Regex parser for named routes.
     *
     * @param [type] $requestUri
     * @param [type] $resource
     */
    protected function parseRegexRoute($requestUri, $resource)
    {
        $route = preg_replace_callback(self::REGVAL, function ($matches) {
            $patterns = $this->patterns;
            $matches[0] = str_replace(['{', '}'], '', $matches[0]);
            if (in_array($matches[0], array_keys($patterns))) {
                return  $patterns[$matches[0]];
            }
        }, $resource);

        $regUri = explode('/', $resource);
        $args = array_diff(
              array_replace(
                  $regUri,
              explode('/', $requestUri)
            ),
            $regUri
          );

        return [array_values($args), $resource, $route];
    }
}


<?php

namespace Shoko\TwitchApiBundle\Factory;

use Shoko\TwitchApiBundle\Model\Entity\Root;

/**
 * Class RootFactory.
 */
class RootFactory implements FactoryInterface
{
    /**
     * @param array $data
     * @param false|Root $root
     *
     * @return Root
     */
    public function createEntity(array $data, $root = false)
    {
        if (false === $root) {
            $root = Root::create();
        }

        if (isset($data['token'])) {
            $root = $root->setToken((new TokenFactory())->createEntity($data['token']));
        }

        if (isset($data['_links'])) {
            $root = $root->setLinks($data['_links']);
        }

        return $root;
    }
}


<?php declare(strict_types=1);
/**
 * HTTP request object.
 *
 * PHP version 7.0
 *
 * @category   fastpress
 *
 * @author     Simon Daniel <samayo@protonmail.ch>
 * @copyright  Copyright (c) 2017 Simon Daniel
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
 *
 * @version    0.1.0
 */

namespace Fastpress\Http;

/**
 * HTTP request object.
 *
 * @category   fastpress
 *
 * @author     Simon Daniel <samayo@protonmail.ch>
 */
class Request implements \ArrayAccess
{
    protected $get = [];
    protected $post = [];
    protected $server = [];
    protected $cookies = [];

    public function __construct(array $_get, array $_post, array $_server, array $_cookies)
    {
        $this->get = $_get;
        $this->post = $_post;
        $this->server = $_server;
        $this->cookies = $_cookies;
    }

    /**
     * Checks if request method is type GET.
     *
     * @return bool
     */
    public function isGet(): bool
    {
        return $this->getMethod() === 'GET';
    }

    /**
     * Checks if request method type POST.
     *
     * @return bool
     */
    public function isPost(): bool
    {
        return $this->getMethod() === 'POST';
    }

    /**
     * Checks if request method is type PUT.
     *
     * @return bool
     */
    public function isPut(): bool
    {
        return $this->getMethod() === 'PUT';
    }

    /**
     * Checks if request methos is type DELETE.
     *
     * @return bool
     */
    public function isDelete(): bool
    {
        return $this->getMethod() === 'DELETE';
    }

    /**
     * Fetch value from GET array.
     *
     * @param string $var
     * @param [type] $filter
     */
    public function get(string $var, $filter = null)
    {
        return $this->filter($this->get, $var, $filter);
    }

    /**
     * Fetch value from POST array.
     *
     * @param string $var
     * @param [type] $filter
     */
    public function post(string $var, $filter = null)
    {
        return $this->filter($this->post, $var, $filter);
    }

    /**
     * fetch value from SERVER array.
     *
     * @param string $var
     * @param [type] $filter
     */
    public function server(string $var, $filter = null)
    {
        return $this->filter($this->server, $var, $filter);
    }

    /**
     * GET the current URI.
     *
     * @return string
     */
    public function getUri(): string
    {
        return $this->filter($this->server, 'REQUEST_URI');
    }

    /**
     * GET http referer.
     *
     * @return string
     */
    public function getReferer(): string
    {
        return $this->filter($this->server, 'HTTP_REFERER');
    }

    /**
     * GET request method type.
     *
     * @return string
     */
    public function getMethod(): string
    {
        return $this->filter($this->server, 'REQUEST_METHOD');
    }

    /**
     * Check if connection is secure.
     *
     * @return bool
     */
    public function isSecure(): bool
    {
        return array_key_exists('HTTPS', $this->server)
        && $this->server['HTTPS'] !== 'off'
      ;
    }

    /**
     * Check if connection is made with XMLHttpRequest.
     *
     * @return bool
     */
    public function isXhr(): bool
    {
        return $this->filter($this->server, 'HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest';
    }

    /**
     * A util function to filter values via filter_var().
     *
     * @param array  $input
     * @param string $var
     * @param [type] $filter
     */
    protected function filter(array $input, string $var, $filter = null)
    {
        $value = $input[$var] ?? false;

        if (!$filter) {
            return $value;
        }

        return filter_var($value, $filter);
    }

    /**
     * Returns superglobal arrays.
     *
     * @return array
     */
    public function requestGlobals(): array
    {
        return [
          'get' => $this->get,
          'post' => $this->post,
          'server' => $this->server,
        ];
    }

    /**
     * Builds a URL.
     */
    public function build_url()
    {
        return  parse_url(
          $this->server('REQUEST_SCHEME').'://'.
          $this->server('SERVER_NAME').
          $this->server('REQUEST_URI')
        );
    }

    /**
     * Call class methods from array context.
     *
     * @param [type] $offset
     */
    public function offsetGet($offset)
    {
        if (in_array($offset, ['isGet', 'isPut', 'isPost', 'isDelete', 'isXhr', 'isSecure'])) {
            return $this->$offset();
        }
    }

    /**
     * Set values.
     *
     * @param [type] $offset
     * @param [type] $value
     */
    public function offsetSet($offset, $value)
    {
        $this->set($offset, $value);
    }

    /**
     * Undocumented function.
     *
     * @param [type] $offset
     */
    public function offsetExists($offset)
    {
    }

    /**
     * Undocumented function.
     *
     * @param [type] $offset
     */
    public function offsetUnset($offset)
    {
    }
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Abstract.php 9/26/2011 7:06:29 scp@orilla $
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter;

/**
 * @class TeamSpeak3_Adapter_Abstract
 * @brief Provides low-level methods for concrete adapters to communicate with a TeamSpeak 3 Server.
 */
abstract class AbstractAdapter
{
  /**
   * Stores user-provided options.
   *
   * @var array
   */
  protected $options = null;

  /**
   * Stores an TeamSpeak3_Transport_Abstract object.
   *
   * @var TeamSpeak3_Transport_Abstract
   */
  protected $transport = null;

  /**
   * The TeamSpeak3_Adapter_Abstract constructor.
   *
   * @param  array $options
   * @return AbstractAdapter
   */
  public function __construct(array $options)
  {
    $this->options = $options;

    if($this->transport === null)
    {
      $this->syn();
    }
  }

  /**
   * The TeamSpeak3_Adapter_Abstract destructor.
   *
   * @return void
   */
  abstract public function __destruct();

  /**
   * Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote
   * server.
   *
   * @throws Exception
   * @return void
   */
  abstract protected function syn();

  /**
   * Commit pending data.
   *
   * @return array
   */
  public function __sleep()
  {
    return array("options");
  }

  /**
   * Reconnects to the remote server.
   *
   * @return void
   */
  public function __wakeup()
  {
    $this->syn();
  }

  /**
   * Returns the profiler timer used for this connection adapter.
   *
   * @return TeamSpeak3_Helper_Profiler_Timer
   */
  public function getProfiler()
  {
    return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Profiler::get(spl_object_hash($this));
  }

  /**
   * Returns the transport object used for this connection adapter.
   *
   * @return TeamSpeak3_Transport_Abstract
   */
  public function getTransport()
  {
    return $this->transport;
  }

  /**
   * Loads the transport object object used for the connection adapter and passes a given set
   * of options.
   *
   * @param  array  $options
   * @param  string $transport
   * @throws Exception
   * @return void
   */
  protected function initTransport($options, $transport = '\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport\TCP')
  {
    if(!is_array($options))
    {
      throw new Exception("transport parameters must provided in an array");
    }

    $this->transport = new $transport($options);
  }

  /**
   * Returns the hostname or IPv4 address the underlying TeamSpeak3_Transport_Abstract object
   * is connected to.
   *
   * @return string
   */
  public function getTransportHost()
  {
    return $this->getTransport()->getConfig("host", "0.0.0.0");
  }

  /**
   * Returns the port number of the server the underlying TeamSpeak3_Transport_Abstract object
   * is connected to.
   *
   * @return string
   */
  public function getTransportPort()
  {
    return $this->getTransport()->getConfig("port", "0");
  }
}


<?php

namespace DevGroup\Entity\traits;

use Closure;
use Yii;
use yii\base\Event;
use yii\db\ActiveRecord;

/**
 * Class BaseActionsInfoTrait
 * This trait attaches a timestamp and a blameable behaviors.
 *
 * @property array $blameableAttributes array list of attributes that are to be automatically filled with the value specified via [[value]].
 * The array keys are the ActiveRecord events upon which the attributes are to be updated,
 * and the array values are the corresponding attribute(s) to be updated. You can use a string to represent
 * a single attribute, or an array to represent a list of attributes. For example,
 *
 * ```php
 * [
 *     ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'],
 *     ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
 * ]
 * ```
 *
 * @property array $timestampAttributes array list of attributes that are to be automatically filled with the value specified via [[value]].
 * The array keys are the ActiveRecord events upon which the attributes are to be updated,
 * and the array values are the corresponding attribute(s) to be updated. You can use a string to represent
 * a single attribute, or an array to represent a list of attributes. For example,
 *
 * ```php
 * [
 *     ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'],
 *     ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
 * ]
 * ```
 * @package DevGroup\Entity\traits
 */
trait BaseActionsInfoTrait
{
    /**
     * @var boolean whether to skip this behavior when the `$owner` has not been
     * modified
     * @since 2.0.8
     * In case, when the property is `null`, the value of `Yii::$app->user->id` will be used as the value.
     */
    public $blameableValue;

    /**
     * @var boolean whether to skip this behavior when the `$owner` has not been
     * modified
     * @since 2.0.8
     * In case, when the value is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
     * will be used as value.
     */
    public $timestampValue;

    /**
     * Get default attributes for Blameable behavior.
     * If you need to set a custom attributes, just add a `blameableAttributes` field to your model.
     * @return array
     */
    protected function getBlameableAttributes()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => [$this->createdByAttribute, $this->updatedByAttribute],
            ActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedByAttribute,
        ];
    }

    /**
     * Get default value of createdByAttribute for Blameable behavior.
     * If you need to set a custom name of attribute, just add a `createdByAttribute` field to your model.
     * @return array
     */
    protected function getCreatedByAttribute()
    {
        return 'created_by';
    }

    /**
     * Get default value of updatedByAttribute for Blameable behavior.
     * If you need to set a custom name of attribute, just add an `updatedByAttribute` field to your model.
     * @return array
     */
    protected function getUpdatedByAttribute()
    {
        return 'updated_by';
    }

    /**
     * Get default attributes for Timestamp behavior.
     * If you need to set a custom attributes, just add a `timestampAttributes` field to your model.
     * @return array
     */
    protected function getTimestampAttributes()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAtAttribute, $this->updatedAtAttribute],
            ActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedAtAttribute,
        ];
    }

    /**
     * Get default value of createdAtAttribute for Timestamp behavior.
     * If you need to set a custom name of attribute, just add an `createdAtAttribute` field to your model.
     * @return array
     */
    protected function getCreatedAtAttribute()
    {
        return 'created_at';
    }

    /**
     * Get default value of updatedAtAttribute for Timestamp behavior.
     * If you need to set a custom name of attribute, just add an `updatedAtAttribute` field to your model.
     * @return array
     */
    protected function getUpdatedAtAttribute()
    {
        return 'updated_at';
    }

    protected function getValueInternal($event, $attributeName)
    {
        if ($this->$attributeName instanceof Closure || is_array($this->$attributeName) && is_callable($this->$attributeName)) {
            return call_user_func($this->$attributeName, $event);
        }
        return $this->$attributeName;
    }

    protected function getBlameableValue($event)
    {
        if ($this->blameableValue === null) {
            $user = Yii::$app->get('user', false);
            return $user && !$user->isGuest ? $user->id : null;
        }
        return $this->getValueInternal($event, 'blameableValue');
    }

    /**
     * @inheritdoc
     *
     * In case, when the [[value]] is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
     * will be used as value.
     */
    protected function getTimestampValue($event)
    {
        if ($this->timestampValue === null) {
            return time();
        }
        return $this->getValueInternal($event, 'timestampValue');
    }

    /**
     * Get trait attribute labels
     * @return array
     */
    public function BaseActionsInfoTraitAttributeLabels()
    {
        return [
            'created_at' => Yii::t('entity', 'Created at'),
            'created_by' => Yii::t('entity', 'Created by'),
            'updated_at' => Yii::t('entity', 'Updated at'),
            'updated_by' => Yii::t('entity', 'Updated by'),
        ];
    }

    /**
     * Evaluates the attribute value and assigns it to the current attributes.
     * @param Event $event
     */
    public function evaluateAttributesInternal($event)
    {
        if (empty($event->data['attributes']) === false) {
            $methodName = $event->data['methodName'];
            $value = $this->$methodName($event);
            foreach ((array) $event->data['attributes'] as $attribute) {
                if (is_string($attribute)) {
                    $this->$attribute = $value;
                }
            }
        }
    }

    /**
     * Init a trait.
     * There is an event attaching here.
     */
    public function BaseActionsInfoTraitInit()
    {
        /** @var ActiveRecord|self $this */
        foreach ($this->blameableAttributes as $eventName => $attributes) {
            $this->on(
                $eventName,
                [$this, 'evaluateAttributesInternal'],
                [
                    'attributes' => $attributes,
                    'methodName' => 'getBlameableValue',
                ]
            );
        }
        foreach ($this->timestampAttributes as $eventName => $attributes) {
            $this->on(
                $eventName,
                [$this, 'evaluateAttributesInternal'],
                [
                    'attributes' => $attributes,
                    'methodName' => 'getTimestampValue',
                ]
            );
        }
    }
}


<?php

namespace Brave\Auth;

use \Mdanter\Ecc\EccFactory;
use \Mdanter\Ecc\Primitives\Point;
use \Mdanter\Ecc\Crypto\Signature\Signature;
use \Mdanter\Ecc\Random\RandomGeneratorFactory;
use \Mdanter\Ecc\Crypto\Key\PrivateKey;
use \Mdanter\Ecc\Crypto\Key\PublicKey;

/**
 * Class CoreAuthHandler
 *
 * @package Brave\Auth
 */
class CoreAuthHandler implements \Requests_Auth
{

	private $debug = FALSE;

	private $math_adapter = FALSE;
	private $service_name = FALSE;
	private $private_key = FALSE;
	private $public_key = FALSE;

	/**
	 * Constructor
	 *
	 * @param      $service
	 * @param      $private_key
	 * @param      $public_key
	 * @param bool $debug
	 */
	public function __construct( $service, $private_key, $public_key, $debug = FALSE )
	{
		$this->math_adapter = EccFactory::getAdapter();
		$this->service_name = $service;
		$this->private_key  = $private_key;
		$this->public_key   = $public_key;
		$this->debug        = $debug;
	}

	/**
	 * @param \Requests_Hooks $hooks
	 */
	public function register( \Requests_Hooks &$hooks )
	{
		$hooks->register('requests.before_request', [&$this, 'before_request']);
		$hooks->register('requests.after_request', [&$this, 'after_request']);
	}

	/**
	 * before_request
	 * Hook for PHP Requests
	 *
	 * @param $url
	 * @param $headers
	 * @param $data
	 */
	public function before_request( &$url, &$headers, &$data )
	{
		// generate a date string
		$date            = new \DateTime('NOW', new \DateTimeZone("GMT"));
		$headers['Date'] = $date->format("D, d M Y H:i:s \G\M\T");

		// build up the data to be signed
		$request_data = $headers['Date']."\n".$url."\n";
		if( !empty($data) )
		{
			$request_data .= http_build_query($data);
		}

		// get a signature for our request

		// private key is in hex form, needs to be converted into PrivateKey Object
		$generator   = EccFactory::getNistCurves()->generator256();
		$private_key = new PrivateKey($this->math_adapter, $generator, $this->math_adapter->hexDec($this->private_key));

		$hash         = $this->math_adapter->hexDec(hash("sha256", $request_data));
		$signer       = EccFactory::getSigner();
		$randomK      = RandomGeneratorFactory::getRandomGenerator()->generate($private_key->getPoint()->getOrder());
		$signatureObj = $signer->sign($private_key, $hash, $randomK);
		$signature    = $this->math_adapter->decHex($signatureObj->getR()).$this->math_adapter->decHex($signatureObj->getS());

		// apply the HTTP headers and send the request
		$headers['X-Service']   = $this->service_name;
		$headers['X-Signature'] = $signature;

		if( $this->debug )
		{
			echo "\n\nRequest Data\n\n";

			echo "URL:\n";
			var_dump($url);

			echo "HEADERS:\n";
			var_dump($headers);

			echo "DATA:\n";
			var_dump($data);
		}
	}

	/**
	 * after_request
	 * Hook for PHP Requests
	 *
	 * @param \Requests_Response $return
	 *
	 * @throws
	 */
	public function after_request( \Requests_Response &$return )
	{
		$headers   = $return->headers;
		$url       = $return->url;
		$data      = $return->body;
		$signature = $headers['x-signature'];

		if( $this->debug )
		{
			echo "\n\nResponse Data:\n";
			var_dump($return);
		}

		// Check if signature header exists, if not the request failed
		if( !isset($headers['x-signature']) or $headers['x-signature'] == '' )
		{
			throw new \Exception('Request Failed');
		}

		// build up the data to be signed
		$request_data = $this->service_name."\n".$headers['date']."\n".$url."\n";
		if( !empty($data) )
		{
			$request_data .= trim($data);
		}

		// try and validate the signature

		// ------------------------------------
		$generator = EccFactory::getNistCurves()->generator256();

		$order_len  = strlen($this->math_adapter->decHex($generator->getOrder()));
		$x          = $this->math_adapter->hexDec(substr($this->public_key, 0, $order_len));
		$y          = $this->math_adapter->hexDec(substr($this->public_key, $order_len));
		$point      = new Point($this->math_adapter, EccFactory::getNistCurves()->curve256(), $x, $y, $generator->getOrder());
		$public_key = new PublicKey($this->math_adapter, $generator, $point);

		$r         = $this->math_adapter->hexDec(substr($signature, 0, $order_len));
		$s         = $this->math_adapter->hexDec(substr($signature, $order_len));
		$signature = new Signature($r, $s);

		$signer     = EccFactory::getSigner();
		$check_hash = $this->math_adapter->hexDec(hash("sha256", $request_data));
		$result     = $signer->verify($public_key, $signature, $check_hash);
		// ------------------------------------

		//$result = \ECDSA::validate($request_data, $signature, $this->public_key);

		// if signature validation failed, throw exception
		if( $result !== TRUE )
		{
			throw new \Exception('Signature Does Not Validate!');
		}
	}
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: UDP.php 9/26/2011 7:06:29 scp@orilla $
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport;

/**
 * @class TeamSpeak3_Transport_UDP
 * @brief Class for connecting to a remote server through UDP.
 */
class UDP extends AbstractTransport
{
  /**
   * Connects to a remote server.
   *
   * @throws Exception
   * @return void
   */
  public function connect()
  {
    if($this->stream !== null) return;

    $host = strval($this->config["host"]);
    $port = strval($this->config["port"]);

    $address = "udp://" . $host . ":" . $port;
    $timeout = intval($this->config["timeout"]);

    $this->stream = @stream_socket_client($address, $errno, $errstr, $timeout);

    if($this->stream === FALSE)
    {
      throw new Exception(utf8_encode($errstr), $errno);
    }

    @stream_set_timeout($this->stream, $timeout);
    @stream_set_blocking($this->stream, $this->config["blocking"] ? 1 : 0);
  }

  /**
   * Disconnects from a remote server.
   *
   * @return void
   */
  public function disconnect()
  {
    if($this->stream === null) return;

    $this->stream = null;

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "Disconnected");
  }

  /**
   * Reads data from the stream.
   *
   * @param  integer $length
   * @throws Exception
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  public function read($length = 4096)
  {
    $this->connect();
    $this->waitForReadyRead();

    $data = @fread($this->stream, $length);

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "DataRead", $data);

    if($data === FALSE)
    {
      throw new Exception("connection to server '" . $this->config["host"] . ":" . $this->config["port"] . "' lost");
    }

    return new \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String($data);
  }

  /**
   * Writes data to the stream.
   *
   * @param  string $data
   * @return void
   */
  public function send($data)
  {
    $this->connect();

    @stream_socket_sendto($this->stream, $data);

    \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "DataSend", $data);
  }
}


<?php

namespace ASM\Doctrine\DBAL\Types;

use DateTime;
use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

/**
 * Class DateTimeUTCType
 * @package ASM\Doctrine\DBAL\Types
 */
class DateTimeUTCType extends DateTimeType
{
    const DATETIMEUTC = 'datetimeutc';

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::DATETIMEUTC;
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return ($value !== null) ?
            $value->setTimezone(new DateTimeZone('UTC'))->format($platform->getDateTimeFormatString()) : null;
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return $value;
        }

        if ($value instanceof DateTime) {
            return $value->setTimezone(new DateTimeZone('UTC'));
        }

        $dateTime = DateTime::createFromFormat($platform->getDateTimeFormatString(), $value, new DateTimeZone('UTC'));

        if (!$dateTime) {
            $dateTime = date_create($value, new DateTimeZone('UTC'));
        }

        if (!$dateTime) {
            throw ConversionException::conversionFailedFormat(
                $value,
                $this->getName(),
                $platform->getDateTimeFormatString()
            );
        }

        return $dateTime;
    }

    /**
     * {@inheritdoc}
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}


<?php
/**
 * @author Semenov Alexander <semenov@skeeks.com>
 * @link http://skeeks.com/
 * @copyright 2010 SkeekS (СкикС)
 * @date 18.03.2016
 */

namespace skeeks\cms\dbDumper\console\controllers;

use yii\helpers\Console;

/**
 * Working with the mysql database
 *
 * Class DbController
 * @package skeeks\cms\dbDumper\console\controllers
 */
class MysqlController extends \yii\console\Controller
{
    public $defaultAction = "dump";

    /**
     * Restore from the file dump
     * @param null $fileName The path to the dump file
     */
    public function actionRestore($fileName = null)
    {
        try {
            $this->stdout(\Yii::t('skeeks/dbDumper', "The installation process is running the database")."\n");
            \Yii::$app->dbDumper->restore($fileName);
            $this->stdout(\Yii::t('skeeks/dbDumper', "Dump successfully installed")."\n", Console::FG_GREEN);
        } catch (\Exception $e) {
            $this->stdout(\Yii::t('skeeks/dbDumper',
                    "In the process of restoring the dump occurred error").": {$e->getMessage()}\n", Console::FG_RED);
        }
    }

    /**
     * Creating a dump
     */
    public function actionDump()
    {
        try {
            $result = \Yii::$app->dbDumper->dump();
            $this->stdout(\Yii::t('skeeks/dbDumper', "Dump the database was created successfully").": {$result}\n",
                Console::FG_GREEN);
            $removed = \Yii::$app->dbDumper->clear();
            if ($removed > 0) {
                $this->stdout(\Yii::t('skeeks/dbDumper', "Removed old dumps").": {$removed}\n", Console::FG_GREEN);
            }

        } catch (\Exception $e) {
            $this->stdout(\Yii::t('skeeks/dbDumper', "During the dump error occurred").": {$e->getMessage()}\n",
                Console::FG_RED);
        }
    }

}


<?php
/**
 * Menubar Plugin - Handle dynamically a menu
 *
 * @copyright   Copyright (c) 2009-2011 NADEO (http://www.nadeo.com)
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL License 3
 * @version     $Revision$:
 * @author      $Author$:
 * @date        $Date$:
 */

namespace ManiaLivePlugins\Standard\Menubar;

use ManiaLib\Gui\Elements\Icons128x128_1;
use ManiaLive\Features\Admin\AdminGroup;
use ManiaLive\DedicatedApi\Callback\Event as ServerEvent;
use ManiaLive\PluginHandler\Event as PluginEvent;
use ManiaLivePlugins\Standard\Menubar\Gui\Controls\Subitem;
use ManiaLivePlugins\Standard\Menubar\Gui\Controls\Item;
use ManiaLivePlugins\Standard\Menubar\Gui\Windows\Menu;

class Menubar extends \ManiaLive\PluginHandler\Plugin
{
	protected $menu;
	protected $loaded = false;

	public function onInit()
	{
		$this->menu = array();
		$this->setVersion('1.1');
		$this->setPublicMethod('addButton');
		$this->setPublicMethod('initMenu');
	}

	public function onReady()
	{
		$this->refreshMenubar();

		$this->enableDedicatedEvents(ServerEvent::ON_PLAYER_CONNECT);
		$this->enablePluginEvents(PluginEvent::ON_PLUGIN_UNLOADED);

		$this->loaded = true;
	}

	public function refreshMenubar()
	{
		foreach($this->storage->players as $login => $player)
			$this->onPlayerConnect($login, true);
		foreach($this->storage->spectators as $login => $player)
			$this->onPlayerConnect($login, false);
	}

	public function onPlayerConnect($login, $isSpectator)
	{
		$menu = Menu::Create($login);
		$menu->setPosition(136, 45);
		$menu->setScale(0.8);
		$menu->clearItems();

		foreach($this->menu as $section)
		{
			switch(count($section['buttons']))
			{
				case 0: break;
				case 1:
					if(!$section['buttons'][0]['admin'] || AdminGroup::contains($login))
						$menu->addFinalItem($section['name'], $section['icon'], $section['buttons'][0]['callback']);
					break;
				default:
					$entry = $menu->addItem($section['name'], $section['icon']);
					foreach($section['buttons'] as $button)
						if(!$button['admin'] || AdminGroup::contains($login))
							$entry->addSubitem($button['name'], $button['callback']);
			}
		}

		$menu->show();
	}

	// initializes the menu for a specific plugin
	function initMenu($icon, $pluginId = null)
	{
		$id = explode('\\', $pluginId);

		$this->menu[$pluginId] = array('name' => end($id), 'icon' => $icon, 'buttons' => array());

		if($this->loaded)
			$this->refreshMenubar();
	}

	// adds button for the plugin.
	function addButton($name, $callback, $admin = false, $pluginId = null)
	{
		if(!isset($this->menu[$pluginId]))
			$this->initMenu(Icons128x128_1::DefaultIcon, $pluginId);

		$this->menu[$pluginId]['buttons'][] = array('name' => $name, 'callback' => $callback, 'admin' => $admin);

		if($this->loaded)
			$this->refreshMenubar();
	}

	function onPluginUnloaded($pluginId)
	{
		// ignore own unloading
		if ($pluginId == $this->getId())
			return;

		// remove button from bar
		if(isset($this->menu[$pluginId]))
		{
			unset($this->menu[$pluginId]);
			$this->refreshMenubar();
		}
	}

	function onUnload()
	{
		Menu::EraseAll();

		parent::onUnload();
	}
}

?>


<?php

namespace Encore\Wx\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class Install extends \Encore\Console\Command
{
    protected $name = 'wxwidgets:install';
    protected $description = 'Install wxWidgets and wxPHP';

    /**
     * Fire the install command
     *
     * @return void
     */
    public function fire()
    {
        $handle = popen(PHP_BINDIR.'/pecl install wxwidgets 2>&1', 'r');

        while ( ! feof($handle)) {
            $this->output->write(fread($handle, 2048));
        }
    }

    /**
     * Get a list of options that this command takes
     *
     * @return array
     */
    public function getOptions()
    {
        return [
            ['from-source', null, InputOption::VALUE_NONE, 'Download wxPHP from source instead of installing from PECL'],
        ];
    }
}


<?php

namespace Votemike\Dbhelper;

use DB;

class Table
{
    public $name = '';
    private $columns = [];

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

    public function addColumn(Column $column)
    {
        $this->columns[] = $column;
    }

    public function getColumns()
    {
        return $this->columns;
    }

    public function getColumnsForDisplay()
    {
        $toDisplay = [];
        foreach ($this->columns as $column) {
            if ($column->shouldBeDisplayed()) {
                $toDisplay[] = $column;
            }
        }

        return $toDisplay;
    }

    /**
     * Go through each column and find the largest value of that field
     */
    public function populateColumnsWithLongestValue()
    {
        $query = DB::table($this->name);
        foreach ($this->columns as $column) {
            if ($column->isNumeric()) {
                $query->addSelect(DB::raw('MAX(`' . $column->name . '`) as `' . $column->name . '`'));
            }
            if ($column->isTextual()) {
                $query->addSelect(DB::raw('MAX(LENGTH(`' . $column->name . '`)) as `' . $column->name . '`'));
            }
        }
        $result = $query->first();
        foreach ($this->columns as $column) {
            $columnName = $column->name;
            if (isset($result->$columnName)) {
                $column->setMaxValue($result->$columnName);
            }
        }
    }

    public function populateColumnsWithSuggestedType($threshold = 0.75)
    {
        foreach ($this->columns as $column) {
            $column->populateWithSuggestedType($threshold);
        }
    }

    /**
     * Go through each column and find the lowest value of that field
     */
    public function populateNumericColumnsWithLongestValue()
    {
        $query = DB::table($this->name);
        foreach ($this->columns as $column) {
            if ($column->isNumeric()) {
                $query->addSelect(DB::raw('MIN(`' . $column->name . '`) as `' . $column->name . '`'));
            }
        }
        $result = $query->first();
        foreach ($this->columns as $column) {
            $columnName = $column->name;
            if (isset($result->$columnName)) {
                $column->setMinValue($result->$columnName);
            }
        }
    }

    /**
     * If no columns from the table need to be displayed, the table doesn't need to be displayed
     * @return bool
     */
    public function shouldBeDisplayed()
    {
        foreach ($this->columns as $column) {
            if ($column->shouldBeDisplayed()) {
                return true;
            }
        }

        return false;
    }
}


<?php

namespace Shoko\TwitchApiBundle\Util;

use Shoko\TwitchApiBundle\Exception\JsonTransformerException;

/**
 * Class JsonTransformer.
 */
class JsonTransformer implements TransformerInterface
{
    /**
     * Transform Json to Associative Array.
     *
     * @param string $json
     *
     * @return array
     */
    public function transform($json)
    {
        if (!is_string($json)) {
            throw new \InvalidArgumentException('$json variable is not a string.');
        }
        $assocArrayJson = json_decode($json, true);

        return $this->checkDecodedJson($assocArrayJson);
    }

    /**
     * Verification if no json error has occured.
     *
     * @param string $assocArrayJson
     *
     * @throws JsonTransformerException
     *
     * @return string
     */
    private function checkDecodedJson($assocArrayJson)
    {
        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new JsonTransformerException(json_last_error_msg());
        }

        return $assocArrayJson;
    }
}


<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\FormElements;

use Zend\Form\Element;
use Zend\InputFilter\InputProviderInterface;
use Zend\Validator\InArray;

class Radio extends Element implements AngularAwareInterface, InputProviderInterface
{
    use ElementTrait;

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

    /**
     * @param array|\Traversable $options
     * @return $this
     */
    public function setOptions($options)
    {
        if (isset($options['values'])) {
            $this->setValueOptions($options['values']);
        }

        return $this;
    }

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

    /**
     * @param array $valueOptions
     * @return $this
     */
    public function setValueOptions(array $valueOptions)
    {
        $this->valueOptions = $valueOptions;

        return $this;
    }

    /**
     * Should return an array specification compatible with
     * {@link Zend\InputFilter\Factory::createInput()}.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        $haystack = \array_keys($this->getValueOptions());

        return [
            'name' => $this->getName(),
            'required' => $this->isRequired(),
            'validators' => [
                [
                    'name' => InArray::class,
                    'options' => ['haystack' => $haystack],
                ],
            ],
        ];
    }
}


<?php
/**
 * MIT License
 * ===========
 *
 * Copyright (c) 2012 Francisco Javier Palma <palmasev@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @author      Francisco Javier Palma <palmasev@gmail.com>
 * @copyright   2012 Francisco Javier Palma.
 * @license     http://www.opensource.org/licenses/mit-license.php  MIT License
 * @link        http://fjavierpalma.es
 */
namespace Palma\Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Configuration;
use Doctrine\DBAL\DriverManager;
use Doctrine\Common\EventManager;
use Doctrine\Common\Cache\ArrayCache as Cache;

/**
 * Class DoctrineORMServiceProvider
 * @package Palma\Silex\Provider
 */
class DoctrineORMServiceProvider implements ServiceProviderInterface
{
    /**
     * Register ORM on Application
     *
     * @param Application $app
     */
    public function register(Application $app)
    {
        $app['doctrine_orm.configuration'] = $app->share(function ($app) {
            $configuration = new Configuration();

            $mCache = isset($app['doctrine_orm.metadata_cache']) ? $app['doctrine_orm.metadata_cache'] : new Cache();
            $qCache = isset($app['doctrine_orm.query_cache']) ? $app['doctrine_orm.query_cache'] : new Cache();
            $rCache = isset($app['doctrine_orm.result_cache']) ? $app['doctrine_orm.result_cache'] : new Cache();

            $annotation = boolval($app['doctrine_orm.simple_annotation_reader']);
            $driverImpl = $configuration->newDefaultAnnotationDriver($app['doctrine_orm.entities_path'], $annotation);

            $configuration->setMetadataCacheImpl($mCache);
            $configuration->setMetadataDriverImpl($driverImpl);
            $configuration->setQueryCacheImpl($qCache);
            $configuration->setResultCacheImpl($rCache);
            $configuration->setProxyDir($app['doctrine_orm.proxies_path']);
            $configuration->setProxyNamespace($app['doctrine_orm.proxies_namespace']);
            $configuration->setAutogenerateProxyClasses(false);

            if (isset($app['doctrine_orm.autogenerate_proxy_classes'])) {
                $configuration->setAutogenerateProxyClasses($app['doctrine_orm.autogenerate_proxy_classes']);
            } else {
                $configuration->setAutogenerateProxyClasses(true);
            }

            return $configuration;
        });

        $app['doctrine_orm.connection'] = $app->share(function ($app) {
            return DriverManager::getConnection(
                $app['doctrine_orm.connection_parameters'],
                $app['doctrine_orm.configuration'],
                new EventManager()
            );
        });

        $app['doctrine_orm.em'] = $app->share(function ($app) {
            return EntityManager::create(
                $app['doctrine_orm.connection'],
                $app['doctrine_orm.configuration'],
                $app['doctrine_orm.connection']->getEventManager()
            );
        });

    }

    /**
     * Boot
     * @param Application $app
     */
    public function boot(Application $app)
    {
        // do nothing
    }
}


<?php
/**
 * This file is a part of the page-fetcher package.
 *
 * Read more at https://github.com/themichaelhall/page-fetcher
 */
declare(strict_types=1);

namespace MichaelHall\PageFetcher;

use DataTypes\Interfaces\FilePathInterface;
use DataTypes\Interfaces\UrlInterface;
use MichaelHall\PageFetcher\Interfaces\PageFetcherRequestInterface;

/**
 * Page fetcher request class.
 *
 * @since 1.0.0
 */
class PageFetcherRequest implements PageFetcherRequestInterface
{
    /**
     * Constructs a page fetcher request.
     *
     * @since 1.0.0
     *
     * @param UrlInterface $url    The url.
     * @param string       $method The method.
     */
    public function __construct(UrlInterface $url, string $method = 'GET')
    {
        $this->url = $url;
        $this->method = $method;
        $this->headers = [];
        $this->postFields = [];
        $this->files = [];
        $this->rawContent = '';
    }

    /**
     * Adds a header.
     *
     * @since 1.0.0
     *
     * @param string $header The header.
     */
    public function addHeader(string $header): void
    {
        $this->headers[] = $header;
    }

    /**
     * Returns the files to upload.
     *
     * @since 1.0.0
     *
     * @return array The files to upload.
     */
    public function getFiles(): array
    {
        return $this->files;
    }

    /**
     * Returns the headers.
     *
     * @since 1.0.0
     *
     * @return string[] The headers.
     */
    public function getHeaders(): array
    {
        return $this->headers;
    }

    /**
     * Returns the method.
     *
     * @since 1.0.0
     *
     * @return string The method.
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * Returns the post fields.
     *
     * @since 1.0.0
     *
     * @return array The post fields.
     */
    public function getPostFields(): array
    {
        return $this->postFields;
    }

    /**
     * Returns the raw content.
     *
     * @since 1.0.0
     *
     * @return string The raw content.
     */
    public function getRawContent(): string
    {
        return $this->rawContent;
    }

    /**
     * Returns the url.
     *
     * @since 1.0.0
     *
     * @return UrlInterface The url.
     */
    public function getUrl(): UrlInterface
    {
        return $this->url;
    }

    /**
     * Sets a file to upload.
     *
     * @since 1.0.0
     *
     * @param string            $name     The name.
     * @param FilePathInterface $filePath The file path.
     */
    public function setFile(string $name, FilePathInterface $filePath): void
    {
        $this->rawContent = '';
        $this->files[$name] = $filePath;
    }

    /**
     * Sets a post field.
     *
     * @since 1.0.0
     *
     * @param string $name  The name.
     * @param string $value The value.
     */
    public function setPostField(string $name, string $value): void
    {
        $this->rawContent = '';
        $this->postFields[$name] = $value;
    }

    /**
     * Sets the raw content.
     *
     * @since 1.0.0
     *
     * @param string $rawContent The raw content.
     */
    public function setRawContent(string $rawContent): void
    {
        $this->postFields = [];
        $this->files = [];
        $this->rawContent = $rawContent;
    }

    /**
     * @var UrlInterface My url.
     */
    private $url;

    /**
     * @var string My method.
     */
    private $method;

    /**
     * @var string[] My headers.
     */
    private $headers;

    /**
     * @var array My post fields.
     */
    private $postFields;

    /**
     * @var array My files.
     */
    private $files;

    /**
     * @var string My raw content.
     */
    private $rawContent;
}


<?php namespace Jonsa\PimpleResolver;

use Jonsa\PimpleResolver\Contract\ClassResolver as ClassResolverContract;
use Jonsa\PimpleResolver\Event\ClassResolvedEvent;
use Jonsa\PimpleResolver\Exception\BindingResolutionException;
use Pimple\Container;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Class ClassResolver
 *
 * @package Jonsa\PimpleResolver
 * @author Jonas Sandström
 */
class ClassResolver implements ClassResolverContract
{

    /**
     * @var Container
     */
    private $container;

    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * The stack of concretions being current built.
     *
     * @var array
     */
    private $buildStack = array();

    /**
     * @param EventDispatcherInterface $dispatcher
     */
    public function __construct(EventDispatcherInterface $dispatcher = null)
    {
        $this->container = new Container();
        $this->dispatcher = $dispatcher;
    }

    /**
     * Instantiate a concrete instance of the given type.
     *
     * @param string $abstract
     * @param array $parameters
     *
     * @return mixed
     */
    public function resolve($abstract, $parameters = array())
    {
        $concrete = $this->getConcrete($abstract);

        // We're ready to instantiate an instance of the concrete type registered for
        // the binding. This will instantiate the types, as well as resolve any of
        // its "nested" dependencies recursively until all have gotten resolved.
        if ($this->isBuildable($concrete, $abstract)) {
            $object = $this->build($concrete, $parameters);
        } else {
            $object = $this->resolve($concrete, $parameters);
        }

        $this->dispatchEvent(Events::CLASS_RESOLVED, new ClassResolvedEvent($object));

        return $object;
    }

    /**
     * Bind an abstract definition to a concrete implementation.
     *
     * @param string $abstract
     * @param string|\Closure $concrete
     * @param bool $protect
     */
    public function bind($abstract, $concrete, $protect = false)
    {
        if ($protect) {
            $concrete = $this->container->protect($concrete);
        }

        $this->container[$abstract] = $concrete;
    }

    /**
     * Get the concrete type for a given abstract.
     *
     * @param string $abstract
     *
     * @return mixed $concrete
     */
    protected function getConcrete($abstract)
    {
        // If we don't have a registered resolver or concrete for the type, we'll just
        // assume each type is a concrete name and will attempt to resolve it as is
        // since the container should be able to resolve concretes automatically.
        if (!is_scalar($abstract)) {
            return $abstract;
        }

        if (!isset($this->container[$abstract])) {
            if ($this->missingLeadingSlash($abstract) && isset($this->container['\\' . $abstract])) {
                $abstract = '\\' . $abstract;
            }

            return $abstract;
        }

        return $this->container[$abstract];
    }

    /**
     * Determine if the given abstract has a leading slash.
     *
     * @param string $abstract
     *
     * @return bool
     */
    protected function missingLeadingSlash($abstract)
    {
        return is_string($abstract) && strpos($abstract, '\\') !== 0;
    }

    /**
     * Determine if the given concrete is buildable.
     *
     * @param mixed $concrete
     * @param string $abstract
     *
     * @return bool
     */
    protected function isBuildable($concrete, $abstract)
    {
        return $concrete === $abstract || $concrete instanceof \Closure;
    }

    /**
     * Instantiate a concrete instance of the given type.
     *
     * @param string $concrete
     * @param array $parameters
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     */
    protected function build($concrete, $parameters = array())
    {
        // If the concrete type is actually a Closure, we will just execute it and
        // hand back the results of the functions, which allows functions to be
        // used as resolvers for more fine-tuned resolution of these objects.
        if ($concrete instanceof \Closure) {
            return $concrete($this, $parameters);
        }

        $reflector = new \ReflectionClass($concrete);

        // If the type is not instantiable, the developer is attempting to resolve
        // an abstract type such as an Interface of Abstract Class and there is
        // no binding registered for the abstractions so we need to bail out.
        if (!$reflector->isInstantiable()) {
            $message = "Target [$concrete] is not instantiable.";

            throw new BindingResolutionException($message);
        }

        $this->buildStack[] = $concrete;

        $constructor = $reflector->getConstructor();

        // If there are no constructors, that means there are no dependencies then
        // we can just resolve the instances of the objects right away, without
        // resolving any other types or dependencies out of these containers.
        if (is_null($constructor)) {
            array_pop($this->buildStack);

            return new $concrete;
        }

        $dependencies = $constructor->getParameters();

        // Once we have all the constructor's parameters we can create each of the
        // dependency instances and then use the reflection instances to make a
        // new instance of this class, injecting the created dependencies in.
        $parameters = $this->keyParametersByArgument(
            $dependencies, $parameters
        );

        $instances = $this->getDependencies(
            $dependencies, $parameters
        );

        array_pop($this->buildStack);

        return $reflector->newInstanceArgs($instances);
    }

    /**
     * If extra parameters are passed by numeric ID, rekey them by argument name.
     *
     * @param array $dependencies
     * @param array $parameters
     *
     * @return array
     */
    protected function keyParametersByArgument(array $dependencies, array $parameters)
    {
        foreach ($parameters as $key => $value) {
            if (is_numeric($key)) {
                unset($parameters[$key]);

                $parameters[$dependencies[$key]->name] = $value;
            }
        }

        return $parameters;
    }

    /**
     * Resolve all of the dependencies from the ReflectionParameters.
     *
     * @param \ReflectionParameter[] $parameters
     * @param array $primitives
     *
     * @return array
     */
    protected function getDependencies($parameters, array $primitives = array())
    {
        $dependencies = array();

        foreach ($parameters as $parameter) {
            $dependency = $parameter->getClass();

            // If the class is null, it means the dependency is a string or some other
            // primitive type which we can not resolve since it is not a class and
            // we will just bomb out with an error since we have no-where to go.
            if (array_key_exists($parameter->name, $primitives)) {
                $dependencies[] = $primitives[$parameter->name];
            } elseif (is_null($dependency)) {
                $dependencies[] = $this->resolveNonClass($parameter);
            } else {
                $dependencies[] = $this->resolveClass($parameter);
            }
        }

        return (array)$dependencies;
    }

    /**
     * Resolve a non-class hinted dependency.
     *
     * @param \ReflectionParameter $parameter
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     */
    protected function resolveNonClass(\ReflectionParameter $parameter)
    {
        if ($parameter->isDefaultValueAvailable()) {
            return $parameter->getDefaultValue();
        }

        $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";

        throw new BindingResolutionException($message);
    }

    /**
     * Resolve a class based dependency from the container.
     *
     * @param \ReflectionParameter $parameter
     *
     * @return mixed
     *
     * @throws BindingResolutionException
     */
    protected function resolveClass(\ReflectionParameter $parameter)
    {
        try {
            return $this->resolve($parameter->getClass()->name);
        } catch (BindingResolutionException $e) {
            // If we can not resolve the class instance, we will check to see if the value
            // is optional, and if it is we will return the optional parameter value as
            // the value of the dependency, similarly to how we do this with scalars.

            if ($parameter->isOptional()) {
                return $parameter->getDefaultValue();
            }

            throw $e;
        }
    }

    /**
     * Relay events to all listeners.
     *
     * @param string $name
     * @param Event $event
     */
    protected function dispatchEvent($name, Event $event)
    {
        if ($this->dispatcher) {
            $this->dispatcher->dispatch($name, $event);
        }
    }

}