<?php

namespace Sasedev\Commons\SharedBundle\Controller;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bridge\Monolog\Logger;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Validator;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\Meta;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\Link;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\Script;
use Sasedev\Commons\SharedBundle\HtmlModel\Tags\Style;

/**
 * The Default BaseController
 *
 * @author sasedev <seif.salah@gmail.com>
 */
class BaseController extends Controller
{

	/**
	 *
	 * @var array $twig_vars
	 */
	private $twig_vars = array();

	/**
	 *
	 * @var array
	 */
	private $head_metas = array();

	/**
	 *
	 * @var array
	 */
	private $head_links = array();

	/**
	 *
	 * @var array $head_scripts
	 */
	private $head_scripts = array();

	/**
	 *
	 * @var array $head_scripts
	 */
	private $head_styles = array();

	/**
	 *
	 * @var string $browser_page_title
	 */
	private $browser_page_title;

	/**
	 *
	 * @var string $page_title
	 */
	private $page_title;

	/**
	 *
	 * @var array $body_scripts
	 */
	private $body_scripts = array();

	/**
	 * Get Monolog Logger
	 *
	 * @return Logger
	 *
	 * @throws \LogicException If MonologBundle is not available
	 */
	public function getLogger()
	{

		if (!$this->container->has('logger')) {
			throw new \LogicException('The MonologBundle is not registered in your application.');
		}

		return $this->container->get('logger');

	}

	/**
	 * Get Swiftmail Mailer
	 *
	 * @return Swift_Mailer
	 *
	 * @throws \LogicException If SwiftmailerBundle is not available
	 */
	public function getMailer()
	{

		if (!$this->container->has('mailer')) {
			throw new \LogicException('The SwiftmailerBundle is not registered in your application.');
		}

		return $this->container->get('mailer');

	}

	/**
	 * Get symfony router
	 *
	 * @return Router
	 */
	public function getRouter()
	{

		return $this->container->get('router');

	}

	/**
	 * Get Request
	 *
	 * @return Request
	 */
	public function getRequest()
	{

		return $this->container->get('request_stack')->getCurrentRequest();

	}

	/**
	 * Get Session
	 *
	 * @return Session
	 */
	public function getSession()
	{

		return $this->container->get('session');

	}

	/**
	 * Get the translator service
	 *
	 * @return Translator
	 */
	public function getTranslator()
	{

		return $this->container->get('translator');

	}

	/**
	 * Get security context
	 *
	 * @return TokenStorage
	 */
	public function getSecurityTokenStorage()
	{

		return $this->container->get('security.token_storage');

	}

	/**
	 * Get security context
	 *
	 * @return AuthorizationChecker
	 */
	public function getSecurityAuthorizationChecker()
	{

		return $this->container->get('security.authorization_checker');

	}

	/**
	 * Get validator service
	 *
	 * @return RecursiveValidator
	 */
	public function getValidator()
	{

		return $this->container->get('validator');

	}

	/**
	 * Get templating service
	 *
	 * @return DelegatingEngine
	 */
	public function getTemplating()
	{

		return $this->container->get('templating');

	}

	/**
	 * Get referer
	 *
	 * @return string
	 */
	public function getReferer()
	{

		return $this->getRequest()->headers->get('referer');

	}

	/**
	 * Get Doctrine Entity Manager
	 *
	 * @return ObjectManager
	 */
	public function getEntityManager($name = null)
	{

		$entityManager = $this->getDoctrine()->getManager($name);
		if (!$entityManager->isOpen()) {
			$entityManager = $entityManager->create($entityManager->getConnection(), $entityManager->getConfiguration());
		}

		return $entityManager;

	}

	/**
	 * Translates the given message.
	 *
	 * @param string $id
	 * @param array $parameters
	 * @param string $domain
	 * @param string $locale
	 *
	 * @return string
	 */
	public function translate($id, $parameters = array(), $domain = 'messages', $locale = null)
	{

		return $this->getTranslator()->trans($id, $parameters, $domain, $locale);

	}

	/**
	 * Send a message by mail
	 * The return value is the number of recipients who were accepted for
	 * delivery.
	 *
	 * @param Swift_Mime_Message $message
	 *
	 * @return integer
	 */
	public function sendmail($message)
	{

		return $this->getMailer()->send($message);

	}

	/**
	 * Check if a string starts with a prefix
	 *
	 * @param string $string
	 * @param string $prefix
	 *
	 * @return boolean
	 */
	public function startswith($string, $prefix)
	{

		return strpos($string, $prefix) === 0;

	}

	/**
	 * Check if a string ends with a suffix
	 *
	 * @param string $string
	 * @param string $suffix
	 *
	 * @return boolean
	 */
	public function endswith($string, $suffix)
	{

		$strlen = strlen($string);
		$testlen = strlen($suffix);
		if ($testlen > $strlen) {
			return false;
		}

		return substr_compare($string, $suffix, -$testlen) === 0;

	}

	/**
	 * Normalize a string
	 *
	 * @param string $string
	 *
	 * @return string
	 */
	public function normalize($string)
	{

		$table = array(
			'Š' => 'S',
			'š' => 's',
			'Ð' => 'Dj',
			'Ž' => 'Z',
			'ž' => 'z',
			'C' => 'C',
			'c' => 'c',
			'C' => 'C',
			'c' => 'c',
			'À' => 'A',
			'Á' => 'A',
			'Â' => 'A',
			'Ã' => 'A',
			'Ä' => 'A',
			'Å' => 'A',
			'Æ' => 'A',
			'Ç' => 'C',
			'È' => 'E',
			'É' => 'E',
			'Ê' => 'E',
			'Ë' => 'E',
			'Ì' => 'I',
			'Í' => 'I',
			'Î' => 'I',
			'Ï' => 'I',
			'Ñ' => 'N',
			'Ò' => 'O',
			'Ó' => 'O',
			'Ô' => 'O',
			'Õ' => 'O',
			'Ö' => 'O',
			'Ø' => 'O',
			'Ù' => 'U',
			'Ú' => 'U',
			'Û' => 'U',
			'Ü' => 'U',
			'Ý' => 'Y',
			'Þ' => 'B',
			'ß' => 'Ss',
			'à' => 'a',
			'á' => 'a',
			'â' => 'a',
			'ã' => 'a',
			'ä' => 'a',
			'å' => 'a',
			'æ' => 'a',
			'ç' => 'c',
			'è' => 'e',
			'é' => 'e',
			'ê' => 'e',
			'ë' => 'e',
			'ì' => 'i',
			'í' => 'i',
			'î' => 'i',
			'ï' => 'i',
			'ð' => 'o',
			'ñ' => 'n',
			'ò' => 'o',
			'ó' => 'o',
			'ô' => 'o',
			'õ' => 'o',
			'ö' => 'o',
			'ø' => 'o',
			'ù' => 'u',
			'ú' => 'u',
			'û' => 'u',
			'ý' => 'y',
			'ý' => 'y',
			'þ' => 'b',
			'ÿ' => 'y',
			'R' => 'R',
			'r' => 'r'
		);

		return strtr($string, $table);

	}

	/**
	 * Get $twig_vars
	 *
	 * @return array
	 */
	public function getTwigVars()
	{

		return $this->twig_vars;

	}

	/**
	 * Set $twig_vars;
	 *
	 * @param array $twig_vars
	 *
	 * @return BaseController $this
	 */
	public function setTwigVars($twig_vars)
	{

		$this->twig_vars = $twig_vars;

		return $this;

	}

	/**
	 * Add $twig_var;
	 *
	 * @param string $name
	 *
	 * @param mixed $value
	 *
	 * @return BaseController $this
	 */
	public function addTwigVar($name, $value = null)
	{

		$this->twig_vars[$name] = $value;

		return $this;

	}

	/**
	 * Get $head_metas
	 *
	 * @return array
	 */
	public function getHeadMetas()
	{

		return $this->head_metas;

	}

	/**
	 * Set $head_metas
	 *
	 * @param array $head_metas
	 *
	 * @return BaseController $this
	 */
	public function setHeadMetas($head_metas)
	{

		$this->head_metas = $head_metas;

		$this->twig_vars['head_metas'] = $this->head_metas;

		return $this;

	}

	/**
	 * Add $head_meta;
	 *
	 * @param Meta $head_meta
	 *
	 * @return BaseController $this
	 */
	public function addHeadMeta(Meta $head_meta)
	{

		$this->head_metas[] = $head_meta;

		$this->twig_vars['head_metas'] = $this->head_metas;

		return $this;

	}

	/**
	 * Get $head_links
	 *
	 * @return array
	 */
	public function getHeadLinks()
	{

		return $this->head_links;

	}

	/**
	 * Set $head_links
	 *
	 * @param array $head_links
	 *
	 * @return BaseController $this
	 */
	public function setHeadLinks($head_links)
	{

		$this->head_links = $head_links;

		$this->twig_vars['head_links'] = $this->head_links;

		return $this;

	}

	/**
	 * Add $head_link;
	 *
	 * @param Link $head_link
	 *
	 * @return BaseController $this
	 */
	public function addHeadLink(Link $head_link)
	{

		$this->head_links[] = $head_link;

		$this->twig_vars['head_links'] = $this->head_links;

		return $this;

	}

	/**
	 * Get $head_scripts
	 *
	 * @return array
	 */
	public function getHeadScripts()
	{

		return $this->head_scripts;

	}

	/**
	 * Set $head_scripts
	 *
	 * @param array $head_scripts
	 *
	 * @return BaseController $this
	 */
	public function setHeadScripts($head_scripts)
	{

		$this->head_scripts = $head_scripts;

		$this->twig_vars['head_scripts'] = $this->head_scripts;

		return $this;

	}

	/**
	 * Add $head_script;
	 *
	 * @param Script $head_script
	 *
	 * @return BaseController $this
	 */
	public function addHeadScript(Script $head_script)
	{

		$this->head_scripts[] = $head_script;

		$this->twig_vars['head_scripts'] = $this->head_scripts;

		return $this;

	}

	/**
	 * Get $head_styles
	 *
	 * @return array
	 */
	public function getHeadStyles()
	{

		return $this->head_styles;

	}

	/**
	 * Set $head_styles
	 *
	 * @param array $head_styles
	 *
	 * @return BaseController $this
	 */
	public function setHeadStyles($head_styles)
	{

		$this->head_styles = $head_styles;

		$this->twig_vars['head_styles'] = $this->head_styles;

		return $this;

	}

	/**
	 * Add $head_style;
	 *
	 * @param Style $head_style
	 *
	 * @return BaseController $this
	 */
	public function addHeadStyle(Style $head_style)
	{

		$this->head_styles[] = $head_style;

		$this->twig_vars['head_styles'] = $this->head_styles;

		return $this;

	}

	/**
	 *
	 * @return string
	 */
	public function getBrowserPageTitle()
	{

		return $this->browser_page_title;

	}

	/**
	 *
	 * @param string $page_title
	 */
	public function setBrowserPageTitle($title)
	{

		$this->browser_page_title = $title;

		$this->twig_vars['browser_page_title'] = $this->browser_page_title;

		return $this;

	}

	/**
	 *
	 * @return string
	 */
	public function getPageTitle()
	{

		return $this->page_title;

	}

	/**
	 *
	 * @param string $page_title
	 */
	public function setPageTitle($title)
	{

		$this->page_title = $title;

		$this->twig_vars['page_title'] = $this->page_title;

		return $this;

	}

	/**
	 * Get $body_scripts
	 *
	 * @return array
	 */
	public function getBodyScripts()
	{

		return $this->body_scripts;

	}

	/**
	 * Set $body_scripts
	 *
	 * @param array $body_scripts
	 *
	 * @return BaseController $this
	 */
	public function setBodyScripts($body_scripts)
	{

		$this->body_scripts = $body_scripts;

		$this->twig_vars['body_scripts'] = $this->body_scripts;

		return $this;

	}

	/**
	 * Add $body_script;
	 *
	 * @param Script $body_script
	 *
	 * @return BaseController $this
	 */
	public function addBodyScript(Script $body_script)
	{

		$this->body_scripts[] = $body_script;

		$this->twig_vars['body_scripts'] = $this->body_scripts;

		return $this;

	}

}


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

/**
 * This class integrates FirePHP debugging into the EzSQL MySQL (not MySQLi) abstraction layer.
 */
class OwpEzSqlMysql extends OwpDBMySQLi
{

    /**
     * @var object $ezSqlDB ezSQL Database Object
     */
    static private $ezSqlDB;

    /**
     * debugPhpConsole
     *
     * @method void debugPhpConsole()
     * @access public
     * @param  string $title Debug Title
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function debugPhpConsole($title = "OwpEzSqlMysql.ezSQL_mysql.debugPhpConsole")
    {
        $debug = array();

        if ($this->last_error ) {
            $debug["last_error"] = $this->last_error;
        }

        if ($this->last_query ) {
            $debug["last_query"] = $this->last_query;
        }

        if($this->captured_errors) {
            $debug["captured_errors"] = $this->captured_errors;
        }

        if(!empty($this->last_result)) {
            $debug["last_result"] = $this->get_results(null, ARRAY_N);
        }

        PC::debug($debug, $title);
    }//end debugPhpConsole()

    /**
     * Debug
     *
     * @method void __debugInfo()
     * @access public
     * @uses   $this->userData()
     * @uses   $this->userData()
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function __debugInfo()
    {
        return [
                "Last Error"    => $this->last_error,
                "Last Query"    => $this->last_query,
                "Last Result"   => (!empty($this->last_result) ? $this->get_results(null, ARRAY_A) : "No Results"),
               ];

    }//end __debugInfo()

    /**
     * MySQLFirephp()
     *
     * @method mixed MySQLFirephp($title) Integrate FirePHP debugging into the EzSQL MySQLi obstraction layer.
     * @access public
     *
     * @param string $title Optional title.
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function MySQLFirephp($title = "ezSql Debug")
    {

        $table   = array();
        $table[] = array(
                    'Item',
                    'Detail',
                   );

        if ($this->last_error) {
            $table[] = array(
                        'Last Error',
                        $this->last_error,
                       );
        }

        $table[] = array(
                    'Query',
                    $this->last_query,
                   );
        if ($this->col_info) {
            $table[] = array(
                        'Col Info',
                        $this->col_info,
                       );
        }

        $table[] = array(
                    'Last Result',
                    (!empty($this->last_result) ? $this->get_results(null, ARRAY_A) : "No Results"),
                   );

        PC::debug($table, $title);

    }//end MySQLFirephp()

    /**
     * MySQLFirephpGetLastMysqlError()
     *
     * @method mixed MySQLFirephpGetLastMysqlError() Integrate FirePHP debugging into the EzSQL MySQLi obstraction layer.
     * @access public
     *
     * @return mixed Last recorded MySQL Error
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    public function MySQLFirephpGetLastMysqlError()
    {
        if (!empty($this->last_error)) {
            return $this->last_error;
        } else {
            return null;
        }

    }//end MySQLFirephpGetLastMysqlError()

    /**
     * executeSqlFile
     *
     * @method void executeSqlFile($filename) Execute SQL text file
     * @param $filename
     * @return mixed
     * @throws Exception
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function executeSqlFile($filename)
    {
        self::initDb();
        $query_sql = self::$ezSqlDB->escape(file_get_contents($filename));
        return self::$ezSqlDB->query($query_sql);
    }//end executeSqlFile()

    /**
     * initDb
     *
     * @method initDb()
     * @access public
     *
     * @return object|OwpEzSqlMysql
     * @throws Exception
     *
     * @author  Brian Tafoya <btafoya@briantafoya.com>
     * @version 1.0
     */
    static public function initDb()
    {
        if(!self::$ezSqlDB) {
            self::$ezSqlDB = new OwpEzSqlMysql($_ENV["DB_USER"], $_ENV["DB_PASS"], $_ENV["DB_NAME"], $_ENV["DB_HOST"]);
            self::$ezSqlDB->use_disk_cache = false;
            self::$ezSqlDB->cache_queries  = false;
            self::$ezSqlDB->hide_errors();
        }

        return self::$ezSqlDB;

    }//end initDb()

}//end class


<?php
namespace hathoora\grid;

class pagination
{
    /**
     * Simle pagination @ http://harishankar.org/blog/entry.php/function-to-generate-a-pagination-link-list-in-php
     */
    public static function simple($arrParams = array())
    {
        $total_pages =  !empty($arrParams['totalPages']) ? $arrParams['totalPages'] : null;
        $current_page =  !empty($arrParams['currentPage']) ? $arrParams['currentPage'] : null;
        $base_url =  !empty($arrParams['baseURL']) ? $arrParams['baseURL'] : null;
        $query_str =  !empty($arrParams['queryString']) ? $arrParams['queryString'] : 'page';

        $paginate_limit = 10;
        $query_sep = '?';

        if (strpos($base_url, '?')) {
            $query_sep = '&';
        }

        // Array to store page link list
        $page_array = array ();

        // Show dots flag - where to show dots?
        $dotshow = true;

        // walk through the list of pages
        for ( $i = 1; $i <= $total_pages; $i ++ )
        {
           // If first or last page or the page number falls within the pagination limit
           // generate the links for these pages
           if ($i == 1 || $i == $total_pages || ($i >= $current_page - $paginate_limit && $i <= $current_page + $paginate_limit))
           {
              // reset the show dots flag
              $dotshow = true;

              // If it's the current page, leave out the link
              // otherwise set a URL field also
              if ($i != $current_page)
                  $page_array[$i]['url'] = $base_url . $query_sep . $query_str . "=" . $i;

              $page_array[$i]['text'] = strval ($i);
           }

           // If ellipses dots are to be displayed (page navigation skipped)
           else if ($dotshow == true)
           {
               // set it to false, so that more than one
               // set of ellipses is not displayed
               $dotshow = false;
               $page_array[$i]['text'] = "...";
           }
        }

        // return the navigation array
        return $page_array;
    }
}


<?php

/**
 * Jin Framework
 * Diatem
 */

namespace Jin2\Form\Validators;

use Jin2\Language\Translation;
use \Securimage;

/**
 * Validateur : teste si une valeur issue d'un composant SimpleCaptcha est valide
 */
class SimpleCaptchaValidator extends AbstractValidator
{

  /**
   * Implémente la fonction AbstractValidator::getType()
   *
   * @return string
   */
  public static function getType()
  {
    return 'simplecaptcha';
  }

  /**
   * Teste la validité
   *
   * @param  mixed $value Valeur à tester
   * @return boolean
   */
  public function isValid($value)
  {
    $securimage = new \Securimage(array('session_name' => null));

    if (empty($value)) {
      parent::addError(Translation::get('validatorerror_simplecaptcha_required'));
      return false;
    }

    if ($securimage->check($value) == false) {
      parent::addError(Translation::get('validatorerror_simplecaptcha_check'));
      return false;
    }

    return true;
  }

  /**
   * Vérifie si le validateur est prioritaire
   *
   * @return boolean
   */
  public function isPrior()
  {
    return true;
  }

}


<?php

namespace Oxygen\Data\Validation\Laravel;

use Illuminate\Contracts\Hashing\Hasher;
use Seld\JsonLint\JsonParser;
use Seld\JsonLint\ParsingException;

use Illuminate\Validation\Validator as BaseValidator;
use Illuminate\View\Factory;
use Illuminate\Routing\Router;
use Symfony\Component\Translation\TranslatorInterface;

class Validator extends BaseValidator {

    /**
     * The Hasher implementation.
     *
     * @var \Illuminate\Contracts\Hashing\Hasher
     */

    protected $hasher;

    /**
     * The View factory.
     *
     * @var \Illuminate\View\Factory
     */

    protected $view;

    /**
     * The Router instance.
     *
     * @var \Illuminate\Routing\Router
     */

    protected $router;

    /**
     * Create a new Validator instance.
     *
     * @param \Symfony\Component\Translation\TranslatorInterface  $translator
     * @param \Illuminate\Contracts\Hashing\Hasher                $hasher
     * @param  Factory                                            $view
     * @param \Illuminate\Routing\Router                          $router
     * @param  array                                              $data
     * @param  array                                              $rules
     * @param  array                                              $messages
     * @param  array                                              $customAttributes
     */
    public function __construct(TranslatorInterface $translator, Hasher $hasher, Factory $view, Router $router, array $data, array $rules, array $messages = [], array $customAttributes = []) {
        parent::__construct($translator, $data, $rules, $messages, $customAttributes);
        $this->hasher = $hasher;
        $this->view = $view;
        $this->router = $router;
    }

    /**
     * Check the value is a URL slug.
     *
     * foo-for-the-win/i-am-a-horse-123
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateSlug($attribute, $value, $parameters) {
        return preg_match('#^[a-z0-9/\-]+$#', $value);
    }

    /**
     * Check the value is a URL slug.
     *
     * foo-for-the-win/i-am-a-horse-123.jpg
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateSlugExtended($attribute, $value, $parameters) {
        return preg_match('#^[a-z0-9/\-.]+$#', $value);
    }

    /**
     * Check the value is a URL slug without any '/'
     *
     * i-am-a-horse-123.jpg
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateSlugExtendedNoDir($attribute, $value, $parameters) {
        return preg_match('#^[a-z0-9\-.]+$#', $value);
    }

    /**
     * Check the value consists of just alphanumeric characters and dots.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateAlphaDot($attribue, $value, $parameters) {
        return preg_match('/^[\pL\pM\pN\.]+$/u', $value);
    }

    /**
     * Check the value is a name.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateName($attribue, $value, $parameters) {
        return preg_match('/^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð& ,.\'-]+$/u', $value);
    }

    /**
     * Check the field is the given value.
     *
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateHashesTo($attribute, $value, $parameters) {
        $this->requireParameterCount(1, $parameters, 'hashes_to');

        return $this->hasher->check($value, $parameters[0]);
    }

    /**
     * Determines if the given view exists.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateViewExists($attribute, $value, $parameters) {
        return $this->view->exists($value);
    }

    /**
     * Replace all place-holders for the in rule.
     *
     * @param  string  $message
     * @param  string  $attribute
     * @param  string  $rule
     * @param  array   $parameters
     * @return string
     */
    public function replaceViewExists($message, $attribute, $rule, $parameters) {
        return str_replace(':view', $this->getValue($attribute), $message);
    }

    /**
     * Determines if the given route exists.
     * If a parameter is provided it will determine whether the routes are fetched by name or action.
     *
     * @param  string  $attribute
     * @param  mixed   $value
     * @param  array   $parameters
     * @return bool
     */
    public function validateRouteExists($attribute, $value, $parameters) {
        $method = 'getBy' . studly_case(isset($parameters[0]) ? $parameters[0] : 'name');
        $routes = $this->router->getRoutes();
        return $routes->$method($value) !== null;
    }

    /**
     * Replace all place-holders for the in rule.
     *
     * @param  string  $message
     * @param  string  $attribute
     * @param  string  $rule
     * @param  array   $parameters
     * @return string
     */
    public function replaceRouteExists($message, $attribute, $rule, $parameters) {
        return str_replace(':route', $this->getValue($attribute), $message);
    }

    /**
     * Get the extra conditions for a unique / exists rule.
     *
     * @param  array  $segments
     * @return array
     */

    protected function getExtraConditions(array $segments) {
        $extra = [];

        $count = count($segments);

        $operators = [
            '=', '<', '>', '<=', '>=', '<>', '!='
        ];

        // if any of the operators are in the segments
        if(!!array_intersect($operators, $segments)) {
            for ($i = 0; $i < $count; $i = $i + 3) {
                $extra[$segments[$i]] = [$segments[$i + 1], $segments[$i + 2]];
            }
        } else {
            for ($i = 0; $i < $count; $i = $i + 2) {
                $extra[$segments[$i]] = $segments[$i + 1];
            }
        }

        return $extra;
    }

}


<?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\Utilities;

use Interop\Container\ServiceProviderInterface;

class ParametersServiceProvider implements ServiceProviderInterface
{
    /**
     * @var array
     */
    protected $values = [];

    /**
     * @param array $values
     */
    public function __construct(array $values)
    {
        $this->values = $values;
    }

    /**
     * {@inheritdoc}
     */
    public function getServices()
    {
        $services = [];
        foreach ($this->values as $key => $value) {
            $services[$key] = new Parameter($value);
        }

        return $services;
    }
}


<?php

namespace Reaction\Widgets\Bootstrap;

use Reaction\Helpers\Html;

/**
 * Button renders a bootstrap button.
 *
 * For example,
 *
 * ```php
 * echo Button::widget([
 *     'label' => 'Action',
 *     'options' => ['class' => 'btn-lg'],
 * ]);
 * ```
 */
class Button extends Widget
{
    /**
     * @var string the tag to use to render the button
     */
    public $tagName = 'button';
    /**
     * @var string the button label
     */
    public $label = 'Button';
    /**
     * @var boolean whether the label should be HTML-encoded.
     */
    public $encodeLabel = true;

    /**
     * Initializes the widget.
     * If you override this method, make sure you call the parent implementation first.
     */
    public function init()
    {
        parent::init();
        $this->clientOptions = false;
        $this->htmlHlp->addCssClass($this->options, ['widget' => 'btn']);
    }

    /**
     * Renders the widget.
     */
    public function run()
    {
        $this->registerPlugin('button');
        return $this->htmlHlp->tag($this->tagName, $this->encodeLabel ? Html::encode($this->label) : $this->label, $this->options);
    }
}


<?php

namespace KsUtils;

/**
 * Date and time utils
 */
class Dt
{
    /**
     * Converts date string from one format to another, f.e.
     * 31.12.2013 <-> 2013-12-31
     * @param  sting       $str       Input date string
     * @param  string      $formatIn  Format of input date string
     * @param  string      $formatOut Format of output date string
     * @return string|null Output date string or null if error
     */
    public static function convert($str, $formatIn, $formatOut)
    {
        if (!$str) {
            return null;
        }

        $date = \DateTime::createFromFormat($formatIn, $str);

        if (!$date) {
            return null;
        }

        return $date->format($formatOut);
    }

    /**
     * Converts date string from format 31.12.2013 to format 2013-12-31.
     * Shortcat for convert(...) method.
     * @param  sting       $str       Input date string
     * @param  string      $formatIn  Format of input date string
     * @param  string      $formatOut Format of output date string
     * @return string|null Output date string or null if error
     */
    public static function rus2int($str, $formatIn = "d.m.Y", $formatOut = "Y-m-d")
    {
        return self::convert($str, $formatIn, $formatOut);
    }

    /**
     * Converts date string from format 2013-12-31 to format 31.12.2013.
     * Shortcat for convert(...) method.
     * @param  sting       $dtStr     Input date string
     * @param  string      $formatIn  Format of input date string
     * @param  string      $formatOut Format of output date string
     * @return string|null Output date string or null if error
     */
    public static function int2rus($dtStr, $formatIn = "Y-m-d", $formatOut = "d.m.Y")
    {
        return self::convert($dtStr, $formatIn, $formatOut);
    }

    /**
     * Returns next date of given date in given format
     * @param  string $dt     Source date
     * @param  string $format Source date format
     * @return string Destination date or empty string if source date can't be parsed
     */
    public static function getNextDay($dt, $format = "Y-m-d")
    {
        $dtObj = \DateTime::createFromFormat($format, $dt);

        if (!$dtObj) {
            return "";
        }

        return $dtObj->add(date_interval_create_from_date_string('1 days'))->format($format);
    }

    /**
     * Returns previous date of given date in given format
     * @param  string $dt     Source date
     * @param  string $format Source date format
     * @return string Destination date or empty string if source date can't be parsed
     */
    public static function getPrevDay($dt, $format = "Y-m-d")
    {
        $dtObj = \DateTime::createFromFormat($format, $dt);

        if (!$dtObj) {
            return "";
        }

        return $dtObj->sub(date_interval_create_from_date_string('1 days'))->format($format);
    }

    /**
     * Creates an array of consecutive dates
     * @param string $from Starting date
     * @param integer $amount Range's length
     * @param string $dtFormat Format of starting and resulting dates, default: Y-m-d
     * @return array List of dates
     */
    public static function createDateRande($from, $amount, $dtFormat='Y-m-d')
    {
        $range = [ $from ];
        $curDt = $from;

        for($i=1; $i<$amount; $i++) {
            $curDt = \KsUtils\Dt::getNextDay($curDt, $dtFormat);
            $range[] = $curDt;
        }

        return $range;
    }
}


<?php

namespace Reaction\Helpers;

use React\EventLoop\Timer\TimerInterface;
use React\Filesystem\FilesystemInterface;
use React\Filesystem\Node\Directory;
use React\Filesystem\Node\DirectoryInterface;
use React\Filesystem\Node\File;
use React\Filesystem\Node\FileInterface;
use React\Filesystem\Node\GenericOperationInterface;
use React\Stream\WritableStreamInterface;
use Reaction\Promise\Deferred;
use Reaction\Promise\ExtendedPromiseInterface;
use Reaction\Promise\Promise;
use function Reaction\Promise\resolve;

/**
 * Class AFileHelper. Async file helper
 * @package Reaction\Helpers
 */
class FileHelperAsc
{
    /** @var string File system component key in Application */
    public static $fileSystem = 'fs';
    /** @var string File open mode (default to 0755 / rwxr-xr-x) */
    public static $fileCreateMode = 0755;
    /** @var int File lock timeout */
    public static $LockTimeout = 10;
    /** @var array Files those were locked by user for writing */
    protected static $_lockedFiles = [];
    /** @var Deferred[][] Files those were locked by user for writing */
    protected static $_lockedFilesQueue = [];
    /** @var TimerInterface Timer used to unlock "forgotten" files  */
    protected static $_unlockTimer;

    /**
     * Get file object
     * @param string $filePath
     * @return FileInterface|File
     */
    public static function file(&$filePath)
    {
        $filePath = \Reaction::$app->getAlias($filePath);
        $filePath = FileHelper::normalizePath($filePath);
        return static::getFs()->file($filePath);
    }

    /**
     * Get dir object
     * @param string $dirPath
     * @return DirectoryInterface|Directory
     */
    public static function dir(&$dirPath)
    {
        $dirPath = \Reaction::$app->getAlias($dirPath);
        $dirPath = FileHelper::normalizePath($dirPath);
        return static::getFs()->dir($dirPath);
    }

    /**
     * Check that file or directory exists
     * @param string|FileInterface|DirectoryInterface $filePath
     * @return \React\Promise\PromiseInterface
     */
    public static function exists($filePath)
    {
        $file = static::ensureFileObject($filePath);
        return $file->exists();
    }

    /**
     * Open file with given flags
     * @param string $filePath
     * @param string $flags c - create, w - write, r - read, t - truncate
     * @return \React\Promise\PromiseInterface
     */
    public static function open($filePath, $flags = 'r')
    {
        $file = static::ensureFileObject($filePath);
        $createMode = FileHelper::permissionsAsString(static::$fileCreateMode);
        return $file->open($flags, $createMode);
    }

    /**
     * Create a file
     * @param string $filePath
     * @param int|null   $mode
     * @param int|null   $time
     * @return \React\Promise\PromiseInterface
     */
    public static function create($filePath, $mode = null, $time = null)
    {
        $mode = isset($mode) ? $mode : static::$fileCreateMode;
        $modeStr = static::permissionsAsString($mode);
        $time = is_int($time) ? $time : time();
        $file = static::file($filePath);
        return $file->create($modeStr, $time)
            ->then(function() use ($file, $mode) {
                return $file->chmod($mode);
            });
    }

    /**
     * Put contents into file
     * @param string|File $filePath
     * @param string      $contents
     * @param string      $openFlags
     * @param bool|int    $lock Lock file for operation and check for a lock OR lock timeout
     * @param int|null    $createMode
     * @return ExtendedPromiseInterface
     */
    public static function putContents($filePath, $contents, $openFlags = 'cwt', $lock = true, $createMode = null)
    {
        $lockTimeout = is_int($lock) && !empty($lock) ? $lock : null;
        $lock = !empty($lock);
        $file = static::ensureFileObject($filePath);
        $createMode = isset($createMode) ? $createMode : static::$fileCreateMode;
        $createModeStr = FileHelper::permissionsAsString($createMode);
        $unlockCallback = function ($result = null) use ($filePath, $lock) {
            if ($lock) {
                static::unlock($filePath);
            }
            if (is_object($result) && $result instanceof \Throwable) {
                throw $result;
            }
            return $result;
        };
        return static::onUnlock($filePath)
            ->then(function() use (&$file, $filePath, $lockTimeout, $openFlags, $createModeStr, $lock) {
                if ($lock) {
                    static::lock($filePath, $lockTimeout);
                }
                return $file->open($openFlags, $createModeStr);
            })->then(function(WritableStreamInterface $stream) use (&$file, $contents) {
                $stream->write($contents);
                return $file->close();
            })->then($unlockCallback, $unlockCallback);
    }

    /**
     * Get file contents
     * @param string|File $filePath
     * @param bool|int    $lock Lock file for operation OR lock timeout
     * @return ExtendedPromiseInterface
     */
    public static function getContents($filePath, $lock = true)
    {
        $lockTimeout = is_int($lock) && !empty($lock) ? $lock : null;
        $lock = !empty($lock);
        $file = static::ensureFileObject($filePath);
        $unlockCallback = function ($result = null) use ($lock, $filePath) {
            if ($lock) {
                static::unlock($filePath);
            }
            if (is_object($result) && $result instanceof \Throwable) {
                throw $result;
            }
            return $result;
        };
        return static::onUnlock($filePath)->then(
            function () use (&$file, $filePath, $lock, $lockTimeout) {
                if ($lock) {
                    static::lock($filePath, $lockTimeout);
                }
                return $file->exists();
            }
        )
            ->then(function () use (&$file, $filePath) {
                return $file->getContents();
            })->then($unlockCallback, $unlockCallback);
    }

    /**
     * Perform 'chmod' operation
     * @param string|GenericOperationInterface $path File or Directory
     * @param int                              $mode
     * @return \React\Promise\PromiseInterface
     */
    public static function chmod($path, $mode = 0755)
    {
        if ($path instanceof GenericOperationInterface) {
            return $path->chmod($mode);
        }
        return static::file($path)->chmod($mode);
    }

    /**
     * Perform 'chmod' operation recursive for directory
     * @param string|DirectoryInterface $dirPath
     * @param int                       $mode
     * @return \React\Promise\PromiseInterface
     */
    public static function chmodRecursive($dirPath, $mode = 0755)
    {
        $dir = static::ensureDirObject($dirPath);
        return $dir->chmodRecursive($mode);
    }

    /**
     * Create directory
     * @param string $dirPath
     * @param int    $mode
     * @param bool   $recursive
     * @return \React\Promise\PromiseInterface
     */
    public static function createDir($dirPath, $mode = null, $recursive = true)
    {
        $dir = static::ensureDirObject($dirPath);
        $file = static::ensureFileObject($dirPath);
        if ($mode === null) {
            $mode = static::$fileCreateMode;
        }
        return $file->exists()
            ->then(null, function() use ($dir, $mode, $recursive) {
                $createMode = FileHelper::permissionsAsString($mode);
                return $recursive ? $dir->createRecursive($createMode) : $dir->create($mode);
            })->then(function() use ($dir, $mode) {
                return $dir->chmod($mode);
            });
    }

    /**
     * Lock file for some time or until some operation is not finished
     * @param string $filePath
     * @param int $timeout
     */
    public static function lock($filePath, $timeout = null)
    {
        $filePath = FileHelper::normalizePath($filePath);
        $timeout = isset($timeout) ? $timeout : static::$LockTimeout;
        $expire = time() + $timeout;
        if (isset(static::$_lockedFiles[$filePath])) {
            $expire = static::$_lockedFiles[$filePath] <= $expire ? $expire : static::$_lockedFiles[$filePath];
        }
        static::$_lockedFiles[$filePath] = $expire;
        static::checkUnlockTimer();
    }

    /**
     * Unlock file
     * @param string $filePath
     * @param bool   $processQueue
     */
    public static function unlock($filePath, $processQueue = true)
    {
        $filePath = FileHelper::normalizePath($filePath);
        if (isset(static::$_lockedFiles[$filePath])) {
            unset(static::$_lockedFiles[$filePath]);
        }
        if ($processQueue) {
            static::processUnlockQueue($filePath);
        }
    }

    /**
     * Check file is locked or not
     * @param string $filePath
     * @return bool
     */
    public static function isLocked($filePath)
    {
        $filePath = FileHelper::normalizePath($filePath);
        return isset(static::$_lockedFiles[$filePath]);
    }

    /**
     * Get promise of unlocking file
     * @param string $filePath
     * @return ExtendedPromiseInterface
     */
    public static function onUnlock($filePath) {
        $filePath = FileHelper::normalizePath($filePath);
        if (!static::isLocked($filePath)) {
            return resolve(true);
        }
        $deferred = new Deferred();
        if (!isset(static::$_lockedFilesQueue[$filePath])) {
            static::$_lockedFilesQueue[$filePath] = [];
        }
        static::$_lockedFilesQueue[$filePath][] = $deferred;
        return $deferred->promise();
    }

    /**
     * Convert octal permissions to string
     * @param int $modeOctal Octal mode (0755). Do not omit zero, must be octal, not decimal!
     * @return string String permissions representation (rwxr-xr-x)
     */
    public static function permissionsAsString($modeOctal) {
        return FileHelper::permissionsAsString($modeOctal);
    }

    /**
     * Convert string representation of permissions to octal
     * @param string $modeStr String permissions (rwxr-xr-x)
     * @return int Octal permissions representation
     */
    public static function permissionsAsOctal($modeStr) {
        return FileHelper::permissionsAsOctal($modeStr);
    }

    /**
     * Process unlock waiting deferred(s) (and promises)
     * @param string $filePath
     */
    protected static function processUnlockQueue($filePath) {
        if (empty(static::$_lockedFilesQueue[$filePath])) {
            return;
        }
        while (!empty(static::$_lockedFilesQueue[$filePath])) {
            if (static::isLocked($filePath)) {
                break;
            }
            /** @var Deferred $deferred */
            $deferred = array_shift(static::$_lockedFilesQueue[$filePath]);
            $deferred->resolve(true);
        }
    }

    /**
     * Ensure that object is implementing FileInterface
     * @param File|Directory|string $pathOrObject
     * @return File
     */
    protected static function ensureFileObject(&$pathOrObject)
    {
        if ($pathOrObject instanceof FileInterface) {
            return $pathOrObject;
        } elseif ($pathOrObject instanceof DirectoryInterface) {
            return static::file($pathOrObject->getPath());
        } elseif (is_string($pathOrObject)) {
            return static::file($pathOrObject);
        }
        return $pathOrObject;
    }

    /**
     * Ensure that object is implementing DirectoryInterface
     * @param FileInterface|DirectoryInterface|string $pathOrObject
     * @return DirectoryInterface
     */
    protected static function ensureDirObject(&$pathOrObject)
    {
        if ($pathOrObject instanceof DirectoryInterface) {
            return $pathOrObject;
        } elseif ($pathOrObject instanceof FileInterface) {
            return static::dir($pathOrObject->getPath());
        } elseif (is_string($pathOrObject)) {
            return static::dir($pathOrObject);
        }
        return $pathOrObject;
    }

    /**
     * Check if unlock timer is set or create it
     */
    protected static function checkUnlockTimer() {
        if (static::$_unlockTimer instanceof TimerInterface) {
            return;
        }
        static::$_unlockTimer = \Reaction::$app->loop->addPeriodicTimer(1, function () {
            $now = time();
            foreach (static::$_lockedFiles as $filePath => $timeout) {
                if ($timeout <= $now) {
                    static::unlock($filePath);
                }
            }
        });
    }

    /**
     * Get FilesystemInterface object
     * @return FilesystemInterface
     */
    protected static function getFs()
    {
        return \Reaction::$app->{static::$fileSystem};
    }
}


<?php

namespace Colorium\Http;

class Request
{

    /** @var Uri */
    public $uri;

    /** @var int */
    public $code = 200;

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

    /** @var bool http or https */
    public $secure;

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

    /** @var bool */
    public $ajax;

    /** @var Request\Accept */
    public $accept;

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

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

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

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

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

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

    /** @var Request\File[] */
    public $files = [];

    /** @var bool */
    public $cli = false;

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

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

    /** @var array */
    public $local = ['127.0.0.1', '::1'];

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

    /**
     * New http request
     *
     * @param string|Uri $uri
     * @param string $method
     */
    public function __construct($uri = '/', $method = 'GET')
    {
        $this->uri = ($uri instanceof Uri) ? $uri : new Uri($uri);
        $this->method = $method;
        $this->accept = new Request\Accept;
    }

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

    /**
     * Get _server
     *
     * @param string $name
     *
     * @return string
     */
    public function server($name)
    {
        return isset($this->servers[$name]) ? $this->servers[$name] : null;
    }

    /**
     * Get _env
     *
     * @param string $name
     *
     * @return string
     */
    public function env($name)
    {
        return isset($this->envs[$name]) ? $this->envs[$name] : null;
    }

    /**
     * Get _post
     *
     * @param string $name
     *
     * @return string
     */
    public function value($name)
    {
        return isset($this->values[$name]) ? $this->values[$name] : null;
    }

    /**
     * Get _file
     *
     * @param string $name
     *
     * @return Request\File
     */
    public function file($name)
    {
        return isset($this->files[$name]) ? $this->files[$name] : null;
    }

    /**
     * Get _cookie
     *
     * @param string $name
     *
     * @return string
     */
    public function cookie($name)
    {
        return isset($this->cookies[$name]) ? $this->cookies[$name] : null;
    }

    /**
     * If IP is local
     *
     * @return bool
     */
    public function local()
    {
        return in_array($this->ip, $this->local);
    }

    /**
     * Clone request
     */
    public function __clone()
    {
        $this->uri = clone $this->uri;
        $this->accept = clone $this->accept;
        foreach($this->files as $key => $file) {
            $this->files[$key] = clone $file;
        }
    }

    /**
     * Create from global environment
     *
     * @return static
     */
    public static function globals()
    {
        static $globals;
        if(!$globals) {

            $globals = new static(Uri::current());
            $globals->servers = &$_SERVER;
            $globals->envs = &$_ENV;
            $globals->values = &$_POST;
            $globals->cookies = &$_COOKIE;

            $globals->accept = Request\Accept::from(
                $globals->server('HTTP_ACCEPT'),
                $globals->server('HTTP_ACCEPT_LANGUAGE'),
                $globals->server('HTTP_ACCEPT_ENCODING'),
                $globals->server('HTTP_ACCEPT_CHARSET')
            );

            $globals->method = $globals->server('REQUEST_METHOD');
            $globals->secure = ($globals->server('HTTPS') == 'on');
            $globals->ajax = $globals->server('HTTP_X_REQUESTED_WITH')
                && strtolower($globals->server('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest';

            $globals->root = dirname($globals->server('SCRIPT_FILENAME'));
            $globals->root = rtrim($globals->root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

            if(function_exists('http_response_code')) {
                $globals->code = http_response_code();
            }
            if(function_exists('http_get_request_body')) {
                $globals->body = http_get_request_body();
            }
            if(function_exists('apache_request_headers')) {
                $globals->headers = apache_request_headers();
            }

            foreach($_FILES as $index => $file) {
                $globals->files[$index] = new Request\File($file);
            }

            $globals->cli = (php_sapi_name() === 'cli');
            $globals->agent = $globals->server('HTTP_USER_AGENT');
            $globals->ip = $globals->server('REMOTE_ADDR');
            $globals->time = $globals->server('REQUEST_TIME');
        }

        return $globals;
    }

}


<?php

namespace Ekyna\Bundle\CoreBundle\Form\Extension;

use Ekyna\Bundle\CoreBundle\Form\Util\MomentFormatConverter;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class DatetimeTypeExtension
 * @package Ekyna\Bundle\CoreBundle\Form\Extension
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class DatetimeTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $pickerOptions = $options['picker_options'];

        // Set automatically the language
        if (!isset($options['picker_options']['locale'])) {
            $pickerOptions['locale'] = \Locale::getDefault();
        }
        if ($pickerOptions['locale'] == 'en') {
            unset($pickerOptions['locale']);
        }

        // Convert format for moment.js
        $pickerOptions['format'] = MomentFormatConverter::convert($options['format']);

        $view->vars = array_replace($view->vars, [
            'picker_options' => $pickerOptions,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver
            ->setDefaults([
                'widget' => 'single_text',
                'format' => 'dd/MM/yyyy HH:mm', // TODO localised configurable format
                'picker_options' => [
                    'widgetPositioning' => ['horizontal' => 'right'],
                    'showTodayButton' => true,
                    'showClear'       => true,
                    'showClose'       => true,
                ],
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return 'datetime';
    }
}


<?php

namespace NetLimeTheme\Core\Lib;

class ThemeSectionBase implements ThemeSectionBaseInterface
{
    public $cache = false;
    public $template = false;
    public $data = [];

    function __construct($cache = false)
    {
        $this->cache = $cache;
    }

    /**
     * Initialise the section
     */
    function init()
    {
    }

    /**
     * Do something before rendering section
     */
    public function beforeRender()
    {
    }

    /**
     * Do something after rendering section
     */
    public function afterRender()
    {
    }

    /**
     * Render the section
     */
    public function render()
    {
        if (!file_exists($this->template)):
            throw new \Exception("Template of section is not defined.");
        endif;

        $func = $this->closedRender($this->template, $this->data);
        $func();
    }

    /**
     * This will close rending into sandbox disallowing to use $this
     * in the view layer
     *
     * @param $file
     * @param $data
     * @return mixed
     */
    public function closedRender($file, $data)
    {
        return static function () use ($file, $data) {
            extract($data);
            include $file;
        };
    }
}


<?php
namespace wiggum\services\db;

class JoinClause {

	public $type;
	public $table;
	public $clauses = array();
	public $bindings = array();

	/**
	 * Create a new join clause instance.
	 *
	 * @param string $type
	 * @param string $table
	 * @return void
	 */
	public function __construct($type, $table) {
		$this->type = $type;
		$this->table = $table;
	}

	/**
	 * Add an "on" clause to the join.
	 *
	 * @param string $first
	 * @param string $operator
	 * @param string $second
	 * @param string $boolean
	 * @param bool $where
	 * @return \queryBuilder\JoinClause
	 */
	public function on($firstColumn, $operator, $secondColumn, $boolean = 'and', $where = false) {

		if ($where)
			$this->bindings[] = $secondColumn;

		if ($where && ($operator === 'in' || $operator === 'not in') && is_array($secondColumn)) {
			$secondColumn = count($secondColumn);
		}

		$this->clauses[] = compact('firstColumn', 'operator', 'secondColumn', 'boolean', 'where');

		return $this;
	}

	/**
	 * Add an "on where" clause to the join.
	 *
	 * @param string $firstColumn
	 * @param string $operator
	 * @param string $second
	 * @param string $boolean
	 * @return \queryBuilder\JoinClause
	 */
	public function where($firstColumn, $operator, $secondColumn, $boolean = 'and') {
		return $this->on($firstColumn, $operator, $secondColumn, $boolean, true);
	}

	/**
	 * Add an "on where is null" clause to the join.
	 *
	 * @param string $column
	 * @param string $boolean
	 * @return \queryBuilder\JoinClause
	 */
	public function whereNull($column, $boolean = 'and', $not = false) {
		$null = $not ? 'not null' : 'null';

		return $this->on($column, 'is', $null, $boolean, false);
	}

	/**
	 * Add an "on where in (...)" clause to the join.
	 *
	 * @param  string  $column
	 * @param  array  $values
	 * @return \Illuminate\Database\Query\JoinClause
	 */
	public function whereIn($column, array $values, $boolean = 'and', $not = false) {
		$in = $not ? 'not in' : 'in';

		return $this->on($column, $in, $values, $boolean, true);
	}

}


<?php
/**
 * This file is part of the Hephaistos project management API.
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 5.6
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace CSDT\CollectionsBundle\CollectionHelper\HelperTrait;

// @codingStandardsIgnoreStart
use CSDT\CollectionsBundle\CollectionHelper\HelperInterface\ArrayCasterManagerInterface;
// @codingStandardsIgnoreEnd

/**
 * Helper array caster trait
 *
 * This trait define the logic for the
 * helper array casting process.
 *
 * @category Trait
 * @package  Hephaistos
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
trait HelperArrayCasterTrait
{
    /**
     * Array to collection
     *
     * This method inject an array into specific collection type.
     *
     * @param array  $source          The array source to inject
     * @param string $collectionClass The collection class name
     *
     * @throws \ParseError if the array cannot be cast
     * @return CollectionInterface
     */
    public function arrayToCollection(array $source, $collectionClass)
    {
        $manager = $this->manager;
        if ($manager instanceof ArrayCasterManagerInterface) {
            return $manager->process($source, $collectionClass);
        }

        throw new \LogicException(
            "The manager must be set to cast array in collection"
        );
    }
}


<?php namespace Ordercloud\Entities\Products;

use JsonSerializable;

class ProductOptionSet extends AbstractProductAddonSet implements JsonSerializable
{
    /**
     * @var array|ProductOption[]
     * @reflectType Ordercloud\Entities\Products\ProductOption
     */
    protected $options;

    /**
     * @param int                   $id
     * @param string                $name
     * @param string                $displayName
     * @param string                $description
     * @param boolean               $enabled
     * @param array|ProductOption[] $options
     */
    public function __construct($id, $name, $displayName, $description, $enabled, array $options)
    {
        parent::__construct($id, $name, $displayName, $description, $enabled);
        $this->options = $options;
    }

    /**
     * @return array|ProductOption[]
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @param ProductAddonComparator $comparator
     *
     * @return array|ProductOption[]
     */
    public function getSortedOptions(ProductAddonComparator $comparator)
    {
        $options = $this->getOptions();

        usort($options, $comparator);

        return $options;
    }

    /**
     * @param $optionID
     *
     * @return ProductOption|null
     */
    public function getOptionByID($optionID)
    {
        foreach ($this->getOptions() as $option) {
            if ($option->getId() == $optionID) {
                return $option;
            }
        }

        return null;
    }

    /**
     * Specify data which should be serialized to JSON
     */
    public function jsonSerialize()
    {
        $json = parent::jsonSerialize();

        $json['options'] = $this->getOptions();

        return $json;
    }
}


<?php

namespace spec\Yami\SheetFight\Model;

require_once __DIR__.'/../Mock/Collection.php';

use PhpSpec\ObjectBehavior;
use InvalidArgumentException;
use RangeException;
use Yami\SheetFight\Model\InputInterface;
use Yami\SheetFight\Model\MoveInterface;
use Yami\SheetFight\Model\FrameDataInterface;
use LogicException;
use spec\Yami\SheetFight\Mock\Collection;

class MoveSpec extends ObjectBehavior
{
    private $defaultInputs;
    private $defaultCancelAbilities;
    private $defaultFrameData;

    public function let(InputInterface $input, MoveInterface $move, FrameDataInterface $frameData)
    {
        $input->getValue()->willReturn('2');
        $move->getInputs()->willReturn([$input]);
        $move->getInputs(true)->willReturn('2');
        $this->defaultInputs = [$input];
        $this->defaultCancelAbilities = [$move];
        $this->defaultFrameData = $frameData;
        $this->beConstructedWith(
            MoveInterface::TYPE_NORMAL,
            'YamoKick',
            'standing',
            $this->defaultInputs,
            100,
            100,
            'mid',
            $this->defaultCancelAbilities,
            $this->defaultFrameData
        );
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('Yami\SheetFight\Model\Move');
    }

    public function it_is_a_move()
    {
        $this->shouldImplement('Yami\SheetFight\Model\MoveInterface');
    }

    /**
     * Specifies if the move is a normal, special or super.
     *
     * @return bool
     */
    public function it_could_be_normal()
    {
        $this->isNormal()->shouldBeBool();
        $this->isNormal()->shouldBe(true);
        $this->isSpecial()->shouldBe(false);
        $this->isSuper()->shouldBe(false);
    }

    public function it_could_be_special()
    {
        $this->beConstructedWith(MoveInterface::TYPE_SPECIAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData);
        $this->isSpecial()->shouldBeBool();
        $this->isSpecial()->shouldBe(true);
        $this->isNormal()->shouldBe(false);
        $this->isSuper()->shouldBe(false);
    }

    public function it_could_be_super()
    {
        $this->beConstructedWith(MoveInterface::TYPE_SUPER, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData);
        $this->isSuper()->shouldBeBool();
        $this->isSuper()->shouldBe(true);
        $this->isSpecial()->shouldBe(false);
        $this->isNormal()->shouldBe(false);
    }

    public function it_has_a_type()
    {
        $this->getType()->shouldBeString();
        $this->getType()->shouldReturn('normal');
    }

    public function it_has_a_name()
    {
        $this->getName()->shouldBeString();
        $this->getName()->shouldReturn('YamoKick');
    }

    public function its_name_should_be_string()
    {
        $this->shouldThrow(new InvalidArgumentException('The name should be a string'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 123, 'standing', $this->defaultInputs, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_has_an_initial_position()
    {
        $this->getInitialPosition()->shouldBeString();
        $this->getInitialPosition()->shouldReturn('standing');
    }

    public function its_initial_position_should_be_string()
    {
        $this->shouldThrow(new InvalidArgumentException('The initial position should be a string'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 123, $this->defaultInputs, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function its_initial_position_should_be_valid()
    {
        $this->shouldThrow(new InvalidArgumentException('Invalid initial position'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'Yamo', $this->defaultInputs, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_has_inputs()
    {
        $this->getInputs()->shouldReturn($this->defaultInputs);
        $this->getInputs(true)->shouldReturn('2');
    }

    public function its_inputs_should_always_be_an_array()
    {
        $this->shouldThrow(new InvalidArgumentException('The inputs should be an array'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', 1, 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function its_inputs_should_only_contain_input(InputInterface $input)
    {
        $this->shouldThrow(new InvalidArgumentException('The inputs should contain only input'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', [$input, 123], 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_should_have_at_least_one_input()
    {
        $this->shouldThrow(new InvalidArgumentException('The inputs should not be empty'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', [], 100, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_has_damage()
    {
        $this->getDamage()->shouldBeInteger();
        $this->getDamage()->shouldReturn(100);
    }

    public function its_damage_should_be_an_integer()
    {
        $this->shouldThrow(new InvalidArgumentException('The damage should be an integer'))
          ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 1.4, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
      ;
    }

    public function its_damage_should_be_positive()
    {
        $this->shouldThrow(new RangeException('The damage should not be negative'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, -1, 100, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_has_meter_gain()
    {
        $this->getMeterGain()->shouldBeInteger();
        $this->getMeterGain()->shouldReturn(100);
    }

    public function its_meter_gain_should_be_an_integer()
    {
        $this->shouldThrow(new InvalidArgumentException('The meter gain should be an integer'))
          ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 1, 1.4, 'mid', $this->defaultCancelAbilities, $this->defaultFrameData])
      ;
    }

    public function it_has_a_hit_level()
    {
        $this->getHitlevel()->shouldBeString();
        $this->getHitLevel()->shouldReturn('mid');
    }

    public function its_hit_level_should_be_string()
    {
        $this->shouldThrow(new InvalidArgumentException('The hit level should be string'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 123, $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function its_hit_level_should_always_be_valid()
    {
        $this->shouldThrow(new InvalidArgumentException('Invalid hit level'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'Yamo', $this->defaultCancelAbilities, $this->defaultFrameData])
        ;
    }

    public function it_has_cancel_abilities()
    {
        $this->getCancelAbilities()->shouldReturn($this->defaultCancelAbilities);
    }

    public function its_cancel_abilities_could_be_a_collection(Collection $collection)
    {
        $this->beConstructedWith(MoveInterface::TYPE_SPECIAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', $collection, $this->defaultFrameData);
        $this->getCancelAbilities()->shouldReturn($collection);
    }

    public function its_cancel_abilities_should_always_be_an_array()
    {
        $this->shouldThrow(new InvalidArgumentException('The cancel abilities should be an array'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', 123, $this->defaultFrameData])
        ;
    }

    public function its_cancel_abilities_should_only_contain_move(MoveInterface $move)
    {
        $this->shouldThrow(new InvalidArgumentException('The cancel abilities should contain only moves'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', [$move, 123], $this->defaultFrameData])
        ;
    }

    public function its_cancel_abilities_should_contain_unique_moves(MoveInterface $move, InputInterface $input)
    {
        $input->getValue()->willReturn('2');
        $move->getInputs()->willReturn([$input]);
        $this->shouldThrow(new LogicException('The cancel abilities should contain unique moves'))
            ->during('__construct', [MoveInterface::TYPE_NORMAL, 'YamoKick', 'standing', $this->defaultInputs, 100, 100, 'mid', [$move, $move], $this->defaultFrameData])
        ;
    }

    public function it_has_a_frame_data()
    {
        $this->getFrameData()->shouldReturn($this->defaultFrameData);
    }

    public function it_compares_by_inputs(MoveInterface $otherMove)
    {
        $otherMove->getInputs(true)->willReturn('2');
        $this->equals($otherMove)->shouldBeBoolean();
        $this->equals($otherMove)->shouldReturn(true);

        $otherMove->getInputs(true)->willReturn('');
        $this->equals($otherMove)->shouldBeBoolean();
        $this->equals($otherMove)->shouldReturn(false);
    }
}


<?php

declare(strict_types=1);

namespace Ruwork\ObjectStore\DependencyInjection;

use Ruwork\ObjectStore\Exception\LogicException;
use Ruwork\ObjectStore\Type\StoreTypeInterface;
use Ruwork\ObjectStore\TypeResolver\StoreTypeResolver;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

final class AddStoreTypesPass implements CompilerPassInterface
{
    private $serviceId;
    private $tag;

    public function __construct(
        string $serviceId = StoreTypeResolver::class,
        string $tag = 'ruwork_object_store.type'
    ) {
        $this->serviceId = $serviceId;
        $this->tag = $tag;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has($this->serviceId)) {
            return;
        }

        $tagged = $container->findTaggedServiceIds($this->tag, true);
        $references = [];

        foreach ($tagged as $id => $attributes) {
            $class = $container->getDefinition($id)->getClass();

            if (!is_subclass_of($class, StoreTypeInterface::class)) {
                throw new LogicException(sprintf(
                    'Service tagged with "%s" must implement "%s".',
                    $this->tag,
                    StoreTypeInterface::class
                ));
            }

            $references[$class] = new Reference($id);
        }

        $container
            ->findDefinition($this->serviceId)
            ->setArgument('$types', ServiceLocatorTagPass::register($container, $references));
    }
}


<?php

namespace Reaction\Web\Sessions;

use Reaction\Db\CommandInterface;
use Reaction\Db\ConnectionInterface;
use Reaction\Db\DatabaseInterface;
use Reaction\Db\Query;
use Reaction\Promise\ExtendedPromiseInterface;

/**
 * Class SessionArchiveInDb
 * @package Reaction\Web\Sessions
 */
class SessionArchiveInDb extends SessionArchiveAbstract
{
    /**
     * @var string Db table name
     */
    public $table = '{{%session_archive}}';
    /**
     * @var DatabaseInterface|string Database used
     */
    public $db = 'db';

    /**
     * @inheritdoc
     */
    public function init()
    {
        if (!isset($this->db)) {
            $this->db = \Reaction::$app->getDb();
        } elseif (!is_object($this->db)) {
            $this->db = \Reaction::$app->get($this->db);
        }
    }

    /**
     * Get data from archive
     * @param string $id Session id
     * @param bool   $remove Flag to remove data
     * @return ExtendedPromiseInterface with data array
     */
    public function get($id, $remove = false)
    {
        return $this->getInternal($id);
    }

    /**
     * Save data to archive
     * @param string $id
     * @param array  $data
     * @return ExtendedPromiseInterface which resolved after save complete
     */
    public function set($id, $data)
    {
        $dataSerialized = $this->getHandler()->serializeData($data);
        $timestamp = time();
        $row = [
            'sid' => $id,
            'data' => $dataSerialized,
            'updated_at' => $timestamp,
        ];
        return $this->getInternal($id, false)
            ->then(function($existingRow) use ($row) {
                return $this->updateInternal($row, $existingRow);
            }, function() use ($row) {
                return $this->insertInternal($row);
            })->then(function() {
                return true;
            });
    }

    /**
     * Check that session exists in archive
     * @param string $id Session id
     * @return ExtendedPromiseInterface
     */
    public function exists($id)
    {
        return $this->selectQuery()->where(['sid' => $id])->exists($this->db);
    }

    /**
     * Remove from archive
     * @param string $id Session id
     * @return ExtendedPromiseInterface which resolved when process complete
     */
    public function remove($id)
    {
        return $this->createCommand()
            ->delete($this->table, ['sid' => $id])
            ->execute();
    }

    /**
     * Garbage collector callback
     * @param int $lifeTime Session life time in archive
     * @return ExtendedPromiseInterface which resolved after process complete
     */
    public function gc($lifeTime = 3600)
    {
        $expiredTs = time() - $lifeTime;
        return $this->createCommand()
            ->delete($this->table, ['<', 'updated_at', $expiredTs])
            ->execute();
    }

    /**
     * Create SELECT Query
     * @return Query
     */
    protected function selectQuery()
    {
        return (new Query())->from($this->table);
    }

    /**
     * Create command
     * @param string|null              $sql
     * @param array                    $params
     * @param ConnectionInterface|null $connection
     * @return CommandInterface
     */
    protected function createCommand($sql = null, $params = [], $connection = null)
    {
        return $this->db->createCommand($sql = null, $params = [], $connection = null);
    }

    /**
     * Get entry from DB
     * @param string $id
     * @param bool $unserialize
     * @return ExtendedPromiseInterface
     */
    protected function getInternal($id, $unserialize = true)
    {
        return $this->selectQuery()->where(['sid' => $id])
            ->one($this->db)
            ->then(function($row) use ($unserialize) {
                return $unserialize ? $this->getHandler()->unserializeData($row['data']) : $row;
            });
    }

    /**
     * Insert new entry to DB
     * @param array $row
     * @return ExtendedPromiseInterface|\Reaction\Promise\LazyPromiseInterface
     */
    protected function insertInternal($row)
    {
        return $this->createCommand()
            ->insert($this->table, $row)
            ->execute();
    }

    /**
     * Update existing entry in DB
     * @param array      $row
     * @param array|null $existingRow
     * @return ExtendedPromiseInterface|\Reaction\Promise\LazyPromiseInterface
     */
    protected function updateInternal($row, $existingRow = null)
    {
        $equal = isset($existingRow) && isset($existingRow['data']) && $row['data'] === $existingRow['data'];
        $id = $row['sid'];
        unset($row['sid']);
        //If data not changed then just update timestamp
        if ($equal) {
            unset($row['data']);
        }
        return $this->createCommand()
            ->update($this->table, $row, ['sid' => $id])
            ->execute();
    }
}