<?php

/**
 * @author      José Lorente <jose.lorente.martin@gmail.com>
 * @license     The MIT License (MIT)
 * @copyright   José Lorente
 * @version     1.0
 */

namespace jlorente\location\widgets;

use jlorente\location\db\City;
use jlorente\location\db\Country;
use jlorente\location\db\LocationInterface;
use jlorente\location\db\Region;
use jlorente\location\db\State;
use jlorente\location\Module;
use kartik\depdrop\DepDrop;
use Yii;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Inflector;
use yii\helpers\Url;
use yii\widgets\ActiveForm;

/**
 * LocationFormWidget widget.
 *
 * @author José Lorente <jose.lorente.martin@gmail.com>
 */
class LocationFormWidget extends Widget
{

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

    /**
     *
     * @var ActiveForm
     */
    protected $form;

    /**
     *
     * @var LocationInterface
     */
    protected $model;

    /**
     * Model name to submit the model. By default will be the model name.
     *
     * @var LocationInterface
     */
    public $submitModelName;

    /**
     *
     * @var string
     */
    public $template = "{country}\n{state}\n{region}\n{city}\n{address}\n{postalCode}\n{geolocation}";

    /**
     *
     * @var string
     */
    public $localized = 'address';

    /**
     *
     * @var Module
     */
    protected $module;

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

    /**
     * @inheritdoc
     * @throws InvalidConfigException
     */
    public function init()
    {
        parent::init();

        if ($this->form === null) {
            throw new InvalidConfigException('form property must be provided');
        }

        if ($this->model === null) {
            throw new InvalidConfigException('model property must be provided');
        }

        $this->module = Module::getInstance();
    }

    /**
     * @inheritdoc
     */
    public function run()
    {
        $this->ensureFieldIds();
        if (isset($this->fieldIds['country'])) {
            $this->country();
        }
        if (isset($this->fieldIds['state'])) {
            $this->state();
        }
        if (isset($this->fieldIds['region'])) {
            $this->region();
        }
        if (isset($this->fieldIds['city'])) {
            $this->city();
        }
        if (isset($this->fieldIds['address'])) {
            $this->address();
        }
        if (isset($this->fieldIds['postal_code'])) {
            $this->postalCode();
        }
        if (isset($this->fieldIds['latitude']) || isset($this->fieldIds['longitude'])) {
            $this->geolocation();
        }
        return strtr($this->template, $this->parts);
    }

    /**
     * Renders the country part.
     */
    protected function country()
    {
        $this->parts['{country}'] = $this->form->field($this->model, $this->model->getCountryPropertyName(), ['options' => ['class' => 'form-group']])->dropDownList(
                ArrayHelper::map(Country::find()->orderBy(['name' => SORT_ASC])->all(), 'id', 'name'), [
            'id' => $this->fieldIds['country']
            , 'prompt' => Yii::t('jlorente/location', 'Select country')
            , 'name' => $this->getSubmitModelName($this->model->getCountryPropertyName())
        ]);
    }

    /**
     * Renders the region part.
     */
    protected function state()
    {
        $this->parts['{state}'] = $this->form->field($this->model, $this->model->getStatePropertyName())->widget(DepDrop::className(), [
            'options' => [
                'id' => $this->fieldIds['state']
                , 'placeholder' => Yii::t('jlorente/location', 'Select state')
                , 'name' => $this->getSubmitModelName($this->model->getStatePropertyName())
            ]
            , 'data' => ArrayHelper::map(State::find()->where(['country_id' => $this->model->country_id])->orderBy(['name' => SORT_ASC])->all(), 'id', 'name')
            , 'pluginOptions' => [
                'url' => Url::to(["/{$this->module->id}/state/list"])
                , 'depends' => [$this->fieldIds['country']]
            ]
        ]);
    }

    /**
     * Renders the region part.
     */
    protected function region()
    {
        $pluginOptions = [
            'url' => Url::to(["/{$this->module->id}/region/list"])
            , 'depends' => [$this->fieldIds['country']]
        ];
        if (isset($this->fieldIds['state'])) {
            $pluginOptions['depends'][] = $this->fieldIds['state'];
            $pluginOptions['initDepends'] = [$this->fieldIds['country']];
        } else {
            $pluginOptions['depends'][] = null;
        }

        $this->parts['{region}'] = $this->form->field($this->model, $this->model->getRegionPropertyName())->widget(DepDrop::className(), [
            'options' => [
                'id' => $this->fieldIds['region']
                , 'placeholder' => Yii::t('jlorente/location', 'Select region')
                , 'name' => $this->getSubmitModelName($this->model->getRegionPropertyName())
            ]
            , 'data' => ArrayHelper::map(Region::find()->where(['country_id' => $this->model->country_id])->orderBy(['name' => SORT_ASC])->all(), 'id', 'name')
            , 'pluginOptions' => $pluginOptions
        ]);
    }

    /**
     * Renders the city part.
     */
    protected function city()
    {
        $pluginOptions = [
            'url' => Url::to(["/{$this->module->id}/city/list"])
            , 'depends' => [$this->fieldIds['country']]
        ];
        if (isset($this->fieldIds['state'])) {
            $pluginOptions['depends'][] = $this->fieldIds['state'];
            $pluginOptions['initDepends'] = [$this->fieldIds['country']];
        } else {
            $pluginOptions['depends'][] = null;
        }

        if (isset($this->fieldIds['region'])) {
            $pluginOptions['depends'][] = $this->fieldIds['region'];
            if (isset($this->fieldIds['state'])) {
                $pluginOptions['initDepends'][] = $this->fieldIds['state'];
            }
        } else {
            $pluginOptions['depends'][] = null;
        }

        $this->parts['{city}'] = $this->form->field($this->model, $this->model->getCityPropertyName())->widget(DepDrop::className(), [
            'options' => [
                'id' => $this->fieldIds['city']
                , 'cityholder' => Yii::t('jlorente/location', 'Select city')
                , 'name' => $this->getSubmitModelName($this->model->getCityPropertyName())
            ]
            , 'data' => ArrayHelper::map(City::find()->where(['region_id' => $this->model->region_id])->orderBy(['name' => SORT_ASC])->all(), 'id', 'name')
            , 'pluginOptions' => $pluginOptions
        ]);
    }

    /**
     * Renders the address part.
     */
    protected function address()
    {
        $this->parts['{address}'] = $this->form->field($this->model, 'address')->textInput([
            'name' => $this->getSubmitModelName('address')
            , 'id' => $this->fieldIds['address']
        ]);
    }

    /**
     * Renders the postalCode part.
     */
    protected function postalCode()
    {
        $this->parts['{postalCode}'] = $this->form->field($this->model, 'postal_code')->textInput([
            'name' => $this->getSubmitModelName('postal_code')
            , 'id' => $this->fieldIds['postal_code']
        ]);
    }

    /**
     * Renders the geolocation part.
     */
    protected function geolocation()
    {
        $this->parts['{geolocation}'] = $this->form->field($this->model, 'latitude')->textInput([
                    'name' => $this->getSubmitModelName('latitude')
                    , 'id' => $this->fieldIds['latitude']
                ])
                . "\n"
                . $this->form->field($this->model, 'longitude')->textInput([
                    'name' => $this->getSubmitModelName('longitude')
                    , 'id' => $this->fieldIds['longitude']
        ]);
    }

    /**
     *
     * @param ActiveForm $activeForm
     */
    public function setForm(ActiveForm $activeForm)
    {
        $this->form = $activeForm;
    }

    /**
     *
     * @param LocationInterface $model
     */
    public function setModel(LocationInterface $model)
    {
        $this->model = $model;
    }

    /**
     * Gets the submit model name.
     *
     * @param string $attribute
     * @return string
     */
    public function getSubmitModelName($attribute)
    {
        return empty($this->submitModelName) ? Html::getInputName($this->model, $attribute) : $this->submitModelName . "[$attribute]";
    }

    /**
     * Ensures the field ids names.
     */
    protected function ensureFieldIds()
    {
        if ($this->submitModelName) {
            $formName = Inflector::slug($this->submitModelName, '_');
        } else {
            $model = new \ReflectionClass($this->model);
            $formName = $model->getShortName();
        }
        $parts = [];
        preg_match_all('/{([^}]+)}/', $this->template, $parts);
        $keys = array_flip($parts[1]);
        $fieldIds = [];
        if (isset($keys['country'])) {
            $fieldIds['country'] = $formName . '_country_id';
        }
        if (isset($keys['state'])) {
            $fieldIds['state'] = $formName . '_state_id';
        }
        if (isset($keys['region'])) {
            $fieldIds['region'] = $formName . '_region_id';
        }
        if (isset($keys['city'])) {
            $fieldIds['city'] = $formName . '_city_id';
        }
        if (isset($keys['address'])) {
            $fieldIds['address'] = $formName . '_address';
        }
        if (isset($keys['postalCode'])) {
            $fieldIds['postal_code'] = $formName . '_postal_code';
        }
        if (isset($keys['geolocation'])) {
            $fieldIds['latitude'] = $formName . '_latitude';
            $fieldIds['longitude'] = $formName . '_longitude';
        }
        $this->fieldIds = $fieldIds;
    }

}


<?php
/**
 * Phossa Project
 *
 * PHP version 5.4
 *
 * @category  Library
 * @package   Phossa\Query
 * @author    Hong Zhang <phossa@126.com>
 * @copyright 2015 phossa.com
 * @license   http://mit-license.org/ MIT License
 * @link      http://www.phossa.com/
 */
/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

/**
 * OnTrait
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @see     OnInterface
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait OnTrait
{
    /**
     * ONs
     *
     * @var    array
     * @access protected
     */
    protected $clause_on = [];

    /**
     * {@inheritDoc}
     */
    public function on(
        /*# string */ $firstTableCol,
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE,
        /*# bool */ $or = false
    ) {
        if (ClauseInterface::NO_OPERATOR === $operator) {
            $on = [$or, $firstTableCol, '=', $firstTableCol];
        } elseif (ClauseInterface::NO_VALUE === $secondTableCol) {
            $on = [$or, $firstTableCol, '=', $operator];
        } else {
            $on = [$or, $firstTableCol, $operator, $secondTableCol];
        }
        $this->clause_on[] = $on;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function orOn(
        /*# string */ $firstTableCol,
        /*# string */ $operator = ClauseInterface::NO_OPERATOR,
        /*# string */ $secondTableCol = ClauseInterface::NO_VALUE
    ) {
        return $this->on(
            $firstTableCol, $operator, $secondTableCol, true
        );
    }

    /**
     * {@inheritDoc}
     */
    public function onRaw(/*# string */ $on)
    {
        return $this->on($on, ClauseInterface::NO_OPERATOR,
            ClauseInterface::NO_VALUE);
    }

    /**
     * {@inheritDoc}
     */
    public function orOnRaw(/*# string */ $on)
    {
        return $this->on($on, ClauseInterface::NO_OPERATOR,
            ClauseInterface::NO_VALUE, true);
    }

    /**
     * Build ON
     *
     * @return array
     * @access protected
     */
    protected function buildOn()/*# : array */
    {
        $result = [];
        foreach ($this->clause_on as $on) {
            $res = [ $on[0] ? 'OR' : 'ON'];
            $res[] = $this->quote($on[1]); // first col
            $res[] = $on[2]; // operator
            $res[] = $this->quote($on[3]); // second col
            $result[] = join(' ', $res);
        }
        return $result;
    }

    /* utilities from UtilityTrait */
    abstract protected function quote(/*# string */ $str)/*# : string */;
}


<?php
/**
 * Created by PhpStorm.
 * User: claudio
 * Date: 21-01-16
 * Time: 6:50
 */

namespace AscensoDigital\PerfilBundle\Security;

use AscensoDigital\PerfilBundle\Entity\Menu;
use AscensoDigital\PerfilBundle\Entity\Permiso;
use Doctrine\DBAL\DBALException;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class PermisoVoter extends Voter
{
    const MENU = 'menu'; //slug de menu
    const PERMISO = 'permiso'; // nombre del permiso

    private $perfil_id;
    private $permisos;

    public function __construct(Session $session, EntityManager $em, $sessionName)
    {
        $this->perfil_id = $session->get($sessionName,null);
        try{
            $menus = $em->getRepository('ADPerfilBundle:Menu')->findArrayPermisoByPerfil($this->perfil_id);
            $this->permisos[self::MENU] = isset($menus[self::MENU]) ? $menus[self::MENU] : array();

            if(!is_null($this->perfil_id)) {
                $this->permisos[self::PERMISO] = $em->getRepository('ADPerfilBundle:PerfilXPermiso')->findArrayIdByPerfil($this->perfil_id);
            }
        } catch(\PDOException $e) {
            return;
        }
    }

    /**
     * Determines if the attribute and subject are supported by this voter.
     *
     * @param string $attribute An attribute
     * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
     *
     * @return bool True if the attribute and subject are supported, false otherwise
     */
    protected function supports($attribute, $subject)
    {
        // if the attribute isn't one we support, return false
        if (!in_array($attribute, array(self::MENU, self::PERMISO))) {
            return false;
        }

        if ($attribute == self::MENU && !is_null($subject) && !$subject instanceof Menu) {
            return false;
        }

        return true;
    }

    /**
     * Perform a single access check operation on a given attribute, subject and token.
     *
     * @param string $attribute
     * @param mixed $subject
     * @param TokenInterface $token
     *
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        if(is_null($subject)){
            return true;
        }

        switch($attribute){
            case self::MENU:
                /** @var Menu $subject */
                if(isset($this->permisos[$attribute][Permiso::LIBRE]) && in_array($subject->getSlug(), $this->permisos[$attribute][Permiso::LIBRE])){
                    return true;
                }
                if(!isset($this->permisos[$attribute][Permiso::RESTRICT])){
                    return false;
                }
                return in_array($subject->getSlug(), $this->permisos[$attribute][Permiso::RESTRICT]);
            case self::PERMISO:
                if(!isset($this->permisos[$attribute])){
                    return false;
                }
                return in_array($subject, $this->permisos[$attribute]);
        }

        $user = $token->getUser();
        if (!is_object($user)) {
            // the user must be logged in; if not, deny access
            return false;
        }

        if(is_null($this->perfil_id)){
            return false;
        }

        throw new \LogicException('El código no es reconocido!');
    }
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * 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.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Util;

/**
 * PHP の配列機能を使った Map の実装です.
 * このマップはキーに整数または文字列しか使えないという制限があります.
 *
 * このクラスは foreach で各マッピングのキーと値を取り出すことが出来ます.
 */
class ArrayMap implements Map, \IteratorAggregate
{
    /**
     * マッピングを保持する配列です.
     * @var array
     */
    private $data;

    /**
     * 新しいインスタンスを構築します.
     * @param Map|array $var 指定された配列またはマッピングでこのマップを初期化します.
     */
    public function __construct($var = null)
    {
        if ($var instanceof ArrayMap) {
            $this->data = $var->data;
            return;
        }

        if ($var instanceof Map) {
            $this->data = array();
            $entryList = $var->entryList();
            foreach ($entryList as $entry) {
                $this->put($entry->getKey(), $entry->getValue());
            }
            return;
        }

        if (!isset($var)) {
            $this->data = array();
        } elseif (is_array($var)) {
            $this->data = $var;
        } else {
            throw new \InvalidArgumentException("Argument (" . Values::getType($var) . ") must be array or \\Peach\\Util\\Map");
        }
    }

    /**
     * 指定されたキー名にマッピングされている値を返します.
     * マッピングが存在しない場合は代替値 (デフォルトは NULL) を返します.
     * このメソッドの返り値が NULL (または指定した代替値) の場合, 必ずしもマッピングが存在しないとは限りません.
     * マッピングが存在するかどうかを調べる場合は {@link ArrayMap::containsKey} を使用してください.
     *
     * @param  string $name         キー名
     * @param  mixed  $defaultValue デフォルト値
     * @return mixed  指定したキーに関連づけられた値. 存在しない場合は $defaultValue を返す
     */
    public function get($name, $defaultValue = null)
    {
        return (isset($this->data[$name])) ? $this->data[$name] : $defaultValue;
    }

    /**
     * 指定されたキー名と値を関連づけます.
     * この実装では, 内部に保存されている配列に対して
     * <code>
     * $arr[$key] = $value;
     * </code>
     * を実行するのと同等の操作を行います.
     * もしも $key に非スカラー値 (オブジェクトや配列など) が指定された場合は,
     * {@link Values::stringValue} で string 型に変換した結果をキーとします.
     *
     * @param  string $key   キー名
     * @param  mixed  $value 指定されたキーに関連づける値
     */
    public function put($key, $value)
    {
        if (!is_scalar($key)) {
            $key = Values::stringValue($key);
        }

        $this->data[$key] = $value;
    }

    /**
     * 指定された Map のマッピングをすべて登録します.
     *
     * @param Map $map
     * @see   Map::putAll
     */
    public function putAll(Map $map)
    {
        $entryList = $map->entryList();
        foreach ($entryList as $entry) {
            $this->put($entry->getKey(), $entry->getValue());
        }
    }

    /**
     * 指定されたキー名によるマッピングが存在するかどうかを調べます.
     * マッピングが存在する場合に TRUE を返します.
     *
     * @param  string $name キー名
     * @return bool   マッピングが存在する場合に TRUE
     */
    public function containsKey($name)
    {
        return array_key_exists($name, $this->data);
    }

    /**
     * 指定されたキー名によるマッピングが存在する場合に, そのマッピングを削除します.
     * @param string $key キー名
     */
    public function remove($key)
    {
        if (isset($this->data[$key])) {
            unset($this->data[$key]);
        }
    }

    /**
     * このマップを空にします.
     */
    public function clear()
    {
        $this->data = array();
    }

    /**
     * 登録されているマッピングの個数を返します.
     * @return int
     */
    public function size()
    {
        return count($this->data);
    }

    /**
     * このマップに登録されているすべてのキーを配列で返します.
     * 返される配列に対する操作はこのマップには反映されません.
     *
     * @return array
     */
    public function keys()
    {
        return array_keys($this->data);
    }

    /**
     * このマップに登録されているすべての値を配列で返します.
     * 返される配列に対する操作はこのマップには反映されません.
     * @return array
     */
    public function values()
    {
        return array_values($this->data);
    }

    /**
     * このマップに含まれるすべてのエントリーを返します.
     *
     * @return array {@link MapEntry} の配列
     */
    public function entryList()
    {
        $result = array();
        foreach ($this->data as $key => $value) {
            $result[] = new ArrayMapEntry($key, $value, $this);
        }
        return $result;
    }

    /**
     * このマップに登録されているエントリーを配列として返します.
     * 返される配列に対する操作はこのマップには反映されません.
     *
     * @return array このマップの配列表現
     */
    public function asArray()
    {
        return $this->data;
    }

    /**
     * このマップに登録されているマッピングを取り出す Iterator を返します.
     * @return \Iterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->data);
    }
}


<?php

namespace Miky\Bundle\UserBundle\Controller\Frontend;

use FOS\UserBundle\Model\UserInterface;
use Miky\Bundle\UserBundle\Entity\Customer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

class ProfileController extends Controller
{
    /**
     * @return Response
     *
     * @throws AccessDeniedException
     */
    public function showAction()
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw $this->createAccessDeniedException('This user does not have access to this section.');
        }
        return $this->render('SonataUserBundle:Profile:show.html.twig', array(
            'user' => $user,
            'blocks' => $this->container->getParameter('sonata.user.configuration.profile_blocks'),
        ));
    }

    /**
     * @return Response|RedirectResponse
     *
     * @throws AccessDeniedException
     */
    public function editProfileAction(Request $request)
    {
        $customer = $this->getUser();
        if (!is_object($customer) || !$customer instanceof Customer) {
            return $this->redirectToRoute("miky_app_customer_security_login");
        }

        $customerManager = $this->container->get('miky_customer_manager');
        $customerManager->getRepository()->findOneById($customer->getId());
        $form = $this->createForm('miky_customer_profile_front', $customer);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();
            $customerManager->updateUser($user);
        }

        return $this->render('MikyUserBundle:Profile:edit.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * @param string $action
     * @param string $value
     */
    protected function setFlash($action, $value)
    {
        $this->get('session')->getFlashBag()->set($action, $value);
    }
}


<?php
/**
 * AnimeDb package.
 *
 * @author    Peter Gribanov <info@peter-gribanov.ru>
 * @copyright Copyright (c) 2014, Peter Gribanov
 * @license   http://opensource.org/licenses/MIT
 */

namespace AnimeDb\Bundle\CacheTimeKeeperBundle\Service\Driver;

/**
 * Multi drivers.
 *
 * The driver is a wrapper for multiple drivers. Takes the driver with quick
 * access to the data (stored in memory) and slow (stored on the hard drive),
 * and receives data on the possibility of fast drivers and if not luck reads
 * data from slow.
 */
class Multi extends BaseDriver
{
    /**
     * @var DriverInterface
     */
    protected $fast;

    /**
     * @var DriverInterface
     */
    protected $slow;

    /**
     * @param DriverInterface $fast
     * @param DriverInterface $slow
     */
    public function __construct(DriverInterface $fast, DriverInterface $slow)
    {
        $this->fast = $fast;
        $this->slow = $slow;
    }

    /**
     * @param string $key
     *
     * @return \DateTime|null
     */
    public function get($key)
    {
        if ($time = $this->fast->get($key)) {
            return $time;
        }

        return $this->slow->get($key);
    }

    /**
     * @param string $key
     * @param \DateTime $time
     *
     * @return bool
     */
    public function set($key, \DateTime $time)
    {
        if ($this->fast->set($key, $time)) {
            return $this->slow->set($key, $time);
        }

        return false;
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function remove($key)
    {
        if ($this->fast->remove($key)) {
            return $this->slow->remove($key);
        }

        return false;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: christof
 * Date: 20.11.15
 * Time: 12:37.
 */
namespace MandarinMedien\MMMediaBundle\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use MandarinMedien\MMMediaBundle\Entity\Media;
use MandarinMedien\MMMediaBundle\Form\DataTransformer\MediaToMediaSortableTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;

class UploadType extends AbstractType
{
    protected $manager;

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

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['multiple'] = $options['multiple'];
        $view->vars['allowed_filetypes'] = $options['allowed_filetypes'];

        $mediaEntity = $this->manager->getRepository('MMMediaBundle:Media')->find((int) $view->vars['value']);
        $view->vars['value_media_json'] = $this->getJsonFormatedMedia($mediaEntity);
        // TODO: implement MediaType Configuration
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'multiple' => false,
            'class' => Media::class,
            'allowed_filetypes' => null,
        ));

        $resolver
            ->setAllowedTypes('multiple', 'boolean')
            ->setAllowedTypes('allowed_filetypes', array('null', 'array'));
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer(new MediaToMediaSortableTransformer($this->manager));
    }

    public function getParent()
    {
        return HiddenEntityType::class;
    }

    /**
     * @param Media $media
     *
     * @return string
     */
    public function getJsonFormatedMedia($media = null)
    {
        $data = array();

        if ($media) {
            $data[] = array(
                'id' => $media->getId(),
                'name' => $media->getMediaTypeReference(),
                'size' => false,
                'type' => '',
                'url' => '/media/'.$media->getMediaTypeReference(),
            );
        }

        return json_encode($data);
    }
}


<?php
/*
 * Copyright (c) 2014 @trashtoy
 * https://github.com/trashtoy/
 *
 * 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.
 */
/**
 * PHP class file.
 * @auhtor trashtoy
 * @since  2.0.0
 */
namespace Peach\Util;

/**
 * 任意の値やオブジェクトをキーに指定することが出来る Map です. 格納のアルゴリズムは
 * {@link http://docs.oracle.com/javase/jp/7/api/java/util/HashMap.html java.util.HashMap}
 * を参考にしています.
 * キーに使用するオブジェクトは, 出来る限り不変 (イミュータブル) なものを使用してください.
 * キーに設定したオブジェクトに対して外部から変更が加わった場合,
 * このオブジェクトの動作は保障されません.
 */
class HashMap implements Map
{
    /**
     * このマップが持つエントリーの一覧です.
     * この値は以下のような構造となります. (値は HashMapEntry オブジェクト)
     *
     * <pre>
     * array(
     *     [0] => array(
     *         [0] => entry1
     *         [1] => entry4
     *         [2] => entry5
     *     )
     *     [1] => array(
     *         [0] => entry2
     *         [1] => entry3
     *     )
     *     [2] => ...
     * )
     * </pre>
     *
     * @var array
     */
    private $table;

    /**
     * 格納先のインデックスの個数です.
     * 常に 2 の累乗の値になります.
     *
     * @var int
     */
    private $capacity;

    /**
     * キーの等価性のチェックを行うために使用する Equator です.
     * @var Equator
     */
    private $equator;

    /**
     * put() や remove() などで内部構造に変化が加えられたことを示すフラグです.
     * {@link HashMap::entryList} を呼び出した際にキャッシュを使用するかどうか
     * 判断するために使用します.
     *
     * @var bool
     */
    private $modFlag;

    /**
     * {@link HashMap::entryList} の返り値のキャッシュデータです.
     * この値はオブジェクトの内部構造が変化すると無効化されます.
     *
     * @var array
     */
    private $cache;

    /**
     * 新しい HashMap を構築します.
     * 引数で設定された容量は, オブジェクト構築後に変更することは出来ません.
     *
     * @param  Map|array $map      デフォルトのマッピング (オプション)
     * @param  Equator   $e        オブジェクトの等価性を判断するための Equator
     *                             (NULL の場合は {@link DefaultEquator} が適用されます)
     * @param  int       $capacity 容量 (デフォルトは 16, 最小で 2)
     */
    public function __construct($map = null, Equator $e = null, $capacity = 16)
    {
        $this->table    = array();
        $this->equator  = isset($e) ? $e : DefaultEquator::getInstance();
        $this->capacity = self::detectCapacity($capacity);
        $this->modFlag  = true;
        $this->cache    = array();
        if (isset($map)) {
            $this->initTable($map);
        }
    }

    /**
     * コンストラクタの第一引数が指定された場合に実行される,
     * マッピングの初期化処理です.
     *
     * @param Map|array $map
     */
    private function initTable(&$map)
    {
        if ($map instanceof Map) {
            $entryList = $map->entryList();
            foreach ($entryList as $entry) {
                $this->put($entry->getKey(), $entry->getValue());
            }
            return;
        }
        if (is_array($map)) {
            foreach ($map as $key => $value) {
                $this->put($key, $value);
            }
            return;
        }

        throw new \InvalidArgumentException("Argument (" . Values::getType($map) . ") must be array or \\Peach\\Util\\Map");
    }

    /**
     * このマップの容量を計算します.
     * 引数以上で最小の 2 の累乗となる整数を返します.
     * @param int $capacity 容量
     */
    private static function detectCapacity($capacity)
    {
        if ($capacity < 2) {
            return 2;
        }

        $i = 2;
        while ($i < $capacity) {
            $i *= 2;
        }
        return $i;
    }

    /**
     * 指定されたキーと値をこの Map に関連づけます.
     * @param mixed $key   キー
     * @param mixed $value 値
     */
    public function put($key, $value)
    {
        $index = $this->getIndexOf($key);
        if (!isset($this->table[$index])) {
            $this->table[$index] = array();
        }
        foreach ($this->table[$index] as $entry) {
            if ($entry->keyEquals($key, $this->equator)) {
                $entry->setValue($value);
                $this->modFlag = true;
                return;
            }
        }
        $this->table[$index][] = $this->createEntry($key, $value);
        $this->modFlag = true;
    }

    /**
     * 指定された Map の中身をすべて追加します。
     * もしも引数の Map とこの Map に同じキーが存在していた場合,
     * 引数のマッピングで上書きされます.
     *
     * @param Map $map 格納される Map
     * @see   Map::putAll
     */
    public function putAll(Map $map)
    {
        $entryList = $map->entryList();
        foreach ($entryList as $entry) {
            $this->put($entry->getKey(), $entry->getValue());
        }
    }

    /**
     * 指定されたキーにマッピングされている値を返します.
     * マッピングが存在しない場合は代替値 (デフォルトは NULL) を返します.
     * このメソッドの返り値が NULL (または指定した代替値) の場合, 必ずしもマッピングが存在しないとは限りません.
     * マッピングの存在を確認する場合は {@link HashMap::containsKey} を使用してください.
     *
     * @param  mixed $key          マッピングのキー
     * @param  mixed $defaultValue マッピングが存在しない場合に返される代替値
     * @return mixed
     */
    public function get($key, $defaultValue = null)
    {
        $index = $this->getIndexOf($key);
        if (!isset($this->table[$index])) {
            return $defaultValue;
        }
        foreach ($this->table[$index] as $entry) {
            if ($entry->keyEquals($key, $this->equator)) {
                return $entry->getValue();
            }
        }
        return $defaultValue;
    }

    /**
     * マッピングを空にします.
     */
    public function clear()
    {
        $this->table = array();
        $this->modFlag = true;
    }

    /**
     * この Map が持つマッピングの個数を返します.
     * @return int
     * @see    Map::size
     */
    public function size()
    {
        $size = 0;
        foreach ($this->table as $entries) {
            $size += count($entries);
        }
        return $size;
    }

    /**
     * この HashMap に含まれるキーの一覧を返します.
     * @return array この HashMap に含まれるキーの配列
     */
    public function keys()
    {
        $result = array();
        foreach ($this->table as $entries) {
            foreach ($entries as $entry) {
                $result[] = $entry->getKey();
            }
        }
        return $result;
    }

    /**
     * 指定されたキーによるマッピングが存在するかどうかを調べます.
     * マッピングが存在する場合に TRUE を返します.
     *
     * @param  mixed $key キー
     * @return bool       マッピングが存在する場合に TRUE
     */
    public function containsKey($key)
    {
        $index = $this->getIndexOf($key);
        if (!isset($this->table[$index])) {
            return false;
        }
        foreach ($this->table[$index] as $entry) {
            if ($entry->keyEquals($key, $this->equator)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 指定されたキーのマッピングを削除します.
     * @param mixed $key キー
     */
    public function remove($key)
    {
        $index = $this->getIndexOf($key);
        if (!isset($this->table[$index])) {
            return;
        }
        foreach ($this->table[$index] as $i => $entry) {
            if ($entry->keyEquals($key, $this->equator)) {
                array_splice($this->table[$index], $i, 1);
                $this->modFlag = true;
                return;
            }
        }
        return;
    }

    /**
     * このマップに登録されているすべての値を配列で返します.
     * 返される配列に対する操作はこのマップには反映されません.
     * @return array
     */
    public function values()
    {
        $result = array();
        foreach ($this->table as $entries) {
            foreach ($entries as $entry) {
                $result[] = $entry->getValue();
            }
        }
        return $result;
    }

    /**
     * この HashMap に登録されているすべてのエントリーを返します.
     *
     * @return array {@link HashMapEntry} の配列
     */
    public function entryList()
    {
        if ($this->modFlag) {
            $this->cache = array();
            foreach ($this->table as $entries) {
                foreach ($entries as $entry) {
                    $this->cache[] = $entry;
                }
            }
            $this->modFlag = false;
        }
        return $this->cache;
    }

    /**
     * 指定されたキーと値をマッピングする, 新しい {@link HashMapEntry} を構築します.
     * ユーザーは, 必要に応じてこのメソッドをオーバーライドし,
     * 機能拡張した HashMapEntry を返すようにすることもできます.
     *
     * @param  mixed $key   マッピングのキー
     * @param  mixed $value マッピングの値
     * @return HashMapEntry 引数の $key と $value をマッピングした HashMapEntry
     */
    protected function createEntry($key, $value)
    {
        return new HashMapEntry($key, $value);
    }

    /**
     * 指定されたキーのインデックスを返します.
     * @param  string $key
     * @return int
     */
    private function getIndexOf($key)
    {
        $hash = $this->equator->hashCode($key);
        return ($this->capacity - 1) & $hash;
    }
}


<?php

namespace vkabachenko\phpuser;

use yii\base\Object;
use yii\helpers\VarDumper;

class UserManager extends Object
{
    const FILENAME = 'users.php';

    /**
     * @var $_params array
     * Structure:
     * [
     *     'users' => [
     *                'user1'=> [
     *                    'password' => 'hash11',
     *                    'authkey => 'hash12'
     *                  ],
     *                 'user2' => [
     *                    'password' => 'hash21',
     *                    'authkey => 'hash22'
     *                  ],
     * ........................................
     *               ]
     * ]
     */
    private $_params;

    /**
     * @var $_file string user config file with path
     */
    private $_file;

    public $path; // alias of directory where config file exists

    /**
     * prepare array of users in init
     */
    public function init()
    {
        $this->_file = \Yii::getAlias($this->path.'/config/'.self::FILENAME);
        $this->loadFromFile();
    }

    /**
     * @param $userData array
     * structure:
     * ['user1' => [
     *   'password' => 'hash11',
     *   'authkey => 'hash12']
     * ]
     */
    public function addUser($newData)
    {
        $this->_params['users'] = array_merge($this->_params['users'],$newData);
        $this->saveToFile();
    }

    /**
     * load user data from config file
     */
    private function loadFromFile()
    {
        if (is_file($this->_file)) {
            $this->_params = require($this->_file);
        } else {
            $this->_params = ['users' => []];
        }
    }

    /**
     * save user data to config file
     */
    private  function saveToFile()
    {
        file_put_contents($this->_file, "<?php\nreturn " . VarDumper::export($this->_params) . ";\n", LOCK_EX);
    }

}