<?php

namespace Ekyna\Bundle\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class Controller
 * @package Ekyna\Bundle\CoreBundle\Controller
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class Controller extends BaseController
{
    /**
     * Checks if the attributes are granted against the current authentication token and optionally supplied object.
     *
     * @param mixed $attributes
     * @param mixed $object
     * @return bool
     */
    protected function isGranted($attributes, $object = null)
    {
        return $this->get('security.authorization_checker')->isGranted($attributes, $object);
    }

    /**
     * Returns the router.
     *
     * @return \Symfony\Component\Routing\RouterInterface;
     */
    protected function getRouter()
    {
        return $this->get('router');
    }

    /**
     * Returns the event dispatcher.
     *
     * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
     */
    protected function getDispatcher()
    {
        return $this->get('event_dispatcher');
    }

    /**
     * Returns the validator.
     *
     * @return \Symfony\Component\Validator\Validator\ValidatorInterface
     */
    protected function getValidator()
    {
        return $this->get('validator');
    }

    /**
     * Returns the translator.
     *
     * @return \Symfony\Component\Translation\TranslatorInterface
     */
    protected function getTranslator()
    {
        return $this->get('translator');
    }

    /**
     * Returns the session.
     *
     * @return \Symfony\Component\HttpFoundation\Session\Session
     */
    protected function getSession()
    {
        return $this->get('session');
    }

    /**
     * Returns the flash bag.
     *
     * @return \Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface
     */
    protected function getFlashBag()
    {
        return $this->getSession()->getFlashBag();
    }

    /**
     * Adds a flash message.
     *
     * @param string $message
     * @param string $type (info|success|warning|danger)
     * @throws \InvalidArgumentException
     */
    protected function addFlash($message, $type = 'info')
    {
        if (!in_array($type, ['info', 'success', 'warning', 'danger'])) {
            throw new \InvalidArgumentException(sprintf('Invalid flash type "%s".', $type));
        }
        $this->getFlashBag()->add($type, $message);
    }

    /**
     * Redirect to the referer.
     *
     * @param string $defaultPath
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function redirectToReferer($defaultPath)
    {
        if (null !== $request = $this->get('request_stack')->getCurrentRequest()) {
            if (0 < strlen($referer = $request->headers->get('referer'))) {
                return $this->redirect($referer);
            }
        }
        return $this->redirect($defaultPath);
    }

    /**
     * Adds http cache tags and sets the shared max age.
     *
     * @param Response $response
     * @param array $tags
     * @param int $smaxage
     * @return Response;
     */
    protected function configureSharedCache(Response $response, array $tags = [], $smaxage = null)
    {
        if (!empty($tags)) {
            $this->get('ekyna_core.cache.tag_manager')->addTags($tags);
        }
        $smaxage = intval($smaxage);
        if (0 >= $smaxage) {
            $smaxage = $this->container->getParameter('ekyna_core.cache_config')['default_smaxage'];
        }
        return $response->setSharedMaxAge($smaxage);
    }
}


<?php
/**  ______ _                 _               _ ___
 *  |  ____| |               | |             | |__ \
 *  | |__  | |_   ___      __| |__   ___  ___| |  ) |
 *  |  __| | | | | \ \ /\ / /| '_ \ / _ \/ _ \ | / /
 *  | |    | | |_| |\ V  V / | | | |  __/  __/ |/ /_
 *  |_|    |_|\__, | \_/\_/  |_| |_|\___|\___|_|____|
 *             __/ |
 *            |___/
 *
 * Flywheel2: the inertia php framework
 *
 * @category	Flywheel2
 * @package		international
 * @author		wakaba <wakabadou@gmail.com>
 * @copyright	2011- Wakabadou honpo (http://www.wakabadou.net/) / Project ICKX (http://www.ickx.jp/)
 * @license		http://opensource.org/licenses/MIT The MIT License MIT
 * @varsion		2.0.0
 */

namespace ickx\fw2\international\language;

/**
 * 自然言語に係る処理を扱います。
 *
 */
class Language {
	//======================================================
	//言語
	//======================================================
	const AF		= 'af';		//アフリカーンス語
	const BE		= 'be';		//白ロシア語
	const BG		= 'bg';		//ブルアリア語
	const CA		= 'ca';		//カタロニア語
	const CS		= 'cs';		//チェコ語
	const DA		= 'da';		//デンマーク語
	const DE		= 'de';		//ドイツ語
	const DE_AU		= 'de-AU';	//ドイツ語/オーストリア
	const DE_CH		= 'de-CH';	//ドイツ語/スイス
	const DE_DE		= 'de-DE';	//ドイツ語/ドイツ
	const EL		= 'el';		//ギリシア語
	const EN		= 'en';		//英語
	const EN_GB		= 'en-GB';	//英語/英国
	const EN_US		= 'en-US';	//英語/米国
	const ES		= 'es';		//スペイン語
	const ES_AR		= 'es-AR';	//スペイン語/アルゼンチン
	const ES_CO		= 'es-CO';	//スペイン語/コロンビア
	const ES_ES		= 'es-ES';	//スペイン語/スペイン
	const ES_MX		= 'es-MX';	//スペイン語/メキシコ
	const EU		= 'eu';		//バスク語
	const FI		= 'fi';		//フィンランド語
	const FO		= 'fo';		//フェロー語
	const FR		= 'fr';		//フランス語
	const FR_BE		= 'fr-BE';	//フランス語/ベルギー
	const FR_CA		= 'fr-CA';	//フランス語/カナダ
	const FR_CH		= 'fr-CH';	//フランス語/スイス
	const FR_FR		= 'fr-FR';	//フランス語/フランス
	const GA		= 'ga';		//アイルランド語
	const GD		= 'gd';		//スコッチ ゲール語
	const GL		= 'gl';		//ガリチア語
	const HR		= 'hr';		//クロアチア語
	const HU		= 'hu';		//ハンガリー語
	const ID		= 'id';		//インドネシア語
	const IS		= 'is';		//アイスランド語
	const IT		= 'it';		//イタリア語
	const JA		= 'ja';		//日本語
	const KO		= 'ko';		//韓国語
	const MK		= 'mk';		//マケドニア語
	const NL		= 'nl';		//オランダ語
	const NL_BE		= 'nl-BE';	//オランダ語/ベルギー語
	const NO		= 'no';		//ノルウェー語
	const PL		= 'pl';		//ポーランド語
	const PT		= 'pt';		//ポルトガル語
	const PT_BR		= 'pt-BR';	//ポルトガル語/ブラジル
	const RO		= 'ro';		//ルーマニア語
	const RU		= 'ru';		//ロシア語
	const SK		= 'sk';		//スロヴァキア語
	const SL		= 'sl';		//スロヴェニア語
	const SQ		= 'sq';		//アルバニア語
	const SR		= 'sr';		//セルビア語
	const SV		= 'sv';		//スウェーデン語
	const TR		= 'tr';		//トルコ語
	const UK		= 'uk';		//ウクライナ語
	const ZH		= 'zh';		//中国語
	const ZH_CN		= 'zh-CN';	//中国語/中国
	const ZH_TW		= 'zh-TW';	//中国語/台湾

	//======================================================
	//言語の日本語訳
	//======================================================
	const MSG_AF		= 'アフリカーンス語';
	const MSG_BE		= '白ロシア語';
	const MSG_BG		= 'ブルアリア語';
	const MSG_CA		= 'カタロニア語';
	const MSG_CS		= 'チェコ語';
	const MSG_DA		= 'デンマーク語';
	const MSG_DE		= 'ドイツ語';
	const MSG_DE_AU		= 'ドイツ語/オーストリア';
	const MSG_DE_CH		= 'ドイツ語/スイス';
	const MSG_DE_DE		= 'ドイツ語/ドイツ';
	const MSG_EL		= 'ギリシア語';
	const MSG_EN		= '英語';
	const MSG_EN_GB		= '英語/英国';
	const MSG_EN_US		= '英語/米国';
	const MSG_ES		= 'スペイン語';
	const MSG_ES_AR		= 'スペイン語/アルゼンチン';
	const MSG_ES_CO		= 'スペイン語/コロンビア';
	const MSG_ES_ES		= 'スペイン語/スペイン';
	const MSG_ES_MX		= 'スペイン語/メキシコ';
	const MSG_EU		= 'バスク語';
	const MSG_FI		= 'フィンランド語';
	const MSG_FO		= 'フェロー語';
	const MSG_FR		= 'フランス語';
	const MSG_FR_BE		= 'フランス語/ベルギー';
	const MSG_FR_CA		= 'フランス語/カナダ';
	const MSG_FR_CH		= 'フランス語/スイス';
	const MSG_FR_FR		= 'フランス語/フランス';
	const MSG_GA		= 'アイルランド語';
	const MSG_GD		= 'スコッチ ゲール語';
	const MSG_GL		= 'ガリチア語';
	const MSG_HR		= 'クロアチア語';
	const MSG_HU		= 'ハンガリー語';
	const MSG_ID		= 'インドネシア語';
	const MSG_IS		= 'アイスランド語';
	const MSG_IT		= 'イタリア語';
	const MSG_JA		= '日本語';
	const MSG_KO		= '韓国語';
	const MSG_MK		= 'マケドニア語';
	const MSG_NL		= 'オランダ語';
	const MSG_NL_BE		= 'オランダ語/ベルギー語';
	const MSG_NO		= 'ノルウェー語';
	const MSG_PL		= 'ポーランド語';
	const MSG_PT		= 'ポルトガル語';
	const MSG_PT_BR		= 'ポルトガル語/ブラジル';
	const MSG_RO		= 'ルーマニア語';
	const MSG_RU		= 'ロシア語';
	const MSG_SK		= 'スロヴァキア語';
	const MSG_SL		= 'スロヴェニア語';
	const MSG_SQ		= 'アルバニア語';
	const MSG_SR		= 'セルビア語';
	const MSG_SV		= 'スウェーデン語';
	const MSG_TR		= 'トルコ語';
	const MSG_UK		= 'ウクライナ語';
	const MSG_ZH		= '中国語';
	const MSG_ZH_CN		= '中国語/中国';
	const MSG_ZH_TW		= '中国語/台湾';

	//======================================================
	//言語グループ
	//======================================================
	/**
	 * @var	array	ドイツ語グループ
	 * @static
	 */
	const GROUP_DE		= [
		self::DE_AU	=> self::DE_AU,	//ドイツ語/オーストリア
		self::DE_CH	=> self::DE_CH,	//ドイツ語/スイス
		self::DE_DE	=> self::DE_DE,	//ドイツ語/ドイツ
	];

	/**
	 * @var	array	英語グループ
	 * @static
	 */
	const GROUP_EN = [
		self::EN_GB		=> self::EN_GB,	//英語/英国
		self::EN_US		=> self::EN_US,	//英語/米国
	];

	/**
	 * @var	array	スペイン語グループ
	 * @static
	 */
	const GROUP_ES = [
			self::ES_AR		=> self::ES_AR,	//スペイン語/アルゼンチン
			self::ES_CO		=> self::ES_CO,	//スペイン語/コロンビア
			self::ES_ES		=> self::ES_ES,	//スペイン語/スペイン
			self::ES_MX		=> self::ES_MX,	//スペイン語/メキシコ
	];

	/**
	 * @var	array	フランス語グループ
	 * @static
	 */
	const GROUP_FR = [
		self::FR_BE		=> self::FR_BE,	//フランス語/ベルギー
		self::FR_CA		=> self::FR_CA,	//フランス語/カナダ
		self::FR_CH		=> self::FR_CH,	//フランス語/スイス
		self::FR_FR		=> self::FR_FR,	//フランス語/フランス
	];

	/**
	 * @var	array	オランダ語グループ
	 * @static
	 */
	const GROUP_NL = [
		self::NL_BE		=> self::NL_BE,	//オランダ語/ベルギー語
	];

	/**
	 * @var	array	ポルトガル語グループ
	 * @static
	 */
	const GROUP_PT = [
		self::PT_BR		=> self::PT_BR,	//ポルトガル語/ブラジル
	];

	/**
	 * @var	array	中国語グループ
	 * @static
	 */
	const GROUP_ZH = [
		self::ZH_CN		=> self::ZH_CN,	//中国語/中国
		self::ZH_TW		=> self::ZH_TW,	//中国語/台湾
	];

	//======================================================
	//デフォルト言語
	//======================================================
	const DEFAULT_LANG	= self::JA;

	/**
	 * 許可されている言語設定を優先度付きで返します。
	 *
	 * @param	string	$http_accept_language	許可されている言語設定 HTTP accept language header上での形式に依存する。
	 * @return	array	許可されている言語設定のリスト
	 */
	public static function GetAcceptLanguageList ($http_accept_language = null) {
		$http_accept_language !== null ?: $http_accept_language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
		$language_set = [];
		foreach (explode(',', $http_accept_language) as $element) {
			$element = explode(';', $element);
			$language_set[$element[0]] = isset($element[1]) ? (float) substr($element[1], 2) : 1.0;;
		}
		arsort($language_set);
		return $language_set;
	}

	/**
	 * デフォルトの許可言語設定名を返します。
	 *
	 * @param unknown $http_accept_language
	 * @return mixed
	 */
	public static function GetDefaultAcceptLanguage ($http_accept_language = null) {
		$accept_language_list = static::GetAcceptLanguageList($http_accept_language);
		return key($accept_language_list);
	}

	/**
	 * 言語リストを返します。
	 *
	 * @return multitype:string
	 */
	public static function GetLanguageList () {
		return [
			static::AF		=> static::MSG_AF,		//アフリカーンス語
			static::BE		=> static::MSG_BE,		//白ロシア語
			static::BG		=> static::MSG_BG,		//ブルアリア語
			static::CA		=> static::MSG_CA,		//カタロニア語
			static::CS		=> static::MSG_CS,		//チェコ語
			static::DA		=> static::MSG_DA,		//デンマーク語
			static::DE		=> static::MSG_DE,		//ドイツ語
			static::DE_AU	=> static::MSG_DE_AU,	//ドイツ語/オーストリア
			static::DE_CH	=> static::MSG_DE_CH,	//ドイツ語/スイス
			static::DE_DE	=> static::MSG_DE_DE,	//ドイツ語/ドイツ
			static::EL		=> static::MSG_EL,		//ギリシア語
			static::EN		=> static::MSG_EN,		//英語
			static::EN_GB	=> static::MSG_EN_GB,	//英語/英国
			static::EN_US	=> static::MSG_EN_US,	//英語/米国
			static::ES		=> static::MSG_ES,		//スペイン語
			static::ES_AR	=> static::MSG_ES_AR,	//スペイン語/アルゼンチン
			static::ES_CO	=> static::MSG_ES_CO,	//スペイン語/コロンビア
			static::ES_ES	=> static::MSG_ES_ES,	//スペイン語/スペイン
			static::ES_MX	=> static::MSG_ES_MX,	//スペイン語/メキシコ
			static::EU		=> static::MSG_EU,		//バスク語
			static::FI		=> static::MSG_FI,		//フィンランド語
			static::FO		=> static::MSG_FO,		//フェロー語
			static::FR		=> static::MSG_FR,		//フランス語
			static::FR_BE	=> static::MSG_FR_BE,	//フランス語/ベルギー
			static::FR_CA	=> static::MSG_FR_CA,	//フランス語/カナダ
			static::FR_CH	=> static::MSG_FR_CH,	//フランス語/スイス
			static::FR_FR	=> static::MSG_FR_FR,	//フランス語/フランス
			static::GA		=> static::MSG_GA,		//アイルランド語
			static::GD		=> static::MSG_GD,		//スコッチ ゲール語
			static::GL		=> static::MSG_GL,		//ガリチア語
			static::HR		=> static::MSG_HR,		//クロアチア語
			static::HU		=> static::MSG_HU,		//ハンガリー語
			static::ID		=> static::MSG_ID,		//インドネシア語
			static::IS		=> static::MSG_IS,		//アイスランド語
			static::IT		=> static::MSG_IT,		//イタリア語
			static::JA		=> static::MSG_JA,		//日本語
			static::KO		=> static::MSG_KO,		//韓国語
			static::MK		=> static::MSG_MK,		//マケドニア語
			static::NL		=> static::MSG_NL,		//オランダ語
			static::NL_BE	=> static::MSG_NL_BE,	//オランダ語/ベルギー語
			static::NO		=> static::MSG_NO,		//ノルウェー語
			static::PL		=> static::MSG_PL,		//ポーランド語
			static::PT		=> static::MSG_PT,		//ポルトガル語
			static::PT_BR	=> static::MSG_PT_BR,	//ポルトガル語/ブラジル
			static::RO		=> static::MSG_RO,		//ルーマニア語
			static::RU		=> static::MSG_RU,		//ロシア語
			static::SK		=> static::MSG_SK,		//スロヴァキア語
			static::SL		=> static::MSG_SL,		//スロヴェニア語
			static::SQ		=> static::MSG_SQ,		//アルバニア語
			static::SR		=> static::MSG_SR,		//セルビア語
			static::SV		=> static::MSG_SV,		//スウェーデン語
			static::TR		=> static::MSG_TR,		//トルコ語
			static::UK		=> static::MSG_UK,		//ウクライナ語
			static::ZH		=> static::MSG_ZH,		//中国語
			static::ZH_CN	=> static::MSG_ZH_CN,	//中国語/中国
			static::ZH_TW	=> static::MSG_ZH_TW,	//中国語/台湾
		];
	}

	/**
	 * 言語グループのマップを返します。
	 *
	 * @return multitype:string
	 */
	public static function GetGroupMap () {
		return [
			static::DE	=> static::GROUP_DE,
			static::EN	=> static::GROUP_EN,
			static::ES	=> static::GROUP_ES,
			static::FR	=> static::GROUP_FR,
			static::NL	=> static::GROUP_NL,
			static::PT	=> static::GROUP_PT,
			static::ZH	=> static::GROUP_ZH,
		];
	}

	/**
	 * 言語グループの逆引きマップを返します。
	 */
	public static function GetReverseGroupMap () {
		static $reverse_group_map;
		if (!isset($reverse_group_map)) {
			foreach (static::GetGroupMap() as $group_lang => $group_map) {
				foreach ($group_map as $lang) {
					$reverse_group_map[$lang] = $group_lang;
				}
			}
		}
		return $reverse_group_map;
	}
}


<?php

namespace Philip\Plugin;

use Philip\AbstractPlugin as BasePlugin;
use Philip\IRC\Response;
use Philip\IRC\Event;

/**
 * Looks up a random image based on a keyword.
 *
 * @author Bill Israel <bill.israel@gmail.com>
 */
class ImageMePlugin extends BasePlugin
{
    /**
     * Initialize the plugin.
     */
    public function init()
    {
        // Ugh...PHP 5.3, you're killin' me.
        $that = $this;

        // Get me an image!
        $this->bot->onChannel('/^!(?:img|image) (.+)$/i', function(Event $event) use ($that) {
            $matches = $event->getMatches();
            if ($img = $that->getImage(trim($matches[0]), false)) {
                $event->addResponse(Response::msg($event->getRequest()->getSource(), $img));
            }
        });

        // Get me a gif!
        $this->bot->onChannel('/^!gif (.+)$/i', function(Event $event) use ($that) {
            $matches = $event->getMatches();
            if ($img = $that->getImage(trim($matches[0]), true)) {
                $event->addResponse(Response::msg($event->getRequest()->getSource(), $img));
            }
        });
    }

    /**
     * Uses the (deprecated) Google Images API to locate a random image
     *
     * @param string  $term The term to search for
     * @param boolean $gif  True if you only want to search for gifs
     *
     * @return mixed The URL of a found image, null otherwise
     */
    public function getImage($term, $gif = false) {
        $term = urlencode($term);
        $url = "http://ajax.googleapis.com/ajax/services/search/images?q={$term}&v=1.0&rsz=8&safe=active";

        if ($gif) {
            $url .= "&as_filetype=gif";
        }

        $json = trim(file_get_contents($url));
        $decoded = json_decode($json, true);
        $results = isset($decoded['responseData']['results']) ? $decoded['responseData']['results'] : array();

        if (!empty($results)) {
            $result = $results[array_rand($results)];
            return $result['unescapedUrl'];
        }
    }

    /**
     * Help messages!
     */
    public function displayHelp(Event $event)
    {
        return array(
          '!img <keyword> - find a random images that matches the keyword',
          '!gif <keyword> - find a random GIF that matches the keyword',
        );
    }

    /**
     * @see \Philip\AbstractPlugin#getName()
     */
    public function getName()
    {
        return 'ImageMePlugin';
    }
}


<?php

namespace Reaction\Validators;

use Reaction;
use Reaction\Assets\ValidationAsset;
use Reaction\Exceptions\InvalidConfigException;
use Reaction\Helpers\Html;
use Reaction\I18n\I18N;

/**
 * CompareValidator compares the specified attribute value with another value.
 *
 * The value being compared with can be another attribute value
 * (specified via [[compareAttribute]]) or a constant (specified via
 * [[compareValue]]. When both are specified, the latter takes
 * precedence. If neither is specified, the attribute will be compared
 * with another attribute whose name is by appending "_repeat" to the source
 * attribute name.
 *
 * CompareValidator supports different comparison operators, specified
 * via the [[operator]] property.
 *
 * The default comparison function is based on string values, which means the values
 * are compared byte by byte. When comparing numbers, make sure to set the [[$type]]
 * to [[TYPE_NUMBER]] to enable numeric comparison.
 */
class CompareValidator extends Validator
{
    /**
     * Constant for specifying the comparison [[type]] by numeric values.
     * @see type
     */
    const TYPE_STRING = 'string';
    /**
     * Constant for specifying the comparison [[type]] by numeric values.
     * @see type
     */
    const TYPE_NUMBER = 'number';

    /**
     * @var string the name of the attribute to be compared with. When both this property
     * and [[compareValue]] are set, the latter takes precedence. If neither is set,
     * it assumes the comparison is against another attribute whose name is formed by
     * appending '_repeat' to the attribute being validated. For example, if 'password' is
     * being validated, then the attribute to be compared would be 'password_repeat'.
     * @see compareValue
     */
    public $compareAttribute;
    /**
     * @var mixed the constant value to be compared with. When both this property
     * and [[compareAttribute]] are set, this property takes precedence.
     * @see compareAttribute
     */
    public $compareValue;
    /**
     * @var string the type of the values being compared. The follow types are supported:
     *
     * - [[TYPE_STRING|string]]: the values are being compared as strings. No conversion will be done before comparison.
     * - [[TYPE_NUMBER|number]]: the values are being compared as numbers. String values will be converted into numbers before comparison.
     */
    public $type = self::TYPE_STRING;
    /**
     * @var string the operator for comparison. The following operators are supported:
     *
     * - `==`: check if two values are equal. The comparison is done is non-strict mode.
     * - `===`: check if two values are equal. The comparison is done is strict mode.
     * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
     * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
     * - `>`: check if value being validated is greater than the value being compared with.
     * - `>=`: check if value being validated is greater than or equal to the value being compared with.
     * - `<`: check if value being validated is less than the value being compared with.
     * - `<=`: check if value being validated is less than or equal to the value being compared with.
     *
     * When you want to compare numbers, make sure to also set [[type]] to `number`.
     */
    public $operator = '==';
    /**
     * @var string the user-defined error message. It may contain the following placeholders which
     * will be replaced accordingly by the validator:
     *
     * - `{attribute}`: the label of the attribute being validated
     * - `{value}`: the value of the attribute being validated
     * - `{compareValue}`: the value or the attribute label to be compared with
     * - `{compareAttribute}`: the label of the attribute to be compared with
     * - `{compareValueOrAttribute}`: the value or the attribute label to be compared with
     */
    public $message;

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        if ($this->message === null) {
            switch ($this->operator) {
                case '==':
                    $this->message = Reaction::t('rct', '{attribute} must be equal to "{compareValueOrAttribute}".');
                    break;
                case '===':
                    $this->message = Reaction::t('rct', '{attribute} must be equal to "{compareValueOrAttribute}".');
                    break;
                case '!=':
                    $this->message = Reaction::t('rct', '{attribute} must not be equal to "{compareValueOrAttribute}".');
                    break;
                case '!==':
                    $this->message = Reaction::t('rct', '{attribute} must not be equal to "{compareValueOrAttribute}".');
                    break;
                case '>':
                    $this->message = Reaction::t('rct', '{attribute} must be greater than "{compareValueOrAttribute}".');
                    break;
                case '>=':
                    $this->message = Reaction::t('rct', '{attribute} must be greater than or equal to "{compareValueOrAttribute}".');
                    break;
                case '<':
                    $this->message = Reaction::t('rct', '{attribute} must be less than "{compareValueOrAttribute}".');
                    break;
                case '<=':
                    $this->message = Reaction::t('rct', '{attribute} must be less than or equal to "{compareValueOrAttribute}".');
                    break;
                default:
                    throw new InvalidConfigException("Unknown operator: {$this->operator}");
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function validateAttribute($model, $attribute)
    {
        $value = $model->$attribute;
        if (is_array($value)) {
            $this->addError($model, $attribute, Reaction::t('rct', '{attribute} is invalid.'));

            return;
        }
        if ($this->compareValue !== null) {
            $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
        } else {
            $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
            $compareValue = $model->$compareAttribute;
            $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
        }

        if (!$this->compareValues($this->operator, $this->type, $value, $compareValue)) {
            $this->addError($model, $attribute, $this->message, [
                'compareAttribute' => $compareLabel,
                'compareValue' => $compareValue,
                'compareValueOrAttribute' => $compareValueOrAttribute,
            ]);
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function validateValue($value)
    {
        if ($this->compareValue === null) {
            throw new InvalidConfigException('CompareValidator::compareValue must be set.');
        }
        if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
            return [$this->message, [
                'compareAttribute' => $this->compareValue,
                'compareValue' => $this->compareValue,
                'compareValueOrAttribute' => $this->compareValue,
            ]];
        }

        return null;
    }

    /**
     * Compares two values with the specified operator.
     * @param string $operator the comparison operator
     * @param string $type the type of the values being compared
     * @param mixed $value the value being compared
     * @param mixed $compareValue another value being compared
     * @return bool whether the comparison using the specified operator is true.
     */
    protected function compareValues($operator, $type, $value, $compareValue)
    {
        if ($type === self::TYPE_NUMBER) {
            $value = (float)$value;
            $compareValue = (float)$compareValue;
        } else {
            $value = (string)$value;
            $compareValue = (string)$compareValue;
        }
        switch ($operator) {
            case '==':
                return $value == $compareValue;
            case '===':
                return $value === $compareValue;
            case '!=':
                return $value != $compareValue;
            case '!==':
                return $value !== $compareValue;
            case '>':
                return $value > $compareValue;
            case '>=':
                return $value >= $compareValue;
            case '<':
                return $value < $compareValue;
            case '<=':
                return $value <= $compareValue;
            default:
                return false;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clientValidateAttribute($model, $attribute, $view)
    {
        ValidationAsset::register($view);
        $options = $this->getClientOptions($model, $attribute);

        return 'reaction.validation.compare(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', $form);';
    }

    /**
     * {@inheritdoc}
     */
    public function getClientOptions($model, $attribute)
    {
        $options = [
            'operator' => $this->operator,
            'type' => $this->type,
        ];

        if ($this->compareValue !== null) {
            $options['compareValue'] = $this->compareValue;
            $compareLabel = $compareValue = $compareValueOrAttribute = $this->compareValue;
        } else {
            $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
            $compareValue = $model->getAttributeLabel($compareAttribute);
            $options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
            $compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
        }

        if ($this->skipOnEmpty) {
            $options['skipOnEmpty'] = 1;
        }

        $options['message'] = $this->formatMessage($this->message, [
            'attribute' => $model->getAttributeLabel($attribute),
            'compareAttribute' => $compareLabel,
            'compareValue' => $compareValue,
            'compareValueOrAttribute' => $compareValueOrAttribute,
        ]);

        return $options;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension as BaseExtension;
use Symfony\Component\Yaml\Yaml;

/**
 * Class Extension
 * @package Ekyna\Bundle\CoreBundle\DependencyInjection
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
abstract class Extension extends BaseExtension implements PrependExtensionInterface
{
    protected $configDirectory = '/../Resources/config';

    /**
     * {@inheritDoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        if (is_dir($dir = $this->getConfigurationDirectory().'/prepend')) {
            $bundles = $container->getParameter('kernel.bundles');
            $finder = new Finder();

            /** @var \Symfony\Component\Finder\SplFileInfo $file */
            foreach ($finder->in($this->getConfigurationDirectory() . '/prepend')->files()->name('*.yml') as $file) {
                $bundle = $file->getBasename('.yml');
                if (array_key_exists($bundle, $bundles)) {
                    $configs = Yaml::parse($file->getRealPath());
                    foreach ($configs as $key => $config) {
                        $container->prependExtensionConfig($key, $config);
                    }
                }
            }
        }
    }

    /**
     * Returns the configuration directory.
     *
     * @return string
     * @throws \Exception
     */
    protected function getConfigurationDirectory()
    {
        $reflector = new \ReflectionClass($this);
        $fileName = $reflector->getFileName();

        if (!is_dir($directory = realpath(dirname($fileName) . $this->configDirectory))) {
            throw new \Exception(sprintf('The configuration directory "%s" does not exists.', $directory));
        }

        return $directory;
    }
}


<?php

namespace Kcs\FunctionMock\Prediction;

use Kcs\FunctionMock\Exception\Call\UnexpectedCallsException;
use Kcs\FunctionMock\FunctionProphecy;
use Prophecy\Call\Call;
use Prophecy\Util\StringUtil;

class NoCallsPrediction implements PredictionInterface
{
    private $util;

    /**
     * Initializes prediction.
     *
     * @param null|StringUtil $util
     */
    public function __construct(StringUtil $util = null)
    {
        $this->util = $util ?: new StringUtil();
    }

    /**
     * Tests that there were no calls made.
     *
     * @param Call[]         $calls
     * @param FunctionProphecy $prophecy
     *
     * @throws UnexpectedCallsException
     */
    public function check(array $calls, FunctionProphecy $prophecy)
    {
        if (!count($calls)) {
            return;
        }

        $verb = count($calls) === 1 ? 'was' : 'were';

        throw new UnexpectedCallsException(sprintf(
            "No calls expected that match:\n".
            "  %s(%s)\n".
            "but %d %s made:\n%s",
            $prophecy->getName(),
            $prophecy->getArgumentsWildcard(),
            count($calls),
            $verb,
            $this->util->stringifyCalls($calls)
        ));
    }
}


<?php
/**
 * Драйвер MySQL
 *
 * @version ${product.version}
 *
 * @copyright 2011, Михаил Красильников <m.krasilnikov@yandex.ru>
 * @license http://www.gnu.org/licenses/gpl.txt	GPL License 3
 * @author Михаил Красильников <m.krasilnikov@yandex.ru>
 *
 * Данная программа является свободным программным обеспечением. Вы
 * вправе распространять ее и/или модифицировать в соответствии с
 * условиями версии 3 либо (по вашему выбору) с условиями более поздней
 * версии Стандартной Общественной Лицензии GNU, опубликованной Free
 * Software Foundation.
 *
 * Мы распространяем эту программу в надежде на то, что она будет вам
 * полезной, однако НЕ ПРЕДОСТАВЛЯЕМ НА НЕЕ НИКАКИХ ГАРАНТИЙ, в том
 * числе ГАРАНТИИ ТОВАРНОГО СОСТОЯНИЯ ПРИ ПРОДАЖЕ и ПРИГОДНОСТИ ДЛЯ
 * ИСПОЛЬЗОВАНИЯ В КОНКРЕТНЫХ ЦЕЛЯХ. Для получения более подробной
 * информации ознакомьтесь со Стандартной Общественной Лицензией GNU.
 *
 * Вы должны были получить копию Стандартной Общественной Лицензии
 * GNU с этой программой. Если Вы ее не получили, смотрите документ на
 * <http://www.gnu.org/licenses/>
 *
 * @package ORM
 */

/**
 * Драйвер MySQL
 *
 * @package ORM
 * @since 1.00
 */
class ORM_Driver_MySQL extends ORM_Driver_SQL
{
    /**
     * Возвращает выражение SQL для описания поля таблицы
     *
     * @param ORM_Field_Abstract $field  поле
     *
     * @return string  SQL
     */
    protected function getFieldDefinition(ORM_Field_Abstract $field)
    {
        $sql = parent::getFieldDefinition($field);
        $sql = preg_replace('/^(\w+)/', '`$1`', $sql);
        return $sql;
    }

    /**
     * Возвращает выражение SQL для создания таблицы
     *
     * @param string   $name        имя таблицы
     * @param string[] $fields      выражения для полей
     * @param string   $primaryKey  выражение для главного ключа
     * @param string[] $indexes     выражения для индексов
     *
     * @return string  SQL
     */
    protected function getCreateTableDefinition($name, $fields, $primaryKey, $indexes)
    {
        return "CREATE TABLE $name ("
        . implode(', ', array_merge($fields, array($primaryKey), $indexes))
        . ') ENGINE InnoDB DEFAULT CHARSET=utf8';
    }

    /**
     * Возвращает объявление индекса
     *
     * @param string $name
     * @param array  $params
     *
     * @return string  SQL
     */
    protected function getIndexDefinition($name, array $params)
    {
        foreach ($params['fields'] as &$fieldName)
        {
            $fieldName = "`$fieldName`";
        }
        $sql = parent::getIndexDefinition($name, $params);
        return $sql;
    }
}


<?php

namespace PhpPlatform\Persist\Connection;

use PhpPlatform\Config\Settings;
use PhpPlatform\Errors\Exceptions\Persistence\NoConnectionException;

final class ConnectionFactory {
	private static $connection = null;

	/**
	 * This method creates and returns connection implementaion , based on the configuration property 'connection-class'
	 *
	 * @throws NoConnectionException
	 * @return Connection
	 */
	static function getConnection($forceNewConnection = false){
		if(self::$connection == null || $forceNewConnection){
			$connectionImpl = Settings::getSettings('php-platform/persist','connection-class');
			$connectionImplReflectionClass = new \ReflectionClass($connectionImpl);
			$connectionImplInterfaces = $connectionImplReflectionClass->getInterfaceNames();
			$connectionInterfaceName = 'PhpPlatform\Persist\Connection\Connection';
			if(!in_array($connectionInterfaceName, $connectionImplInterfaces)){
				throw new NoConnectionException("connection implementation $connectionImpl does not implement $connectionInterfaceName");
			}
			self::$connection = $connectionImplReflectionClass->newInstance();
		}
		return self::$connection;
	}

}


<?php

namespace Ekyna\Bundle\CoreBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader;

/**
 * Class EkynaCoreExtension
 * @package Ekyna\Bundle\CoreBundle\DependencyInjection
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class EkynaCoreExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');

        $routers = (array) $config['chain_router']['routers_by_id'];
        if (!empty($routers)) {
            $container->setParameter('ekyna_core.chain_router.routers', $routers);
        }

        $container->setParameter('ekyna_core.ui_config', $config['ui']);
        $container->setParameter('ekyna_core.cache_config', $config['cache']);

        /* Inheritance mapping = [
         *     resource_id => [
         *         'class' => Class ,
         *         'repository' => Repository class ,
         *     ]
         * ] */
        if (!$container->hasParameter('ekyna_core.entities')) {
            $container->setParameter('ekyna_core.entities', []);
        }

        /* Target entities resolution
         * [ Interface => Class or class parameter ]
         */
        if (!$container->hasParameter('ekyna_core.interfaces')) {
            $container->setParameter('ekyna_core.interfaces', []);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        parent::prepend($container);

        $bundles = $container->getParameter('kernel.bundles');
        $configs = $container->getExtensionConfig($this->getAlias());
        $config = $this->processConfiguration(new Configuration(), $configs);

        if (array_key_exists('AsseticBundle', $bundles)) {
            $this->configureAsseticBundle($container, $config['assets']);
        }
        if (array_key_exists('TwigBundle', $bundles)) {
            $this->configureTwigBundle($container);
        }
        if (array_key_exists('BraincraftedBootstrapBundle', $bundles)) {
            $this->configureBraincraftedBootstrapBundle($container);
        }
        if (array_key_exists('KnpMenuBundle', $bundles)) {
            $this->configureKnpMenuBundle($container);
        }
        if (array_key_exists('StfalconTinymceBundle', $bundles)) {
            $this->configureStfalconTinymceBundle($container, $config, $bundles);
        }
        if ($config['cache']['enable'] && array_key_exists('FOSHttpCacheBundle', $bundles)) {
            $this->configureFOSHttpCacheBundle($container);
        }
    }

    /**
     * Configures the TwigBundle.
     *
     * @param ContainerBuilder $container
     */
    protected function configureTwigBundle(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('twig', [
            'form' => ['resources' => ['EkynaCoreBundle:Form:form_div_layout.html.twig']],
        ]);
    }

    /**
     * Configures the AsseticBundle.
     *
     * @param ContainerBuilder $container
     * @param array            $config
     */
    protected function configureAsseticBundle(ContainerBuilder $container, array $config)
    {
        $asseticConfig = new AsseticConfiguration();
        $container->prependExtensionConfig('assetic', [
            'assets' => $asseticConfig->build($config),
            'bundles' => ['EkynaCoreBundle'],
        ]);
    }

    /**
     * Configures the BraincraftedBootstrapBundle.
     *
     * @param ContainerBuilder $container
     */
    protected function configureBraincraftedBootstrapBundle(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('braincrafted_bootstrap', [
            'auto_configure' => [
                'twig' => false,
                'assetic' => false,
                'knp_menu' => false,
            ],
        ]);
    }

    /**
     * Configures the KnpMenuBundle.
     *
     * @param ContainerBuilder $container
     */
    protected function configureKnpMenuBundle(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('knp_menu', [
            'twig' => [
                'template' => 'EkynaCoreBundle:Ui:menu.html.twig',
            ],
        ]);
    }

    /**
     * Configures the StfalconTinymceBundle.
     *
     * @param ContainerBuilder $container
     * @param array            $config
     * @param array            $bundles
     */
    protected function configureStfalconTinymceBundle(ContainerBuilder $container, array $config, array $bundles)
    {
        $tinymceConfig = new TinymceConfiguration();
        $container->prependExtensionConfig('stfalcon_tinymce', $tinymceConfig->build($config, $bundles));
    }

    /**
     * Configures the FOSHttpCacheBundle.
     *
     * @param ContainerBuilder $container
     */
    protected function configureFOSHttpCacheBundle(ContainerBuilder $container)
    {
        $container->prependExtensionConfig('fos_http_cache', [
            'proxy_client' => [
                'default' =>  'varnish',
                'varnish' => [
                    'servers' =>  "%reverse_proxy.host%:%reverse_proxy.port%",
                    'base_url' => "%hostname%:%reverse_proxy.port%",
                ],
            ],
        ]);
    }
}


<?php
/**
 * Plugin Name: Editor capabilities
 * Description: Sets up the editor role a bit different.
 *
 * Plugin URI: https://github.com/trendwerk/editor-capabilities
 *
 * Author: Trendwerk
 * Author URI: https://github.com/trendwerk
 *
 * Version: 1.0.1
 */

class TP_Editor_Capabilities {
	function __construct() {
		add_action( 'init', array( $this, 'set_capabilities' ) );
		add_filter( 'map_meta_cap', array( $this, 'limit_lower_roles' ), 10, 4);
	}

	/**
	 * Set some of the editors capabilities
	 */
	function set_capabilities() {
		$editor = get_role( 'editor' );

		$editor->add_cap( 'list_users' );
		$editor->add_cap( 'remove_users' );
		$editor->add_cap( 'add_users' );
		$editor->add_cap( 'promote_users' );
		$editor->add_cap( 'create_users' );
		$editor->add_cap( 'delete_users' );
		$editor->add_cap( 'edit_users' );

		$editor->add_cap( 'edit_theme_options' );
		$editor->remove_cap( 'switch_themes' );
	}

  	/**
  	 * Refrain non-admins from editing / promoting / deleting administrators
  	 */
	function limit_lower_roles( $caps, $cap, $user_id, $args ) {
		if( 'promote_user' == $cap ) {

			if( ! isset( $args[0] ) )
				$caps[] = 'do_not_allow';

			if( $args[0] == $user_id )
				$caps[] = 'do_not_allow';

			$other = new WP_User( absint( $args[0] ) );
			if( $other->has_cap('administrator') && ! current_user_can( 'administrator' ) )
				$caps[] = 'do_not_allow';

		} else if( $cap == 'delete_users' || $cap == 'edit_user' ) {
			if( ! isset( $_GET['user'] ) )
				return $caps;

			$other_id = absint( $_GET['user'] );

			if( ! $other_id )
				return $caps;

			if( $other_id == $user_id )
				return $caps;

			$other = new WP_User( $other_id );
			if( $other->has_cap( 'administrator' ) && ! current_user_can( 'administrator' ) )
				$caps[] = 'do_not_allow';

		}

		return $caps;
	}
} new TP_Editor_Capabilities;


<?php
namespace Nubs\Which\LocatorFactory;

use Habitat\Environment\Environment;
use Nubs\Which\Locator;
use Nubs\Which\PathBuilder\WindowsPathBuilder;

/**
 * Locator factory for Windows systems.
 */
class WindowsLocatorFactory implements LocatorFactoryInterface
{
    /**
     * Create a locator from the PATH and PATHEXT environment variables.
     *
     * @api
     * @param \Habitat\Environment\Environment $environment The environment
     *     variable wrapper.  Defaults to null which just uses PHP's built-in
     *     getenv.
     * @return \Nubs\Which\Locator The locator.
     */
    public function create(Environment $environment = null)
    {
        return $this->createFromPath(
            $environment ? $environment->getenv('PATH') : getenv('PATH'),
            $environment ? $environment->getenv('PATHEXT') : getenv('PATHEXT')
        );
    }

    /**
     * Create a locator using semicolon-separated PATH and PATHEXT strings.
     *
     * The semicolon is a hard separator.  This means that command paths cannot
     * have a semicolon in the name.
     *
     * The current working directory is always prepended to the list of paths.
     *
     * @api
     * @param string $path The semicolon-separated PATH string.
     * @param string $pathext The semicolon-separated PATHEXT string.
     * @return \Nubs\Which\Locator The locator.
     */
    public function createFromPath($path, $pathext)
    {
        $paths = array_merge(['.'], array_filter(explode(';', $path)));
        $extensions = array_merge([''], array_filter(explode(';', $pathext)));
        return new Locator(new WindowsPathBuilder($paths, $extensions));
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Model;

/**
 * Class AbstractConstants
 * @package Ekyna\Bundle\CoreBundle\Model
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
abstract class AbstractConstants implements ConstantsInterface
{
    /**
     * Returns the constants.
     *
     * @return array
     */
    public static function getConstants()
    {
        return array_keys(static::getConfig());
    }

    /**
     * Returns the constant choices.
     *
     * @return array
     */
    public static function getChoices()
    {
        $choices = [];
        foreach (static::getConfig() as $constant => $config) {
            $choices[$constant] = $config[0];
        }
        return $choices;
    }

    /**
     * Returns the label for the given constant.
     *
     * @param mixed $constant
     * @return string
     */
    public static function getLabel($constant)
    {
        if (null === $constant) {
            return 'ekyna_core.value.undefined';
        }

        static::isValid($constant, true);

        return static::getConfig()[$constant][0];
    }

    /**
     * Returns whether the constant is valid or not.
     *
     * @param mixed   $constant
     * @param boolean $throwException
     *
     * @return bool
     */
    public static function isValid($constant, $throwException = false)
    {
        if (array_key_exists($constant, static::getConfig())) {
            return true;
        }

        if ($throwException) {
            throw new \InvalidArgumentException(sprintf('Unknown constant "%s"', $constant));
        }

        return false;
    }
}


<?php

namespace Reaction\Run;

use Reaction\Helpers\ClassFinderHelper;

class Application extends \Symfony\Component\Console\Application
{
    /**
     * @var \Composer\Autoload\ClassLoader
     */
    public $loader;
    /**
     * @var array Commands namespaces
     */
    public $commandsNamespaces = [
        'Reaction\Run\Commands',
    ];

    /**
     * Application constructor.
     * @param \Composer\Autoload\ClassLoader $loader
     * @param string $name
     * @param string $version
     */
    public function __construct($loader, string $name = 'UNKNOWN', string $version = 'UNKNOWN')
    {
        $this->loader = $loader;
        ClassFinderHelper::setLoader($loader);
        parent::__construct($name, $version);
        $this->registerCommands();
    }

    /**
     * Register commands
     */
    protected function registerCommands()
    {
        $commands = ClassFinderHelper::findClassesPsr4($this->commandsNamespaces);
        foreach ($commands as $commandStr) {
            $this->add(new $commandStr());
        }
    }
}


<?php

/**
 * @author    Sorin Badea <sorin.badea91@gmail.com>
 * @license   MIT license (see the license file in the root directory)
 */

namespace ThinFrame\Foundation\Helper;

use ThinFrame\Foundation\Constant\DataType;
use ThinFrame\Foundation\Exception\InvalidArgumentException;

/**
 * Class TypeCheck
 *
 * @package ThinFrame\Foundation\Helpers
 * @since   0.2
 */
final class TypeCheck
{
    const MESSAGE = 'Argument %s passed to %s() must be of type %s, %s given';
    /**
     * Validators for each data type
     *
     * @var array
     */
    protected static $validators = [
        DataType::INT      => 'is_int',
        DataType::BOOLEAN  => 'is_bool',
        DataType::CALLBACK => 'is_callable',
        DataType::FLOAT    => 'is_float',
        DataType::RESOURCE => 'is_resource',
        DataType::DOUBLE   => 'is_double',
        DataType::STRING   => 'ThinFrame\Foundation\Helper\TypeCheck::isString'
    ];

    /**
     * Check if function arguments match the provided types
     */
    public static function doCheck()
    {
        $backtrace         = debug_backtrace();
        $functionArguments = $backtrace[1]['args'];
        $functionName      = $backtrace[1]['function'];
        $doChecks          = func_get_args();

        unset($backtrace);

        array_walk(
            $functionArguments,
            function ($value, $key) use (&$doChecks, $functionName) {
                if (is_null($value) || !isset($doChecks[$key]) || $doChecks[$key] == DataType::SKIP) {
                    return;
                }
                if (!TypeCheck::checkValue($value, $doChecks[$key])) {
                    if (is_callable($doChecks[$key])) {
                        $doChecks[$key] = 'unknown (custom validator)';
                    }
                    if (is_object($value)) {
                        $message = sprintf(
                            TypeCheck::MESSAGE,
                            $key,
                            $functionName,
                            $doChecks[$key],
                            'instance of ' . get_class($value)
                        );
                    } else {
                        $message = sprintf(
                            TypeCheck::MESSAGE,
                            $key,
                            $functionName,
                            $doChecks[$key],
                            gettype($value)
                        );
                    }
                    throw new InvalidArgumentException($message);
                }

            }
        );
    }

    /**
     * Check value against the provided type
     *
     * @param mixed  $value value to be checked
     * @param string $type  value type
     *
     * @return bool
     */
    public static function checkValue($value, $type)
    {
        $validator = is_callable($type) ? $type : (isset(self::$validators[$type]) ? self::$validators[$type] : null);

        if (!is_null($value)) {
            return call_user_func($validator, $value);
        }

        return false;
    }

    /**
     * Check if provided value is a string
     *
     * @param mixed $string string to be checked
     *
     * @return bool
     */
    public static function isString($string)
    {
        if (intval($string) == $string || is_string($string)) {
            return true;
        }

        return false;
    }
}


<?php
/**
 *  Soluble Components (http://belgattitude.github.io/solublecomponents)
 *
 *  @link      http://github.com/belgattitude/solublecomponents for the canonical source repository
 *  @copyright Copyright (c) 2013-2014 Sébastien Vanvelthem
 *  @license   https://github.com/belgattitude/solublecomponents/blob/master/LICENSE.txt MIT License
 */
namespace Soluble\Db\Compat;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\Driver;

class PDO
{
    /**
     * Return a Zend\Db\Adapter\Adapter object from an existing pdo connection
     * @param \PDO $pdo
     * @return Adapter
     */
    public static function getAdapter(\PDO $pdo)
    {
        $driver = new Driver\Pdo\Pdo($pdo);
        $adapter = new Adapter($driver);
        return $adapter;
    }
}


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Laralum\Social\Models\Settings;

class CreateLaralumSocialSettings extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('laralum_social_settings', function (Blueprint $table) {
            $table->increments('id');
            $table->boolean('enabled');
            $table->boolean('allow_register');
            $table->text('facebook_client_id')->nullable();
            $table->text('facebook_client_secret')->nullable();
            $table->text('twitter_client_id')->nullable();
            $table->text('twitter_client_secret')->nullable();
            $table->text('linkedin_client_id')->nullable();
            $table->text('linkedin_client_secret')->nullable();
            $table->text('google_client_id')->nullable();
            $table->text('google_client_secret')->nullable();
            $table->text('github_client_id')->nullable();
            $table->text('github_client_secret')->nullable();
            $table->text('bitbucket_client_id')->nullable();
            $table->text('bitbucket_client_secret')->nullable();
            $table->timestamps();
        });

        Settings::create([
            'enabled'        => false,
            'allow_register' => false,
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('laralum_social_settings');
    }
}


<?php

/*
 * This file is part of madewithlove/service-providers
 *
 * (c) madewithlove <heroes@madewithlove.be>
 *
 * For the full copyright and license information, please view the LICENSE
 */

namespace Madewithlove\ServiceProviders\Http;

use Interop\Container\ServiceProviderInterface;
use League\Container\ImmutableContainerAwareTrait;
use League\Route\RouteCollection;
use League\Route\Strategy\AbstractStrategy;
use League\Route\Strategy\ParamStrategy;
use League\Route\Strategy\StrategyInterface;
use Madewithlove\ServiceProviders\Utilities\Alias;
use Psr\Container\ContainerInterface;

class LeagueRouteServiceProvider implements ServiceProviderInterface
{
    use ImmutableContainerAwareTrait;

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

    /**
     * @param string $strategy
     */
    public function __construct($strategy = ParamStrategy::class)
    {
        $this->strategy = $strategy;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        return [
            StrategyInterface::class => [$this, 'getStrategy'],
            RouteCollection::class => [$this, 'getRouter'],
            'router' => new Alias(RouteCollection::class),
        ];
    }

    /**
     * @param ContainerInterface $container
     *
     * @return StrategyInterface
     */
    public function getStrategy(ContainerInterface $container)
    {
        /** @var AbstractStrategy $strategy */
        $strategy = new $this->strategy();
        $strategy->setContainer($container);

        return $strategy;
    }

    /**
     * @param ContainerInterface $container
     *
     * @return RouteCollection
     */
    public function getRouter(ContainerInterface $container)
    {
        $router = new RouteCollection($container);
        $router->setStrategy($container->get(StrategyInterface::class));

        return $router;
    }
}


<?php
/**
* @package     jelix
* @subpackage  utils
* @author      Sylvain de Vathaire
* @contributor Laurent Jouanneau
* @copyright   2008 Sylvain de Vathaire, 2009-2014 Laurent Jouanneau
* @link        http://www.jelix.org
* @licence     GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
*/

/**
 * object to generate WSDL files and web services documentation
 * we have 1 WSDL file for each soap web service, each service is implemented by 1 Jelix controller
 * @package    jelix
 * @subpackage utils
 */
class jWSDL {

    /**
    * module name
    */
    public $module;

    /**
    * controller name
    */
    public $controller;

    /**
    * controller class name
    */
    private $controllerClassName;

    /**
    * WSDL file path (cached file)
    */
    public $WSDLfilePath;

    private $_ctrlpath;

    private $_dirname = 'WSDL';
    private $_cacheSuffix = '.wsdl';

    public function __construct($module, $controller){

        $this->module = $module;
        $this->controller = $controller;

        $this->_createPath();
        $this->_createCachePath();
     }

    /**
     * create the path for the cache file
     */
    private function _createPath(){
        $config = jApp::config();

        //Check module availability
        if(!isset($config->_modulesPathList[$this->module])){
            throw new jExceptionSelector('jelix~errors.module.unknown', $this->module);
        }

        //Build controller path
        $this->_ctrlpath = $config->_modulesPathList[$this->module].'controllers/'.$this->controller.'.soap.php';

        //Check controller availability
        if(!file_exists($this->_ctrlpath)){
            throw new jException('jelix~errors.action.unknown',$this->controller);
        }

        //Check controller declaration
        require_once($this->_ctrlpath);
        $this->controllerClassName = $this->controller.'Ctrl';
        if(!class_exists($this->controllerClassName,false)){
            throw new jException('jelix~errors.ad.controller.class.unknown', array('jWSDL', $this->controllerClassName, $this->_ctrlpath));
        }

        //Check eAccelerator configuration in order to Reflexion API work
        if (extension_loaded('eAccelerator')) {
            $reflect = new ReflectionClass('jWSDL');
            if($reflect->getDocComment() == NULL) {
                throw new jException('jsoap~errors.eaccelerator.configuration');
            }
            unset($reflect);
        }

    }

    /**
     * Build the WSDL cache file path
     */
    private function _createCachePath(){
        $this->_cachePath = jApp::tempPath('compiled/'.$this->_dirname.'/'.$this->module.'~'.$this->controller.$this->_cacheSuffix);
    }

    /**
     * Return the WSDL cache file path (WSDL is updated if necessary)
     */
    public function getWSDLFilePath(){
        $this->_updateWSDL();
        return $this->_cachePath;
    }

    /**
     * Return the WSDL file content (WSDL is updated if necessary)
     */
    public function getWSDLFile(){
        $this->_updateWSDL();
        return file_get_contents($this->_cachePath);
    }

    /**
     * Return array of params object for the operation $operationName
     * @param string $operationName Name of the operation (controller method)
     * @return array list params object (empty if no params)
     */
    public function getOperationParams($operationName){

       $IPReflectionMethod = new IPReflectionMethod($this->controllerClassName, $operationName);
       return $IPReflectionMethod->getParameters();
    }

    /**
     * Update the WSDL cache file
     */
    private function _updateWSDL(){

        static $updated = FALSE;

        if($updated){
            return;
        }

        $mustCompile = jApp::config()->compilation['force'] || !file_exists($this->_cachePath);
        if(jApp::config()->compilation['checkCacheFiletime'] && !$mustCompile){
            if( filemtime($this->_ctrlpath) > filemtime($this->_cachePath)){
                $mustCompile = true;
            }
        }

        if($mustCompile){
            jFile::write($this->_cachePath, $this->_compile());
        }
        $updated = TRUE;
    }

    /**
     * Generate the WSDL content
     */
    private function _compile(){

        $url = jUrl::get($this->module.'~'.$this->controller.':index@soap',array(),jUrl::JURL);
        $url->clearParam ();
        $url->setParam('service',$this->module.'~'.$this->controller );

        $serverUri = jUrl::getRootUrlRessourceValue('soap');
        if ($serverUri === null) {
            $serverUri = jUrl::getRootUrlRessourceValue('soap-'.$this->module);
        }
        if ($serverUri === null) {
            $serverUri = jUrl::getRootUrlRessourceValue('soap-'.$this->module.'-'.$this->controller);
        }
        if ($serverUri === null) {
            $serverUri = jApp::coord()->request->getServerURI();
        }

        $serviceURL = $serverUri .$url->toString();
        $serviceNameSpace = $serverUri . jApp::urlBasePath();

        $wsdl = new WSDLStruct($serviceNameSpace, $serviceURL, SOAP_RPC, SOAP_ENCODED);
        $wsdl->setService(new IPReflectionClass($this->controllerClassName));

        try {
            $gendoc = $wsdl->generateDocument();
        } catch (WSDLException $exception) {
            throw new JException('jsoap~errors.wsdl.generation', $exception->msg);
        }

        return $gendoc;
    }

    /**
     * Load the class or service definition for doc purpose
     * @param string $classname Name of the class for witch we want the doc, default doc is the service one (controller)
     */
    public function doc($className=""){

        if($className != ""){
            if(!class_exists($className,false)){
                throw new jException('jelix~errors.ad.controller.class.unknown', array('WSDL generation', $className, $this->_ctrlpath));
            }
            $classObject = new IPReflectionClass($className);
        }else{
            $classObject = new IPReflectionClass($this->controllerClassName);
        }

        $documentation = Array();
        $documentation['menu'] = Array();

        if($classObject){
            $classObject->properties = $classObject->getProperties(false, false, false);
            $classObject->methods = $classObject->getMethods(false, false, false);
            foreach((array)$classObject->methods as $method) {
                $method->params = $method->getParameters();
            }

            $documentation['class'] = $classObject;
            $documentation['service'] = $this->module.'~'.$this->controller;
        }
        return $documentation;
    }

    /**
     * Return an array of all the soap controllers class available in the application
     * @return array Classname of controllers
     */
    public static function getSoapControllers(){

        $modules = jApp::config()->_modulesPathList;
        $controllers = array();

        foreach($modules as $module){
            if(is_dir($module.'controllers')){
                if ($handle = opendir($module.'controllers')) {
                    $moduleName = basename($module);
                    while (false !== ($file = readdir($handle))) {
                        if (substr($file, strlen($file) - strlen('.soap.php')) == '.soap.php') {
                            $controller = array();
                            $controller['class'] = substr($file, 0, strlen($file) - strlen('.soap.php'));
                            $controller['module'] = $moduleName;
                            $controller['service'] = $moduleName.'~'.$controller['class'];
                            array_push($controllers, $controller);
                        }
                    }
                    closedir($handle);
                }
            }
        }
        return $controllers;
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\DependencyInjection;

/**
 * Class AsseticConfiguration
 * @package Ekyna\Bundle\CoreBundle\DependencyInjection
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class AsseticConfiguration
{
    /**
     * Builds the assetic configuration.
     *
     * @param array $config
     * @return array
     */
    public function build(array $config)
    {
        $output = [];

        // Fix output dir trailing slash
        if ('/' !== substr($config['output_dir'], -1) && strlen($config['output_dir']) > 0) {
            $config['output_dir'] .= '/';
        }

        if ($config['bootstrap_css']['enabled']) {
            $output['bootstrap_css'] = $this->buildBootstrapCss($config);
        }
        if ($config['content_css']['enabled']) {
            $output['content_css'] = $this->buildContentCss($config);
        }

        $output['twig_js'] = $this->buildTwigJs($config);
        $output['form_css'] = $this->buildFormCss($config);

        return $output;
    }

    /**
     * Builds the content_css asset collection configuration.
     *
     * @param array $config
     * @return array
     */
    protected function buildContentCss(array $config)
    {
        $dir = $config['output_dir'];
        $inputs = $config['content_css']['inputs'];

        return [
            'inputs'  => $inputs,
            'filters' => ['cssrewrite', 'yui_css'],
            'output'  => $dir . 'css/content.css',
            'debug'   => false,
        ];
    }

    /**
     * Builds the bootstrap_css asset collection configuration.
     *
     * @param array $config
     * @return array
     */
    protected function buildBootstrapCss(array $config)
    {
        $dir = $config['output_dir'];
        $inputs = $config['bootstrap_css']['inputs'];

        $inputs[] = 'assets/bootstrap-dialog/dist/css/bootstrap-dialog.min.css';

        return [
            'inputs'  => $inputs,
            'filters' => ['cssrewrite', 'less', 'yui_css'],
            'output'  => $dir . 'css/bootstrap.css',
            'debug'   => false,
        ];
    }

    /**
     * Builds the jquery asset collection configuration.
     *
     * @param array $config
     * @return array
     */
    protected function buildTwigJs(array $config)
    {
        $dir = $config['output_dir'];
        $inputs = ['%kernel.root_dir%/../vendor/jms/twig-js/twig.js'];

        return [
            'inputs'  => $inputs,
//            'filters' => array('yui_js'),
            'output'  => $dir . 'js/twig.js',
            'debug'   => false,
        ];
    }

    /**
     * Builds the core_css asset collection configuration.
     *
     * @param array $config
     * @return array
     */
    protected function buildFormCss(array $config)
    {
        $inputs = array_merge([
            '%kernel.root_dir%/../web/assets/bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.css',
            '@EkynaCoreBundle/Resources/asset/css/lib/bootstrap.colorpickersliders.css',
            '@EkynaCoreBundle/Resources/asset/css/lib/select2.css',
            '@EkynaCoreBundle/Resources/asset/css/lib/jquery.qtip.css',
            '@EkynaCoreBundle/Resources/asset/css/form.css',
            //'@EkynaCoreBundle/Resources/asset/css/modal-gallery.css',
        ], $config['form_css']['inputs']);

        return [
            'inputs'  => $inputs,
            'filters' => ['yui_css'], // 'cssrewrite'
            'output'  => $config['output_dir'] . 'css/form.css',
            'debug'   => false,
        ];
    }
}


<?php

/**
 * Part of the Attachfiles package.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under MIT License.
 *
 * This source file is subject to MIT License that is
 * bundled with this package in the LICENSE file.
 *
 * @package    Attachfiles
 * @version    1.0.0
 * @author     AngryDeer
 * @license    MIT
 * @copyright  (c) 2016, DP Studio
 * @link       http://angrydeer.ru
 */

namespace Angrydeer\Attachfiles;

use Illuminate\Database\Eloquent\Builder;
use File;
use Storage;

trait AttachableTrait
{

    /**
     * The Eloquent attaches model name.
     *
     * @var string
     */
    protected static $attachesModel = 'Angrydeer\Attachfiles\IlluminateAttach';

    /**
     * The Slug generator method.
     *
     * @var string
     */
    protected static $slugGenerator = 'Illuminate\Support\Str::slug';

    /**
     * {@inheritdoc}
     */
    public static function getAttachesModel()
    {
        return static::$attachesModel;
    }

    /**
     * {@inheritdoc}
     */
    public static function setAttachesModel($model)
    {
        static::$attachesModel = $model;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSlugGenerator()
    {
        return static::$slugGenerator;
    }

    /**
     * {@inheritdoc}
     */
    public static function setSlugGenerator($slugGenerator)
    {
        static::$slugGenerator = $slugGenerator;
    }

    /**
     * {@inheritdoc}
     */
    public function attaches()
    {
        return $this->morphToMany(static::$attachesModel, 'attachable', 'attached', 'attachable_id', 'attach_id');
    }

    /**
     * {@inheritdoc}
     */
    public static function allAttaches()
    {
        $instance = new static;

        return $instance->createAttachesModel()->whereNamespace(
            $instance->getEntityClassName()
        );
    }

    /**
     * {@inheritdoc}
     */
    public static function scopeWhereAttach(Builder $query, $attaches, $type = 'filename')
    {
        $attaches = (new static)->prepareAttaches($attaches);

        foreach ($attaches as $attach) {
            $query->whereHas('attaches', function ($query) use ($type, $attach) {
                $query->where($type, $attach);
            });
        }

        return $query;
    }

    /**
     * {@inheritdoc}
     */
    public static function scopeWithAttach(Builder $query, $attaches, $type = 'filename')
    {
        $attaches = (new static)->prepareAttaches($attaches);

        return $query->whereHas('attaches', function ($query) use ($type, $attaches) {
            $query->whereIn($type, $attaches);
        });
    }

    /**
    * {@inheritdoc}
    */
    public static function scopeWithoutAttach(Builder $query, $attaches, $type = 'filename')
    {
        $attaches = (new static)->prepareAttaches($attaches);

        return $query->whereDoesntHave('attaches', function ($query) use ($type, $attaches) {
            $query->whereIn($type, $attaches);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function attach($attaches)
    {
        foreach ($this->prepareAttaches($attaches) as $attach) {
            $this->addAttach($attach);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function unattach($attaches = null)
    {
        $attaches = $attaches ?: $this->attaches->lists('name')->all();

        foreach ($this->prepareAttaches($attaches) as $attach) {
            $this->removeAttach($attach);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function setAttaches($attaches, $type = 'name')
    {
        // Prepare the attaches
        $attaches = $this->prepareAttaches($attaches);

        // Get the current entity attaches
        $entityAttaches = $this->attaches->lists($type)->all();

        // Prepare the attaches to be added and removed
        $attachesToAdd = array_diff($attaches, $entityAttaches);
        $attachesToDel = array_diff($entityAttaches, $attaches);

        // Detach the attaches
        if (! empty($attachesToDel)) {
            $this->unattach($attachesToDel);
        }

        // Attach the attaches
        if (! empty($attachesToAdd)) {
            $this->attach($attachesToAdd);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function addAttach($filename, $title=null, $alt=null, $desc=null)
    {
        $path='attaches/'.date ('Y-m-d').'/';

        $attach = $this->createAttachesModel()->firstOrNew([
            'filename'      => $filename,
            'namespace' => $this->getEntityClassName(),
            'alt' => $alt,
            'desc' => $desc,
            'title' => $title,
        ]);

        if (! $attach->exists) {
            $info = pathinfo($filename);
            if(! $alt) {
                $cleanName = basename($filename,'.'.$info['extension']);
                $attach->alt = $cleanName;
            }

            $newFileName = md5(date('Y-m-d-s').$filename).'.'.$info['extension'];
            $attach->filename = $path.$newFileName;
                Storage::put(
                $path.$newFileName,
                file_get_contents(public_path($filename))
            );
            $attach->save();
            unlink(public_path($filename));
        }

        if (! $this->attaches->contains($attach->id)) {
            $this->attaches()->attach($attach);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function updateOrNewAttach($filename, $title=null, $alt=null, $desc=null)
    {
        if(Storage::exists($filename)){
            $namespace = $this->getEntityClassName();

            $attach = $this
                ->createAttachesModel()
                ->whereNamespace($namespace)
                ->where(function ($query) use ($filename) {
                    $query
                        ->orWhere('filename', $filename)
                    ;
                })
                ->first()
            ;

            if ($attach) {
                $attach->title=$title;
                $attach->alt=$alt;
                $attach->desc=$desc;
                $attach->save();
            }
        }

        else $this->addAttach($filename, $title, $alt, $desc);
    }

    /**
     * {@inheritdoc}
     */
    public function keepOnly($filenames)
    {
        $collection = collect($filenames);
        foreach($this->attaches as $attach)
        {
            if(! $collection->contains($attach->filename))
            {
                if (Storage::exists($attach->filename)) Storage::delete($attach->filename);
                $this->removeAttach($attach->filename);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeAttach($name)
    {
        $namespace = $this->getEntityClassName();

        $attach = $this
            ->createAttachesModel()
            ->whereNamespace($namespace)
            ->where(function ($query) use ($name) {
                $query
                    ->orWhere('title', $name)
                    ->orWhere('filename', $name)
                ;
            })
            ->first()
        ;
        if ($attach) {
            $this->attaches()->detach($attach);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function prepareAttaches($attaches)
    {
        if (is_null($attaches)) {
            return [];
        }

        if (is_string($attaches)) {
            $delimiter = preg_quote($this->getAttachesDelimiter(), '#');

            $attaches = array_map('trim',
                preg_split("#[{$delimiter}]#", $attaches, null, PREG_SPLIT_NO_EMPTY)
            );
        }

        return array_unique(array_filter($attaches));
    }

    /**
     * {@inheritdoc}
     */
    public static function createAttachesModel()
    {
        return new static::$attachesModel;
    }

    /**
     * Generate the attach slug using the given name.
     *
     * @param  string  $name
     * @return string
     */
    protected function generateAttachSlug($name)
    {
        return call_user_func(static::$slugGenerator, $name);
    }

    /**
     * Returns the entity class name.
     *
     * @return string
     */
    protected function getEntityClassName()
    {
        if (isset(static::$entityNamespace)) {
            return static::$entityNamespace;
        }

        return $this->attaches()->getMorphClass();
    }
}


<?php

namespace Flowcode\DashboardBundle\Form\Type;

use Flowcode\DashboardBundle\Entity\Setting;
use Flowcode\DashboardBundle\Service\SettingService;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class SettingType extends AbstractType
{

    /**
     * @var SettingService
     */
    protected $settingService;

    /**
     * SettingType constructor.
     * @param SettingService $settingService
     */
    public function __construct(SettingService $settingService)
    {
        $this->settingService = $settingService;
    }

    private function getChoices()
    {
        $choices = [];
        $settingOptions = $this->settingService->getAll();
        foreach ($settingOptions as $settingOption) {
            $choices[$settingOption['key']] = $settingOption['label'];
        }
        return $choices;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', ChoiceType::class, array(
                'choices' => $this->getChoices(),
            ))
            ->add('value');
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Flowcode\DashboardBundle\Entity\Setting',
            'translation_domain' => 'Setting',
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'setting';
    }
}


<?php

namespace Colorium\Http;

class Uri
{

    /** @var string */
    public $scheme;

    /** @var string */
    public $user;

    /** @var string */
    public $password;

    /** @var string */
    public $host;

    /** @var int */
    public $port;

    /** @var string */
    public $base;

    /** @var string */
    public $path = '/';

    /** @var array */
    public $params = [];

    /** @var string */
    public $fragment;

    /** @var string */
    public $full;

    /**
     * Parse and init
     *
     * @param string $uri
     * @param string $base
     */
    public function __construct($uri = '/', $base = null)
    {
        if(!is_array($uri)) {
            $uri = parse_url($uri);
        }

        $parsed = $uri + [
            'scheme' => null,
            'user' => null,
            'pass' => null,
            'host' => null,
            'port' => null,
            'base' => $base,
            'path' => '/',
            'query' => null,
            'fragment' => null,
        ];

        $this->scheme = strtolower($parsed['scheme']);
        $this->user = $parsed['user'];
        $this->password = $parsed['pass'];
        $this->host = strtolower($parsed['host']);
        $this->port = (int)$parsed['port'];
        $this->base = $parsed['base'];
        $this->path = '/' . trim($parsed['path'], '/');
        $this->query = $parsed['query'];
        $this->fragment = $parsed['fragment'];

        if($this->base) {
            $this->path = substr($this->path, strlen($this->base)) ?: '/';
        }

        parse_str($parsed['query'], $this->params);

        $full = '/';
        if($this->host) {
            $authority = $this->host;
            if($this->port) {
                $authority .= ':' . $this->port;
            }
            if($this->user) {
                $userInfo = $this->user;
                if($this->password) {
                    $userInfo .= ':' . $this->password;
                }
                $authority = $userInfo . '@' . $authority;
            }
            $full = '//' . $authority . $full;
            if($this->scheme) {
                $full = $this->scheme . ':' . $full;
            }
        }
        if($this->base) {
            $full .= trim($this->base, '/') . '/';
        }
        if($this->path) {
            $full .= trim($this->path, '/');
        }
        if($this->query) {
            $full .= '?' . $this->query;
        }
        if($this->fragment) {
            $full .= '#' . $this->fragment;
        }
        $this->full = $full;
    }

    /**
     * Get uri param
     *
     * @param string $key
     * @return string
     */
    public function param($key)
    {
        return isset($this->params[$key])
            ? $this->params[$key]
            : null;
    }

    /**
     * Change base uri
     *
     * @param string $base
     * @return Uri
     */
    public function rebase($base)
    {
        return new static([
            'scheme' => $this->scheme,
            'user' => $this->user,
            'pass' => $this->password,
            'host' => $this->host,
            'port' => $this->port,
            'base' => $base,
            'path' => $this->path,
            'query' => $this->query,
            'fragment' => $this->fragment,
        ]);
    }

    /**
     * Make uri
     *
     * @param string $path
     * @param array $params
     * @return Uri
     */
    public function make($path, array $params = [])
    {
        return new static([
            'scheme' => $this->scheme,
            'user' => $this->user,
            'pass' => $this->password,
            'host' => $this->host,
            'port' => $this->port,
            'base' => $this->base,
            'path' => $this->base . $path,
            'query' => http_build_query($params),
            'fragment' => $this->fragment,
        ]);
    }

    /**
     * Compare query
     *
     * @param string $query
     *
     * @return bool
     */
    public function is($query)
    {
        return fnmatch($query, $this->path);
    }

    /**
     * Return full uri
     *
     * @return string
     */
    public function __toString()
    {
        return $this->full;
    }

    /**
     * Generate uri from $_SERVER
     *
     * @param string $base
     * @return static
     */
    public static function current($base = null)
    {
        static $current;
        if(!$current) {

            // parse server header
            $scheme = isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : null;
            $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
            $path = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null;
            $query = parse_url($path, PHP_URL_QUERY);
            $path = parse_url($path, PHP_URL_PATH);

            // auto-resolve base path
            if(!$base) {
                if(!empty($_SERVER['HTTP_BASE_URI'])) {
                    $base = $_SERVER['HTTP_BASE_URI'];
                }
                elseif(isset($_SERVER['SCRIPT_NAME']) and $scriptname = dirname($_SERVER['SCRIPT_NAME'])) {
                    $scriptname = trim($scriptname, '.');
                    while($scriptname and $scriptname != '/') {
                        if(strncmp($path, $scriptname, strlen($scriptname)) === 0) {
                            $base = $scriptname;
                            break;
                        }
                        $scriptname = dirname($scriptname);
                    }
                }
            }

            $current = new static([
                'scheme' => $scheme,
                'user' => null,
                'pass' => null,
                'host' => $host,
                'port' => null,
                'base' => $base,
                'path' => $path,
                'query' => $query,
                'fragment' => null,
            ]);
        }

        return $current;
    }

    /**
     * Sanitize string for uri usage
     *
     * @param $string
     * @return string
     */
    public static function sanitize($string)
    {
        $string = strtolower($string);
        $string = str_replace('é', 'e', $string);
        $string = str_replace('è', 'e', $string);
        $string = str_replace('ë', 'e', $string);
        $string = str_replace('ê', 'e', $string);
        $string = str_replace('à', 'a', $string);
        $string = str_replace('ä', 'a', $string);
        $string = str_replace('ö', 'o', $string);
        $string = str_replace('ù', 'u', $string);
        $string = str_replace('ü', 'u', $string);
        $string = str_replace('ç', 'c', $string);
        $string = preg_replace('/[^0-9a-z-]/', '-', $string);
        $string = preg_replace('/-+/', '-', $string);
        $string = trim($string, ' -');

        return $string;
    }

}


<?php

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

namespace Valkyrja\Routing;

/**
 * Class RouteCollection.
 *
 * @author Melech Mizrachi
 */
class RouteCollection
{
    /**
     * The routes.
     *
     * @var \Valkyrja\Routing\Route[]
     */
    protected $routes = [];

    /**
     * The static routes.
     *
     * @var string[][]
     */
    protected $staticRoutes = [];

    /**
     * The dynamic routes.
     *
     * @var string[][]
     */
    protected $dynamicRoutes = [];

    /**
     * The named routes.
     *
     * @var array[]
     */
    protected $namedRoutes = [];

    /**
     * Add a route.
     *
     * @param Route $route The route
     *
     * @return void
     */
    public function addRoute(Route $route): void
    {
        $key                = md5(\json_encode((array) $route));
        $this->routes[$key] = $route;

        foreach ($route->getRequestMethods() as $requestMethod) {
            // If this is a dynamic route
            if ($route->isDynamic()) {
                // Set the route's regex and path in the dynamic routes list
                $this->dynamicRoutes[$requestMethod][$route->getRegex()] = $key;
            } // Otherwise set it in the static routes array
            else {
                // Set the route's path in the static routes list
                $this->staticRoutes[$requestMethod][$route->getPath()] = $key;
            }
        }

        // If this route has a name set
        if ($route->getName()) {
            // Set the route in the named routes list
            $this->namedRoutes[$route->getName()] = $key;
        }
    }

    /**
     * @return Route[]
     */
    public function getRoutes(): array
    {
        return $this->routes;
    }

    /**
     * Get a static route.
     *
     * @param string $method The request method
     * @param string $path   The path
     *
     * @return null|Route
     *      The route if found or null when no static route is
     *      found for the path and method combination specified
     */
    public function staticRoute(string $method, string $path): ? Route
    {
        return $this->route($this->staticRoutes[$method][$path] ?? $path);
    }

    /**
     * Determine if a static route exists.
     *
     * @param string $method The request method
     * @param string $path   The path
     *
     * @return bool
     */
    public function issetStaticRoute(string $method, string $path): bool
    {
        return isset($this->staticRoutes[$method][$path]);
    }

    /**
     * Get static routes of a certain request method.
     *
     * @param string $method The request method
     *
     * @return \string[]
     */
    public function getStaticRoutes(string $method): array
    {
        return $this->staticRoutes[$method];
    }

    /**
     * Get a dynamic route.
     *
     * @param string $method The request method
     * @param string $regex  The regex
     *
     * @return null|Route
     *      The route if found or null when no static route is
     *      found for the path and method combination specified
     */
    public function dynamicRoute(string $method, string $regex): ? Route
    {
        return $this->route($this->dynamicRoutes[$method][$regex] ?? $regex);
    }

    /**
     * Determine if a dynamic route exists.
     *
     * @param string $method The request method
     * @param string $regex  The regex
     *
     * @return bool
     */
    public function issetDynamicRoute(string $method, string $regex): bool
    {
        return isset($this->dynamicRoutes[$method][$regex]);
    }

    /**
     * Get the dynamic routes in this collection.
     *
     * @param string $method
     *
     * @return string[]
     */
    public function getDynamicRoutes(string $method): array
    {
        return $this->dynamicRoutes[$method] ?? [];
    }

    /**
     * Get a named route.
     *
     * @param string $name The name
     *
     * @return null|Route
     *      The route if found or null when no static route is
     *      found for the path and method combination specified
     */
    public function namedRoute(string $name): ? Route
    {
        return $this->route($this->namedRoutes[$name] ?? $name);
    }

    /**
     * Determine if a named route exists.
     *
     * @param string $name The name
     *
     * @return bool
     */
    public function issetNamedRoute(string $name): bool
    {
        return isset($this->namedRoutes[$name]);
    }

    /**
     * Get the named routes in this collection.
     *
     * @return string[]
     */
    public function getNamedRoutes(): array
    {
        return $this->namedRoutes;
    }

    /**
     * Get a route.
     *
     * @param string $path The path
     *
     * @return null|Route
     *      The route if found or null when no static route is
     *      found for the path and method combination specified
     */
    protected function route(string $path): ? Route
    {
        return $this->routes[$path] ?? null;
    }

    /**
     * Determine if a route exists.
     *
     * @param string $path The path
     *
     * @return bool
     */
    protected function issetRoute(string $path): bool
    {
        return isset($this->routes[$path]);
    }
}


<?php

namespace Ekyna\Bundle\CoreBundle\Redirection;

/**
 * Class ProviderRegistry
 * @package Ekyna\Bundle\CoreBundle\Redirection
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class ProviderRegistry implements ProviderRegistryInterface
{
    /**
     * @var array|ProviderInterface[]
     */
    private $providers;

    /**
     * @var bool
     */
    private $initialized = false;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->providers = [];
    }

    /**
     * {@inheritdoc}
     */
    public function addProvider(ProviderInterface $provider)
    {
        if ($this->initialized) {
            throw new \RuntimeException('Redirection registry as been initialized and can\'t register more providers.');
        }
        if (array_key_exists($provider->getName(), $this->providers)) {
            throw new \InvalidArgumentException(sprintf('Provider "%s" is already registered.', $provider->getName()));
        }
        $this->providers[$provider->getName()] = $provider;
    }

    /**
     * {@inheritdoc}
     */
    public function getProviders()
    {
        if (!$this->initialized) {
            usort($this->providers, function (ProviderInterface $a, ProviderInterface $b) {
                if ($a->getPriority() == $b->getPriority()) {
                    return 0;
                }
                return $a->getPriority() > $b->getPriority() ? 1 : -1;
            });
            $this->initialized = true;
        }
        return $this->providers;
    }
}


<?php

namespace Rhubarb\Leaf\Crud\Leaves;

use Rhubarb\Crown\String\StringTools;
use Rhubarb\Leaf\Controls\Common\Buttons\Button;
use Rhubarb\Leaf\Views\View;
use Rhubarb\Stem\Schema\SolutionSchema;

class CrudView extends View
{
    /**
     * @var CrudModel
     */
    protected $model;

    /**
     * The place where extending classes should create and register new Views
     */
    protected function createSubLeaves()
    {
        parent::createSubLeaves();

        $this->registerSubLeaf(new Button("Save", "Save", function(){
            $this->model->savePressedEvent->raise();
        }));

        $this->registerSubLeaf(new Button("Delete", "Delete", function(){
            $this->model->deletePressedEvent->raise();
        }));

        $this->registerSubLeaf(new Button("Cancel", "Cancel", function(){
            $this->model->cancelPressedEvent->raise();
        }));
    }

    protected function getTitle()
    {
        if ($this->model->restModel !== null) {
            if ($this->model->restModel->isNewRecord()) {
                return "Adding a new " . strtolower(
                    StringTools::wordifyStringByUpperCase(
                        SolutionSchema::getModelNameFromClass(get_class($this->model->restModel))
                    )
                ) . " entry";
            } else {
                return ucfirst(
                    strtolower(
                        StringTools::wordifyStringByUpperCase(
                            SolutionSchema::getModelNameFromClass(get_class($this->model->restModel))
                        )
                    ) . " '" . $this->model->restModel->getLabel() . "'"
                );
            }
        } else {
            if ($this->model->restCollection !== null) {
                return StringTools::wordifyStringByUpperCase(
                    StringTools::makePlural(
                        SolutionSchema::getModelNameFromClass($this->model->restCollection->getModelClassName())
                    )
                );
            } else {
                return "Untitled";
            }
        }
    }
}


<?php

namespace tourze\Http\Request\Client;

use Exception;
use Requests;
use tourze\Base\Base;
use tourze\Http\Response;
use tourze\Http\Request;
use tourze\Http\Request\Exception\RequestException;
use tourze\Http\Request\RequestClient;

/**
 * 获取指定地址的外部请求
 *
 * @package tourze\Http\Request\Client
 */
class ExternalClient extends RequestClient
{

    /**
     * 执行外部请求，并返回接口
     *
     *     $request->execute();
     *
     * @param  Request  $request
     * @param  Response $response
     * @return Response
     * @throws Exception
     */
    public function executeRequest(Request $request, Response $response)
    {
        $previous = Request::$current;
        Request::$current = $request;

        // 如果post数据了
        if ($post = $request->post())
        {
            $request->body = http_build_query($post, null, '&');
            $request->headers('content-type', 'application/x-www-form-urlencoded; charset=' . $request->charset);
        }

        // 如果需要暴露框架信息
        if (Base::$expose)
        {
            $request->headers('user-agent', Base::version());
        }

        try
        {
            // 处理header
            $sendHeaders = [];
            if ($headers = $request->headers())
            {
                foreach ($headers as $key => $value)
                {
                    if (is_array($value))
                    {
                        $value = implode(', ', $value);
                    }
                    $sendHeaders[$key] = $value;
                }
            }

            // 处理cookie
            if ($cookies = $request->cookie())
            {
                $sendHeaders['Cookie'] = http_build_query($cookies, null, '; ');
            }

            $url = $request->uri;
            if ($query = $request->query())
            {
                $url .= '?' . http_build_query($query, null, '&');
            }

            // 执行请求
            $result = Requests::request($url, $sendHeaders, $request->body, $request->method, $this->options);
            if ( ! $result->success)
            {
                throw new RequestException('Error fetching remote :url [ status :code ]', [
                    ':url'   => $url,
                    ':code'  => $result->status_code,
                ]);
            }

            foreach ($result->headers as $k => $v)
            {
                $response->headers($k, $v);
            }
            $response->status = $result->status_code;
            $response->body = $result->body;
        }
        catch (Exception $e)
        {
            Request::$current = $previous;
            throw $e;
        }

        Request::$current = $previous;
        return $response;
    }
}