<?php

namespace MediaWiki\Extension\MetaStore;

use OutputPage, PPFrame, RequestContext, Skin;

/**
 * Class MW_EXT_Kernel
 */
class MW_EXT_Kernel {

	/**
	 * Clear DATA (escape html).
	 *
	 * @param $string
	 *
	 * @return string
	 */
	public static function outClear( $string ) {
		$trim = trim( $string );
		$out  = htmlspecialchars( $trim, ENT_QUOTES );

		return $out;
	}

	/**
	 * Normalize DATA (lower case & remove space).
	 *
	 * @param $string
	 *
	 * @return string
	 */
	public static function outNormalize( $string ) {
		$replace = str_replace( ' ', '-', $string );
		$out     = mb_strtolower( $replace, 'UTF-8' );

		return $out;
	}

	/**
	 * Get JSON data.
	 *
	 * @param $src
	 *
	 * @return mixed
	 */
	public static function getJSON( $src ) {
		$src = file_get_contents( $src );
		$out = json_decode( $src, true );

		return $out;
	}

	/**
	 * Wiki Framework: Message.
	 *
	 * @param $id
	 * @param $key
	 *
	 * @return string
	 */
	public static function getMessageText( $id, $key ) {
		$string  = 'mw-ext-' . $id . '-' . $key;
		$message = wfMessage( $string )->inContentLanguage();
		$out     = $message->text();

		return $out;
	}

	/**
	 * Wiki Framework: Configuration parameters.
	 *
	 * @param $config
	 *
	 * @return mixed
	 * @throws \ConfigException
	 */
	public static function getConfig( $config ) {
		$context = RequestContext::getMain()->getConfig();
		$out     = $context->get( $config );

		return $out;
	}

	/**
	 * Wiki Framework: Title.
	 *
	 * @return null|\Title
	 */
	public static function getTitle() {
		$context = RequestContext::getMain();
		$out     = $context->getTitle();

		return $out;
	}

	/**
	 * Wiki Framework: User.
	 *
	 * @return \User
	 */
	public static function getUser() {
		$context = RequestContext::getMain();
		$out     = $context->getUser();

		return $out;
	}

	/**
	 * Wiki Framework: WikiPage.
	 *
	 * @return \WikiPage
	 * @throws \MWException
	 */
	public static function getWikiPage() {
		$context = RequestContext::getMain();
		$out     = $context->getWikiPage();

		return $out;
	}

	/**
	 * Converts an array of values in form [0] => "name=value" into a real
	 * associative array in form [name] => value. If no = is provided,
	 * true is assumed like this: [name] => true.
	 *
	 * @param array $options
	 * @param PPFrame $frame
	 *
	 * @return array
	 */
	public static function extractOptions( $options = [], PPFrame $frame ) {
		$results = [];

		foreach ( $options as $option ) {
			$pair = explode( '=', $frame->expand( $option ), 2 );

			if ( count( $pair ) === 2 ) {
				$name             = MW_EXT_Kernel::outClear( $pair[0] );
				$value            = MW_EXT_Kernel::outClear( $pair[1] );
				$results[ $name ] = $value;
			}

			if ( count( $pair ) === 1 ) {
				$name             = MW_EXT_Kernel::outClear( $pair[0] );
				$results[ $name ] = true;
			}
		}

		return $results;
	}

	/**
	 * Load resource function.
	 *
	 * @param OutputPage $out
	 * @param Skin $skin
	 *
	 * @return bool
	 */
	public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
		$out->addModuleStyles( [ 'ext.mw.kernel.styles' ] );

		return true;
	}
}


<?php
namespace HtSettingsModule\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use HtSettingsModule\Mapper\DbSettingsMapper;

class DbSettingsMapperFactory implements FactoryInterface
{
    /**
     * Gets settings mapper
     *
     * @param  ServiceLocatorInterface $serviceLocator
     * @return DbSettingsMapper
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $options = $serviceLocator->get('HtSettingsModule\Options\ModuleOptions');
        $mapper = new DbSettingsMapper();
        $mapper->setDbAdapter($serviceLocator->get('HtSettingsModule\DbAdapter'));
        $entityClass = $options->getParameterEntityClass();
        $mapper->setEntityPrototype(new $entityClass);
        $mapper->setTableName($options->getSettingsTable());

        return $mapper;
    }
}


<?php
/**
 * File VendorOptionCollectionHandler.php
 * Created at: 2014-12-30 07-06
 *
 * @author Daniel Bojdo <daniel.bojdo@web-it.eu>
 */

namespace Webit\Shipment\Serializer;

use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\VisitorInterface;

class VendorOptionCollectionHandler implements SubscribingHandlerInterface
{
    /**
     * @var VendorOptionCollectionNormaliser
     */
    private $vendorOptionCollectionNormaliser;

    /**
     * @var VendorOptionValueCollectionNormaliser
     */
    private $vendorOptionValueCollectionNormaliser;

    /**
     * VendorOptionCollectionHandler constructor.
     * @param VendorOptionCollectionNormaliser $vendorOptionCollectionSerialiser
     * @param VendorOptionValueCollectionNormaliser $vendorOptionValueCollectionSerialiser
     */
    public function __construct(
        VendorOptionCollectionNormaliser $vendorOptionCollectionSerialiser,
        VendorOptionValueCollectionNormaliser $vendorOptionValueCollectionSerialiser
    ) {
        $this->vendorOptionCollectionNormaliser = $vendorOptionCollectionSerialiser;
        $this->vendorOptionValueCollectionNormaliser = $vendorOptionValueCollectionSerialiser;
    }

    /**
     * Return format:
     *
     *      array(
     *          array(
     *              'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
     *              'format' => 'json',
     *              'type' => 'DateTime',
     *              'method' => 'serializeDateTimeToJson',
     *          ),
     *      )
     *
     * The direction and method keys can be omitted.
     *
     * @return array
     */
    public static function getSubscribingMethods()
    {
        $supported = array();
        foreach (array('json', 'xml') as $format) {
            $supported[] = array(
                'format' => $format,
                'type' => 'Webit\Shipment\Vendor\VendorOptionCollection',
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'method' => 'serializeOptionCollection'
            );

            $supported[] = array(
                'format' => $format,
                'type' => 'Webit\Shipment\Vendor\VendorOptionCollection',
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'method' => 'deserializeVendorOptionCollection'
            );

            $supported[] = array(
                'format' => $format,
                'type' => 'Webit\Shipment\Vendor\VendorOptionValueCollection',
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
                'method' => 'serializeOptionValueCollection'
            );

            $supported[] = array(
                'format' => $format,
                'type' => 'Webit\Shipment\Vendor\VendorOptionValueCollection',
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'method' => 'deserializeVendorOptionValueCollection'
            );
        }

        return $supported;
    }

    /**
     * @param VisitorInterface $visitor
     * @param $data
     * @param $type
     * @param Context $context
     * @return array|null
     */
    public function serializeOptionCollection(VisitorInterface $visitor, $data, $type, Context $context)
    {
        if ($data) {
            return $this->vendorOptionCollectionNormaliser->normalise($data);
        }

        return null;
    }

    /**
     * @param VisitorInterface $visitor
     * @param $data
     * @param $type
     * @param Context $context
     * @return array|null
     */
    public function serializeOptionValueCollection(VisitorInterface $visitor, $data, $type, Context $context)
    {
        if ($data) {
            return $this->vendorOptionValueCollectionNormaliser->normalise($data);
        }

        return null;
    }

    /**
     * @param VisitorInterface $visitor
     * @param $data
     * @param $type
     * @param Context $context
     * @return \Webit\Shipment\Serializer\VendorOptionCollection
     */
    public function deserializeVendorOptionCollection(VisitorInterface $visitor, $data, $type, Context $context)
    {
        return $this->vendorOptionCollectionNormaliser->denormalise($data);
    }

    /**
     * @param VisitorInterface $visitor
     * @param $data
     * @param $type
     * @param Context $context
     * @return \Webit\Shipment\Serializer\VendorOptionCollection
     */
    public function deserializeVendorOptionValueCollection(VisitorInterface $visitor, $data, $type, Context $context)
    {
        return $this->vendorOptionValueCollectionNormaliser->denormalise($data);
    }
}


<?php

/**
 * The Cerberus class.
 *
 * @author  Leandro Silva <leandro@leandrosilva.info>
 * @license https://github.com/mt-olympus/cerberus/blob/master/LICENSE MIT Licence
 */
namespace Cerberus;

use Zend\Cache\Storage\StorageInterface;

/**
 * The Cerberus Class.
 *
 * @author  Leandro Silva <leandro@leandrosilva.info>
 * @license https://github.com/mt-olympus/cerberus/blob/master/LICENSE MIT Licence
 */
class Cerberus implements CerberusInterface
{
    /**
     * The storage object.
     *
     * @var \Zend\Cache\Storage\StorageInterface
     */
    private $storage;

    /**
     * Maximum number of failures to open the circuit.
     *
     * @var int
     */
    private $maxFailures;

    /**
     * Number of seconds to change from OPEN to HALF OPEN and try the connection again.
     *
     * @var int
     */
    private $timeout;

    /**
     * The default namespace used by the zend-cache storage.
     *
     * @var string
     */
    private $defaultNamespace;

    /**
     * Constructor.
     *
     * @param StorageInterface $storage     The storage object
     * @param int              $maxFailures Maximum number of failures to open the circuit
     * @param int              $timeout     Number of seconds to change from OPEN to HALF OPEN
     */
    public function __construct(StorageInterface $storage, $maxFailures = 5, $timeout = 30)
    {
        $this->maxFailures = (int) $maxFailures;
        $this->timeout = (int) $timeout;
        $this->storage = $storage;
        $this->defaultNamespace = $this->storage->getOptions()->getNamespace();
    }

    /**
     * {@inheritdoc}
     *
     * @see \Cerberus\CerberusInterface::isAvailable()
     */
    public function isAvailable($serviceName = null)
    {
        return $this->getStatus($serviceName) !== CerberusInterface::OPEN;
    }

    /**
     * {@inheritdoc}
     *
     * @see \Cerberus\CerberusInterface::getStatus()
     */
    public function getStatus($serviceName = null)
    {
        $this->setNamespace($serviceName);

        $success = false;
        $failures = (int) $this->storage->getItem('failures', $success);
        if (!$success) {
            $failures = 0;
            $this->storage->setItem('failures', $failures);
        }

        // Still has failures left
        if ($failures < $this->maxFailures) {
            return CerberusInterface::CLOSED;
        }

        $success = false;
        $lastAttempt = $this->storage->getItem('last_attempt', $success);

        // This is the first attempt after a failure, open the circuit
        if (!$success) {
            $lastAttempt = time();
            $this->storage->setItem('last_attempt', $lastAttempt);

            return CerberusInterface::OPEN;
        }

        // Reached maxFailues but has passed the timeout limit, so we can try again
        // We update the lastAttempt so only one call passes through
        if (time() - $lastAttempt >= $this->timeout) {
            $lastAttempt = time();
            $this->storage->setItem('last_attempt', $lastAttempt);

            return CerberusInterface::HALF_OPEN;
        }

        return CerberusInterface::OPEN;
    }

    /**
     * {@inheritdoc}
     *
     * @see \Cerberus\CerberusInterface::reportFailure()
     */
    public function reportFailure($serviceName = null)
    {
        $this->setNamespace($serviceName);
        $this->storage->incrementItem('failures', 1);
    }

    /**
     * {@inheritdoc}
     *
     * @see \Cerberus\CerberusInterface::reportSuccess()
     */
    public function reportSuccess($serviceName = null)
    {
        $this->setNamespace($serviceName);
        $this->storage->setItem('failures', 0);
    }

    /**
     * Sets the zend-cache storage namespace.
     *
     * @param string $serviceName
     */
    private function setNamespace($serviceName = null)
    {
        if ($serviceName === null) {
            $this->storage->getOptions()->setNamespace($this->defaultNamespace);
        } else {
            $this->storage->getOptions()->setNamespace($serviceName);
        }
    }
}


<?php

/**
 * @todo Description
 *
 * I called them Pinicons & Tabicons in keeping with the absolutely pointless name: Favicons.
 *
 * @package silverstripe-seo
 * @subpackage icons
 * @author Andrew Gerber <atari@graphiquesdigitale.net>
 * @version 1.0.0
 *
 */
class SEO_Icons_SiteConfig_DataExtension extends DataExtension
{

    /* Static Variables
    ------------------------------------------------------------------------------*/

    //
    private static $SEOIconsUpload = 'SEO/SiteConfig/Icons/';

    //
    const APPLE_ICON_DEFAULT_BACKGROUND = '000000';

    /* Overload Model
    ------------------------------------------------------------------------------*/

    private static $db = array(
        // Pinned Icon Title
        'PiniconTitle' => 'Varchar(128)',
        // Android Pinned Icon
        'AndroidPiniconThemeColor' => 'Varchar(6)',
        // MS Tile
        'WindowsPiniconBackgroundColor' => 'Varchar(6)',
        // Safari Pinned Tab
//		'SafariTabiconThemeColor' => 'Varchar(6)', // @todo maybe implement
    );
    private static $has_one = array(
        // Favicon
//		'HTML4Favicon' => 'Image', // @todo maybe implement
        'HTML5Favicon' => 'Image',
        // Apple Pinned Icon
        'IOSPinicon' => 'Image',
        // Android Pinned Icon
        'AndroidPinicon' => 'Image',
        // Windows Pinned Icon
        'WindowsPinicon' => 'Image',
        // Safari Pinned Tab
//		'SafariTabiconDefault' => 'Image', // @todo maybe implement
//		'SafariTabiconWide' => 'Image', // @todo maybe implement
//		'SafariTabiconLarge' => 'Image', // @todo maybe implement
    );

    /* Overload Methods
    ------------------------------------------------------------------------------*/

    /**
     * Adds tabs & fields to the CMS.
     *
     * @param FieldList $fields
     */
    public function updateCMSFields(FieldList $fields)
    {

        //// Favicons Tab

        $tab = 'Root.Metadata.Favicons';

        //// Favicon

        $fields->addFieldsToTab($tab, array(
            LabelField::create('FaviconDescription', 'Favicons are `favourite icons` used by browsers in a number of ways whenever an icon is necessary e.g. tabs, history, bookmarks, dashboards.
@ Favicon - Wikipedia, the free encyclopedia')
                ->addExtraClass('information')
        ));

        //// HTML4 Favicon

        // check favicon.ico & set status
        $icoStatus = ReadonlyField::create('HTML4FaviconStatus', 'Favicon ICO
type: ico

size: (multiple)
16x16 & 32x32 & 64x64 px
', 'favicon.ico error');
        if (Director::fileExists('favicon.ico')) {
            $icoStatus
                ->setValue('favicon.ico found')
                ->addExtraClass('success favicon');
        } else {
            $icoStatus
                ->setValue('favicon.ico not found')
                ->addExtraClass('error');
        }

        // header & fields
        $fields->addFieldsToTab($tab, array(
            HeaderField::create('HTML4FaviconHeader', 'HTML4 ( favicon.ico )'),
            LabelField::create('HTML4FaviconDescription', 'It is recommended you simply have a `favicon.ico` file in the webroot.')
                ->addExtraClass('information'),
            $icoStatus
        ));

        //// HTML5 Favicon

        // header & fields
        $fields->addFieldsToTab($tab, array(
            HeaderField::create('HTML5FaviconHeader', 'HTML5 ( favicon.png )'),
            LabelField::create('HTML5FaviconDescription', '@todo Description')
                ->addExtraClass('information'),
            UploadField::create('HTML5Favicon', 'Favicon PNG
type: png

size: 192x192 px
')
                ->setAllowedExtensions(array('png'))
                ->setFolderName(self::$SEOIconsUpload)
        ));

        //// Pinned Icons Tab

        $tab = 'Root.Metadata.PinnedIcons';

        //// Pinned Icons Information

        $fields->addFieldsToTab($tab, array(
            LabelField::create('PiniconDescription', 'Pinned icons are OS-specific desktop shortcuts to pages on your website, they allow you to configure additional theming options to make pages appear more `native` / `web-app-y` within the OS.
Given they are OS-specific, they (obviously!) have a different format for each one :(')
                ->addExtraClass('information')
        ));

        //// Pinned Icon Title

        // CMS fields
        $fields->addFieldsToTab($tab, array(
            // header
            HeaderField::create('PiniconTitleHeader', 'Pinned Icon Title ( a.k.a. App Name )'),
            // description
            LabelField::create('PiniconTitleDescription', 'When adding a link to the home screen, the user can choose a caption. By default, this is the bookmarked page title, which is usually fine. However, iOS and Windows 8 let you override this default value.')
                ->addExtraClass('information'),
            TextField::create('PiniconTitle', 'Application Title')
                ->setAttribute('placeholder', 'default: page title')
        ));

        //// iOS Pinned Icon

        // CMS fields
        $fields->addFieldsToTab($tab, array(
            // header
            HeaderField::create('IOSPiniconHeader', 'iOS Pinned Icon ( a.k.a. Touch Icons, Web Clips )'),
            // information
            LabelField::create('IOSPiniconDescription', 'iPhone and iPad users can pin your web site on their home screen. The link looks like a native app.
@ Configuring Web Applications - iOS Developer Library')
                ->addExtraClass('information'),
            // icon
            UploadField::create('IOSPinicon', 'iOS Icon
type: png

size: 192x192 px
')
                ->setAllowedExtensions(array('png'))
                ->setFolderName(self::$SEOIconsUpload)
                ->setDescription('iOS will fill the transparent regions with black by default, so put your own background in!')
        ));

        //// Android Pinned Icon

        // CMS fields
        $fields->addFieldsToTab($tab, array(
            // header
            HeaderField::create('AndroidPiniconHeader', 'Android Pinned Icon ( a.k.a. Android Chrome Icons, Launcher Icons )'),
            // information
            LabelField::create('AndroidPiniconDescription', 'Add to Homescreen is a also a feature of Android Chrome. Your visitors can mix their natives apps and web bookmarks.
@ Add to Homescreen - Google Chrome')
                ->addExtraClass('information'),
            // icon
            UploadField::create('AndroidPinicon', 'Android Icon
type: png

size: 192x192 px
')
                ->setAllowedExtensions(array('png'))
                ->setFolderName(self::$SEOIconsUpload),
            // background
            TextField::create('AndroidPiniconThemeColor', 'Theme Color
type: hex triplet
')
                ->setAttribute('placeholder', 'none')
                ->setAttribute('size', 6)
                ->setMaxLength(6)
                ->setDescription('Starting with Android Lollipop, you can customize the color of the task bar in the switcher.')
        ));

        //// Windows Pinned Icon

        // CMS fields
        $fields->addFieldsToTab($tab, array(
            // header
            HeaderField::create('WindowsShortcutHeader', 'Windows Pinned Icon ( a.k.a. Windows 8 / Metro Tiles )'),
            // information
            LabelField::create('WindowsShortcutDescription', 'Windows 8 users can pin your web site on their desktop. Your site appears as a tile, just like a native Windows 8 app.
@ Creating custom tiles for IE11 websites (Windows)')
                ->addExtraClass('information'),
            // icon
            UploadField::create('WindowsPinicon', 'Windows Icon
type: png

size: 192x192 px
')
                ->setAllowedExtensions(array('png'))
                ->setFolderName(self::$SEOIconsUpload),
            // background
            TextField::create('WindowsPiniconBackgroundColor', 'Background ( Tile ) Color
type: hex triplet
')
                ->setAttribute('placeholder', 'none')
                ->setAttribute('size', 6)
                ->setMaxLength(6)
        ));

        // @todo Safari Pinned Tab ~ maybe ??

    }

    /**
     * Generates the Android manifest.json file.
     *
     * @todo Information about permissions
     *
     * @return void
     */
    public function onAfterWrite()
    {

        // parent
        parent::onAfterWrite();

        // @todo Add success & error states + messages
        $this->generateAndroidManifest();

    }

    /* Custom Methods
    ------------------------------------------------------------------------------*/

    //// Fetch functions

    /**
     * Fetches the pinicon title.
     *
     * @return bool|string
     */
    public function fetchPiniconTitle()
    {

        if ($this->owner->PiniconTitle) {
            // return pinicon title
            return $this->owner->PiniconTitle;
        } else {
            // default
            return false;
        }

    }

    /**
     * Fetches the Android pinicon theme color.
     *
     * @return string|false
     */
    public function fetchAndroidPiniconThemeColor()
    {

        if ($this->owner->AndroidPiniconThemeColor) {
            return '#' . $this->owner->AndroidPiniconThemeColor;
        } else {
            return false;
        }

    }

    /**
     * Fetches the Windows pinicon background color.
     *
     * @return string|false
     */
    public function fetchWindowsPiniconBackgroundColor()
    {

        if ($this->owner->WindowsPiniconBackgroundColor) {
            return '#' . $this->owner->WindowsPiniconBackgroundColor;
        } else {
            return false;
        }

    }

    //// Generate functions

    /**
     * Generates the android manifest
     *
     * @todo check this is working 100%
     *
     * @return bool
     */
    public function generateAndroidManifest()
    {

        //// Android Pinicon Manifest

        $pinicon = $this->owner->AndroidPinicon();

        if ($pinicon->exists()) {

            //
            $manifest = new stdClass();

            //
            $manifest->name = $this->owner->PiniconTitle;
//			$manifest->start_url = null; @todo Maybe implement
//			$manifest->display = null; @todo Maybe implement
//			$manifest->orientation = null; @todo Maybe implement
            $manifest->icons = array();

            // 0.75x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(36, 36)->getAbsoluteURL(),
                'sizes' => '36x36',
                'type' => 'image/png',
                'density' => 0.75
            ));

            // 1x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(48, 48)->getAbsoluteURL(),
                'sizes' => '48x48',
                'type' => 'image/png',
                'density' => 1
            ));

            // 1.5x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(72, 72)->getAbsoluteURL(),
                'sizes' => '72x72',
                'type' => 'image/png',
                'density' => 1.5
            ));

            // 2x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(96, 96)->getAbsoluteURL(),
                'sizes' => '96x96',
                'type' => 'image/png',
                'density' => 2
            ));

            // 3x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(144, 144)->getAbsoluteURL(),
                'sizes' => '144x144',
                'type' => 'image/png',
                'density' => 3
            ));

            // 4x density icon
            array_push($manifest->icons, array(
                'src' => $pinicon->Fill(192, 192)->getAbsoluteURL(),
                'sizes' => '192x192',
                'type' => 'image/png',
                'density' => 4
            ));

            // create file
            $bytes = file_put_contents(Director::baseFolder() . '/manifest.json', json_encode($manifest));

            //
            if ($bytes !== false) {
                // success
                return true;
            }

        }

        // default return
        return false;

    }

}


<?php
/**
 * This source file is part of Xloit project.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License that is bundled with this package in the file LICENSE.
 * It is also available through the world-wide-web at this URL:
 * <http://www.opensource.org/licenses/mit-license.php>
 * If you did not receive a copy of the license and are unable to obtain it through the world-wide-web,
 * please send an email to <license@xloit.com> so we can send you a copy immediately.
 *
 * @license   MIT
 * @link      http://xloit.com
 * @copyright Copyright (c) 2016, Xloit. All rights reserved.
 */

namespace Xloit\Bridge\Zend\Form\Element;

use Zend\Filter\Callback;
use Zend\Form\Element;
use Zend\Form\ElementPrepareAwareInterface;
use Zend\Form\FormInterface;

/**
 * A {@link RangeFilter} class.
 *
 * @package Xloit\Bridge\Zend\Form\Element
 */
class RangeFilter extends Element implements ElementPrepareAwareInterface
{
    /**
     * Input form element that contains values for start.
     *
     * @var Element\Number
     */
    protected $startElement;

    /**
     * Input form element that contains values for end.
     *
     * @var Element\Number
     */
    protected $endElement;

    /**
     * Seed attributes.
     *
     * @var array
     */
    protected $attributes = [
        'type' => 'rangefilter'
    ];

    /**
     * Constructor to prevent {@link RangeFilter} from being loaded more than once.
     *
     * @param string|null $name    Optional name for the element.
     * @param array       $options Optional options for the element.
     *
     * @throws \Zend\Form\Exception\InvalidArgumentException
     */
    public function __construct($name = null, $options = [])
    {
        $this->startElement = new Element\Number('start');
        $this->endElement   = new Element\Number('end');

        parent::__construct($name, $options);
    }

    /**
     *
     *
     * @param array|\Traversable $options
     *
     * @return $this
     * @throws \Zend\Form\Exception\InvalidArgumentException
     */
    public function setOptions($options)
    {
        parent::setOptions($options);

        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (isset($options['start_attributes'])) {
            $this->startElement->setAttributes($options['start_attributes']);
        }

        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (isset($options['end_attributes'])) {
            $this->endElement->setAttributes($options['end_attributes']);
        }

        return $this;
    }

    /**
     * Set the element value.
     *
     * @param mixed $value
     *
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        /** @noinspection NotOptimalIfConditionsInspection */
        if (is_array($value) && array_key_exists('start', $value) && array_key_exists('end', $value)) {
            $start = (float) $value['start'];
            $end   = (float) $value['end'];

            if ($start <= $end) {
                $this->startElement->setValue($start);
                $this->endElement->setValue($end);
            }
        }

        return $this;
    }

    /**
     *
     *
     * @return Element\Number
     */
    public function getStartElement()
    {
        return $this->startElement;
    }

    /**
     *
     *
     * @param Element\Number $startElement
     *
     * @return $this
     */
    public function setStartElement(Element\Number $startElement)
    {
        $this->startElement = $startElement;

        return $this;
    }

    /**
     *
     *
     * @return Element\Number
     */
    public function getEndElement()
    {
        return $this->endElement;
    }

    /**
     *
     *
     * @param Element\Number $endElement
     *
     * @return $this
     */
    public function setEndElement(Element\Number $endElement)
    {
        $this->endElement = $endElement;

        return $this;
    }

    /**
     *
     *
     * @return string
     */
    public function getValue()
    {
        return sprintf(
            '%s - %s', $this->startElement->getValue(), $this->endElement->getValue()
        );
    }

    /**
     * Prepare the form element (mostly used for rendering purposes).
     *
     * @param FormInterface $form
     *
     * @return void
     */
    public function prepareElement(FormInterface $form)
    {
        $name = $this->getName();

        $this->startElement->setName($name . '[start]');
        $this->endElement->setName($name . '[end]');
    }

    /**
     * Should return an array specification compatible with {@link Zend\InputFilter\Factory::createInput()}.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        return [
            'name'       => $this->getName(),
            'required'   => false,
            'filters'    => [
                [
                    'name'    => Callback::class,
                    'options' => [
                        'callback' => function($date) {
                            // Convert the date to a specific format
                            if (is_array($date)) {
                                $date = $date['start'] . ' - ' . $date['end'];
                            }

                            return $date;
                        }
                    ]
                ]
            ],
            'validators' => []
        ];
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Rendering\Toolbar;

use RedKiteCms\Plugin\PluginManager;

/**
 * Class ToolbarManager is the object assigned to render the block's editor toolbar
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Rendering\Toolbar
 */
class ToolbarManager
{
    /**
     * @type \RedKiteCms\Plugin\PluginManager
     */
    private $pluginManager;
    /**
     * @type \Twig_Environment
     */
    private $twig;

    /**
     * @param \RedKiteCms\Plugin\PluginManager $pluginManager
     * @param \Twig_Environment $twig
     */
    public function __construct(PluginManager $pluginManager, \Twig_Environment $twig)
    {
        $this->pluginManager = $pluginManager;
        $this->twig = $twig;
    }

    /**
     * Renders the toolbar
     *
     * @return string
     */
    public function render()
    {
        $plugins = $this->pluginManager->getBlockPlugins();

        $toolbar = array();
        $left[] = $this->twig->render("RedKiteCms/Resources/views/Editor/Toolbar/_toolbar_left_buttons.html.twig");
        $right[] = $this->twig->render("RedKiteCms/Resources/views/Editor/Toolbar/_toolbar_right_buttons.html.twig");
        foreach ($plugins as $plugin) {
            if (!$plugin->hasToolbar()) {
                continue;
            }

            $left[] = $this->addButtons($plugin, 'left');
            $right[] = $this->addButtons($plugin, 'right');
        }

        $toolbar["left"] = implode("\n", $left);
        $toolbar["right"] = implode("\n", $right);

        return $toolbar;
    }

    private function addButtons($plugin, $type)
    {
        $file = sprintf('/Resources/views/Editor/Toolbar/_toolbar_%s_buttons.html.twig', $type);
        $realFilepath = $plugin->getPluginDir() . $file;
        if (!is_file($realFilepath)) {
            return "";
        }

        return $this->twig->render($plugin->getName() . $file);
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Content\SlotsManager;

use Symfony\Component\Finder\Finder;

/**
 * Class SlotsManagerPage is the object assigned to cretae a slot repeated at page level
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Content\SlotsManager
 */
class SlotsManagerPage extends SlotsManager
{
    /**
     *{@inheritdoc}
     */
    public function addSlot($slotName, $blocks = array(), $username = null)
    {
        $pagesDir = $this->siteDir . '/pages/pages';
        $sitePages = $this->fetchPages($pagesDir);
        foreach ($sitePages as $pageName) {
            foreach ($this->siteInfo["languages"] as $languageName) {
                $pageDir = $pagesDir . '/' . $pageName . '/' . $languageName . '/' . $slotName;
                $this->generateSlot($pageDir, $blocks, $username);
            }
        }
    }

    private function fetchPages($dir)
    {
        $pages = array();
        $finder = new Finder();
        $folders = $finder->directories()->depth(0)->in($dir);
        foreach ($folders as $folder) {
            $pages[] = basename((string)$folder);
        }

        return $pages;
    }
}


<?php

namespace Dothiv\Bundle\ContentfulBundle\Client;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Collections\ArrayCollection;
use Dothiv\Bundle\ContentfulBundle\Exception\RuntimeException;

class CachingHttpClient implements HttpClientInterface
{
    /**
     * @var Cache
     */
    private $cache;

    /**
     * @param Cache  $cache
     * @param string $accessToken
     */
    public function __construct(Cache $cache, $accessToken)
    {
        $this->cache   = $cache;
        $this->headers = new ArrayCollection();
        $this->client  = new HttpClient($accessToken);
    }

    /**
     * {@inheritdoc}
     */
    public function get($uri)
    {
        $key = sha1($uri);
        if (!$this->cache->contains($key)) {
            $this->cache->save($key, '{"items": []}', 60);
            try {
                $body = $this->client->get($uri);
                $this->cache->save($key, $body, 0);
                $this->cache->save($key . '.header', json_encode($this->client->getHeaders()->toArray()), 0);
                $this->setEtag(null);
            } catch (RuntimeException $e) {
                $this->cache->delete($key);
                throw $e;
            }
        }
        $this->headers = new ArrayCollection((array)json_decode($this->cache->fetch($key . '.header')));
        return $this->cache->fetch($key);
    }

    /**
     * @param string $name
     *
     * @return string
     */
    function header($name)
    {
        return $this->headers->get($name);
    }

    /**
     * @param string $etag
     */
    function setEtag($etag)
    {
        $this->client->setEtag($etag);
    }

}


<?php

abstract class SDIS62_Model_Mapper_DbTable_Abstract implements SDIS62_Model_Mapper_Interface
{
    /**
     * La classe DbTable représentant la table mise en jeu dans ce mapper
     * @var Zend_Db_Table_Abstract|string
     */
    protected $dbTable;

    /**
     * Tableau mappant le nom des attributs de l'objet et les champs en base de données
     * Exemple array("attribut de l'entité" => "champs en base")
     * @var array
     */
    protected $map;

    /**
     * Définition de la classe DbTable à utiliser
     *
     * @param Zend_Db_Table_Abstract|string $dbTable
     * @return SDIS62_Model_Mapper_DbTable_Abstract Interface fluide
     * @throws Zend_Exception Si l'objet n'est pas une instance de Zend_Db_Table_Abstract
     */
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable))
        {
            $dbTable = new $dbTable();
        }

        if (!$dbTable instanceof Zend_Db_Table_Abstract)
        {
            throw new Zend_Exception("L'objet n'est pas une instance de type Zend_Db_Table_Abstract");
        }

        $this->dbTable = $dbTable;

        return $this;
    }

    /**
     * Récupération de la DbTable
     * Si la DbTable devant être retournée n'est pas du type Zend_Db_Table_Abstract, on la transforme automatiquement
     *
     * @return Zend_Db_Table_Abstract|null
     */
    public function getDbTable()
    {
        if (is_string($this->dbTable))
        {
            $this->setDbTable($this->dbTable);
        }

        return $this->dbTable;
    }

    /**
     * Définition du tableau de mappage des données
     *
     * @param array $map
     * @return SDIS62_Model_Mapper_DbTable_Abstract Interface fluide
     */
    public function setMap($map)
    {
        $this->map = $map;

        return $this;
    }

    /**
     * Récupération du tableau de mappage des données
     * Si la tableau de mappage est vide, on retourne un tableau vide
     *
     * @return array
     */
    public function getMap()
    {
        if ($this->map === null)
        {
            $this->setMap(array());
        }

        return $this->map;
    }

    /**
     * Récupération du tableau de mappage des données
     * Si la tableau de mappage est vide, on retourne un tableau vide
     *
     * @param array $data Tableau des données à préparer
     * @param boolean $dataFromDb Optionnel, Booléen : Si les données à préparer viennent de la base de données (et pas de l'entité)
     */
    public function mapData(array $data, $dataFromDb = false)
    {
        // On map les nom des champs entre base et entité
        $map = $dataFromDb ? array_flip($this->getMap()) : $this->getMap();

        foreach($data as $key => $value)
        {
            if(array_key_exists($key, $map))
            {
                $newkey = $map[$key];
                $oldkey = $key;

                $data[$newkey] = $data[$oldkey];
                unset($data[$oldkey]);
            }
        }

        // On enlève les données non présentes en base et on attribut les données par défaut au tableau
        if(!$dataFromDb)
        {
            $data = array_intersect_key($data, array_flip($this->getDbTable()->info(Zend_Db_Table_Abstract::COLS)));

            $cols = $this->getDbTable()->info(Zend_Db_Table_Abstract::METADATA);

            foreach($data as $key => $value)
            {
                if($value === null)
                {
                    if(array_key_exists($key, $cols) && $cols[$key]["DEFAULT"] !== null)
                    {
                        switch($cols[$key]["DEFAULT"])
                        {
                            case "CURRENT_TIMESTAMP":
                                $data[$key] = new Zend_Db_Expr('CURRENT_TIMESTAMP');
                                break;

                            default:
                                $data[$key] = $cols[$key]["DEFAULT"];
                        }
                    }
                }
            }
        }

        return $data;
    }

    /**
     * Récupération, construction, et envoi d'une entité correspondant à l'id donnée
     *
     * @param int $id
     * @return SDIS62_Model_Proxy_Abstract|null
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->find($id)->current();

        if(!$row)
        {
            return null;
        }

        $data = $row->toArray();

        return $this->createEntity($data);
    }

    /**
     * Récupération, construction, et envoi d'une entité correspondant aux critères spécifiés
     *
     * @param string|array $where Optionnel
     * @param string|array $order Optionnel
     * @param int $offset Optionnel
     * @return SDIS62_Model_Proxy_Abstract
     */
    public function fetchRow($where = null, $order = null, $offset = null)
    {
        $row = $this->getDbTable()->fetchRow($where, $order, $offset);

        if(!$row)
        {
            return null;
        }

        $data = $row->toArray();

        return $this->createEntity($data);
    }

    /**
     * Récupération, construction, et envoi d'une liste d'entités correspondants aux critères spécifiés
     *
     * @param string|array $where Optionnel
     * @param string|array $order Optionnel
     * @param int $count Optionnel
     * @param int $offset Optionnel
     * @return array
     */
    public function fetchAll($where = null, $order = null, $count = null, $offset = null)
    {
        $entities = array();
        $rows = $this->getDbTable()->fetchAll($where, $order, $count, $offset);

        if($rows)
        {
            foreach($rows as $row)
            {
                $data = $row->toArray();
                $entities[] = $this->createEntity($data);
            }
        }

        return $entities;
    }

    /**
     * On persiste les données de l'entité (sauvegarde)
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param SDIS62_Model_Proxy_Abstract $entity Paramètre passé en référence
     */
    abstract public function save(SDIS62_Model_Proxy_Abstract &$entity);

    /**
     * Suppression des données d'une entité identifiée
     *
     * @param int $id
     * @return boolean
     */
    public function delete($id)
    {
        try
        {
            $this->getDbTable()->find($id)->current()->delete();
            return true;
        }
        catch(Zend_Exception $e)
        {
            return false;
        }
    }

    /**
     * Construction et/ou hydratation de l'entité liée au mapper
     * L'implementation de cette fonction est déléguée aux mappers réels
     *
     * @param array $data
     * @return SDIS62_Model_Proxy_Abstract
     */
    abstract protected function createEntity(array $data);
}


<?php
namespace spec\Clusterpoint\Instance;

use Prophecy\Argument;
use PhpSpec\ObjectBehavior;
use Clusterpoint\Client;
use Clusterpoint\Testing\ConnectionFaker;

/**
 * Clusterpoint/Instance/Servuce Unit Testing.
 *
 */
class ServiceSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
    	$this->beConstructedWith(new ConnectionFaker);
        $this->shouldHaveType('Clusterpoint\Instance\Service');
    }

    function it_parses_implemented_classes()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $this->shouldImplement('Clusterpoint\Query\Builder');
    }

    function it_parses_where_field_only()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->where("name==\"Marks\"")->where("awesome==true")->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE name=="Marks" && awesome==true LIMIT 0, 20');
    }

    // Where
    function it_parses_where_clause_number()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where('age', 24)->get();
    	$response->executedQuery()->shouldReturn('SELECT * FROM database WHERE age==24 LIMIT 0, 20');
    }

    function it_parses_where_clause_string()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where("name", "Marks")->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE name=="Marks" LIMIT 0, 20');
    }

    function it_parses_or_where_clause_goes_first()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->orWhere("name", "Marks")->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE name=="Marks" LIMIT 0, 20');
    }

    function it_parses_where_clause_boolean()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where("awesome", true)->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE awesome==true LIMIT 0, 20');
    }

    function it_parses_where_clause_plus_or_where()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where("name","Marks")->orWhere("age", 24)->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE name=="Marks" || age==24 LIMIT 0, 20');
    }

    function it_parses_where_clause_with_closure()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where(function ($query) {
			$query->where('name', "Marks")
				->where('awesome', true);
        	})->orWhere("gender", "male")->orWhere(function ($query) {
			$query->where('income_per_month', '>', 6)
				->where("company", 'Clusterpoint');
    	})->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE ( name=="Marks" && awesome==true ) || gender=="male" || ( income_per_month>6 && company=="Clusterpoint" ) LIMIT 0, 20');
    }

    function it_parses_where_clause_with_zero()
    {
    	$this->beConstructedWith(new ConnectionFaker);
    	$response = $this->where("price", 0)->orWhere("amount","==", 0)->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database WHERE price==0 || amount==0 LIMIT 0, 20');
    }

    function it_parses_where_clause_with_CP_FIELD_and_RAW_and_prepend()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->prepend("function myFunc(age) { if (age>=18) { return true; } else { return false; } }")->where(Client::field("1==1"), true)->orWhere(Client::raw("myFunc(age)==true"))->get();
        $response->executedQuery()->shouldReturn('function myFunc(age) { if (age>=18) { return true; } else { return false; } } SELECT * FROM database WHERE this["1==1"]==true || myFunc(age)==true LIMIT 0, 20');
    }

    // Select
    function it_parses_select_by_text()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->select("name, age,status")->get();
        $response->executedQuery()->shouldReturn('SELECT name, age,status FROM database LIMIT 0, 20');
    }

    function it_parses_select_by_array()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->select(["name","age","status"])->get();
        $response->executedQuery()->shouldReturn('SELECT name, age, status FROM database LIMIT 0, 20');
    }

    function it_parses_select_by_CP_FIELD()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->select([Client::field("1==1"),"age","status"])->get();
        $response->executedQuery()->shouldReturn('SELECT this["1==1"] as "1==1", age, status FROM database LIMIT 0, 20');
    }

    // Order by
    function it_parses_order_by_1_param()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->orderBy("price")->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database ORDER BY price DESC LIMIT 0, 20');
    }

    function it_parses_order_by_2_param()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->orderBy("price","asc")->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database ORDER BY price ASC LIMIT 0, 20');
    }

    function it_parses_order_by_CP_FIELD()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->orderBy(Client::field("1==1"))->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database ORDER BY this["1==1"] DESC LIMIT 0, 20');
    }

    // Insert
    function it_parses_insert_one()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->insertOne(array("name" => "Marks", "surname"=>"Gerasimovs", "age"=>24));
        $response->executedQuery()->shouldReturn('{"name" : "Marks","surname" : "Gerasimovs","age" : 24}');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

    function it_parses_insert_many()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->insertMany(array("person_1" => array("name" => "Marks", "surname"=>"Gerasimovs", "age"=>24),"company1"=>array("name" => "Clusterpoint", "address"=>"Riga")));
        $response->executedQuery()->shouldReturn('[{"name":"Marks","surname":"Gerasimovs","age":24},{"name":"Clusterpoint","address":"Riga"}]');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

    // Update
    function it_parses_update_simple()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->update("_id", array("name" => "Marks"));
        $response->executedQuery()->shouldReturn('UPDATE database["_id"] SET name = "Marks"');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

    function it_parses_update_multilevel()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->update("_id", array("name" => array("first" => "Marks", "last" => "Gerasimovs")));
        $response->executedQuery()->shouldReturn('UPDATE database["_id"] SET (typeof name != "undefined") ? name["first"] = "Marks" : name = {"first":"Marks","last":"Gerasimovs"}, (typeof name != "undefined") ?  name["last"] = "Gerasimovs" : name = {"first":"Marks","last":"Gerasimovs"}');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

    // First
    function it_parses_first()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->first();
        $response->executedQuery()->shouldReturn('SELECT * FROM database LIMIT 0, 1');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
        $response->shouldImplement('\Clusterpoint\Contracts\ResponseInterface');
    }

    // Get
    function it_parses_get()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->get();
        $response->executedQuery()->shouldReturn('SELECT * FROM database LIMIT 0, 20');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Batch');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
        $response->shouldImplement('\Clusterpoint\Contracts\ResponseInterface');
    }

    // Replace
    function it_parses_replace()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->replace("_id", array("name" => "Marks", "surname"=>"Gerasimovs", "age"=>24));
        $response->executedQuery()->shouldReturn('{"name" : "Marks","surname" : "Gerasimovs","age" : 24}');
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

    //Delete
    function it_parses_delete()
    {
        $this->beConstructedWith(new ConnectionFaker);
        $response = $this->delete("_id");
        $response->shouldReturnAnInstanceOf('\Clusterpoint\Response\Single');
        $response->shouldBeAnInstanceOf('\Clusterpoint\Response\Response');
    }

}


<?php

/*
 * This file is part of the Сáша framework.
 *
 * (c) tchiotludo <http://github.com/tchiotludo>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types = 1);

namespace Cawa\Session\SessionStorage;

use Cawa\Net\Uri;

class RedisStorage extends AbstractStorage
{
    /**
     * @var Uri
     */
    private $config;

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

    /**
     * @var \Redis
     */
    protected $client;

    /**
     * @param string $config
     * @param string|null $prefix
     *
     * @internal param string $path
     */
    public function __construct(string $config, string $prefix = null)
    {
        $this->config = new Uri($config);
        $this->prefix = $prefix;
    }

    /**
     * @param string $key
     *
     * @return string
     */
    private function getKey(string $key) : string
    {
        return ($this->prefix ? $this->prefix . ':' : '') . $key;
    }

    /**
     * {@inheritdoc}
     */
    public function open() : bool
    {
        $this->client = new \Redis();
        $this->client->pconnect($this->config->getHost(), $this->config->getPort(), 2.5);

        return true;
    }

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

    /**
     * {@inheritdoc}
     */
    public function read(string $id)
    {
        if (!($content = $this->client->get($this->getKey($id)))) {
            return false;
        }

        $length = strlen($content);
        $saveData = self::unserialize($content);

        return [$saveData['data'], $saveData['startTime'], $saveData['accessTime'], $length];
    }

    /**
     * {@inheritdoc}
     */
    public function write(string $id, array $data, int $startTime, int $accessTime)
    {
        $saveData = [
            'startTime' => $startTime,
            'accessTime' => $accessTime,
            'data' => $data,
        ];

        $stringData = self::serialize($saveData);
        if ($this->client->setex($this->getKey($id), $this->getDuration(), $stringData)) {
            return false;
        } else {
            return strlen($stringData);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function destroy(string $id) : bool
    {
        return $this->client->del($this->getKey($id)) > 0;
    }

    /**
     * {@inheritdoc}
     */
    public function touch(string $id, array $data, int $startTime, int $accessTime)
    {
        return $this->write($id, $data, $startTime, $accessTime);
    }
}


<?php

namespace OpenOrchestra\ModelBundle\Repository;

use OpenOrchestra\ModelInterface\Model\ContentTypeInterface;
use OpenOrchestra\Pagination\Configuration\PaginateFinderConfiguration;
use OpenOrchestra\ModelInterface\Repository\ContentTypeRepositoryInterface;
use OpenOrchestra\Repository\AbstractAggregateRepository;
use Solution\MongoAggregation\Pipeline\Stage;

/**
 * Class ContentTypeRepository
 */
class ContentTypeRepository extends AbstractAggregateRepository implements ContentTypeRepositoryInterface
{
    /**
     * @param array $contentTypes
     *
     * @return array
     */
    public function findAllNotDeletedInLastVersion(array $contentTypes = array())
    {
        $qa = $this->createAggregationQuery();
        $qa->match(
            array(
                'deleted' => false
            )
        );
        if (!empty($contentTypes)) {
            $qa->match(
                array('contentTypeId' => array('$in' => $contentTypes))
            );
        }
        $elementName = 'contentType';
        $this->generateLastVersionFilter($qa, $elementName);

        return $this->hydrateAggregateQuery($qa, $elementName, 'getContentTypeId');
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return array
     */
    public function findAllNotDeletedInLastVersionForPaginate(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregateQueryNotDeletedInLastVersion();
        $filters = $this->getFilterSearch($configuration);
        if (!empty($filters)) {
            $qa->match($filters);
        }
        $elementName = 'contentType';
        $group = array(
            'names' => array('$last' => '$names'),
            'contentTypeId' => array('$last' => '$contentTypeId')
        );
        $this->generateLastVersionFilter($qa, $elementName, $group);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

        return $this->hydrateAggregateQuery($qa, $elementName, 'getContentTypeId');
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return int
     */
    public function countNotDeletedInLastVersionWithSearchFilter(PaginateFinderConfiguration $configuration)
    {
        $qa = $this->createAggregateQueryNotDeletedInLastVersion();
        $filters = $this->getFilterSearch($configuration);
        if (!empty($filters)) {
            $qa->match($filters);
        }
        $elementName = 'contentType';
        $this->generateLastVersionFilter($qa, $elementName);

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @return int
     */
    public function countByContentTypeInLastVersion()
    {
        $qa = $this->createAggregateQueryNotDeletedInLastVersion();
        $elementName = 'content';
        $this->generateLastVersionFilter($qa, $elementName);

        return $this->countDocumentAggregateQuery($qa);
    }

    /**
     * @param string   $contentType
     *
     * @return ContentTypeInterface
     */
    public function findOneByContentTypeIdInLastVersion($contentType)
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('contentTypeId' => $contentType));
        $qa->sort(array('updatedAt' => -1));

        return $this->singleHydrateAggregateQuery($qa);
    }

    /**
     * @param array $contentTypeIds
     *
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function removeByContentTypeId(array $contentTypeIds)
    {
        $qb = $this->createQueryBuilder();
        $qb->updateMany()
            ->field('contentTypeId')->in($contentTypeIds)
            ->field('deleted')->set(true)
            ->getQuery()
            ->execute();
    }

    /**
     * @param PaginateFinderConfiguration $configuration
     *
     * @return array
     */
    protected function getFilterSearch(PaginateFinderConfiguration $configuration) {
        $filter = array();
        $name = $configuration->getSearchIndex('name');
        $language = $configuration->getSearchIndex('language');
        if (null !== $name && $name !== '' && null !== $language && $language !== '' ) {
            $filter['names.' . $language] = new \MongoRegex('/.*'.$name.'.*/i');
        }

        $linkedToSite = $configuration->getSearchIndex('linkedToSite');
        if (null !== $linkedToSite && $linkedToSite !== '') {
            $filter['linkedToSite'] = (boolean) $linkedToSite;
        }

        $contentTypeId = $configuration->getSearchIndex('contentTypeId');
        if (null !== $contentTypeId && $contentTypeId !== '') {
            $filter['contentTypeId'] =new \MongoRegex('/.*'.$contentTypeId.'.*/i');
        }

        return $filter;
    }

    /**
     * @param Stage  $qa
     * @param string $elementName
     * @param string $elementName
     * @param array  $group
     */
    protected function generateLastVersionFilter(Stage $qa, $elementName, $group = array())
    {
        $group = array_merge($group, array(
                '_id' => array('contentTypeId' => '$contentTypeId'),
                $elementName => array('$last' => '$$ROOT')
        ));

        $qa->sort(array('updatedAt' => 1));
        $qa->group($group);
    }

    /**
     * @return \Solution\MongoAggregation\Pipeline\Stage
     */
    protected function createAggregateQueryNotDeletedInLastVersion()
    {
        $qa = $this->createAggregationQuery();
        $qa->match(array('deleted' => false));
        $qa->sort(array('contentTypeId' => -1));

        return $qa;
    }
}


<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\models;

use dektrium\user\Module;
use yii\base\Model;

/**
 * Registration form collects user input on registration process, validates it and creates new User model.
 *
 * @author Dmitry Erofeev <dmeroff@gmail.com>
 */
class RegistrationForm extends Model
{
    /** @var string */
    public $email;

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

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

    /** @var User */
    protected $user;

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

    /** @inheritdoc */
    public function init()
    {
        $this->user = \Yii::createObject([
            'class'    => User::className(),
            'scenario' => 'register'
        ]);
        $this->module = \Yii::$app->getModule('user');
    }

    /** @inheritdoc */
    public function rules()
    {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'match', 'pattern' => '/^[a-zA-Z]\w+$/'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => $this->module->modelMap['User'],
                'message' => \Yii::t('user', 'This username has already been taken')],
            ['username', 'string', 'min' => 3, 'max' => 20],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => $this->module->modelMap['User'],
                'message' => \Yii::t('user', 'This email address has already been taken')],

            ['password', 'required', 'skipOnEmpty' => $this->module->enableGeneratingPassword],
            ['password', 'string', 'min' => 6],
        ];
    }

    /** @inheritdoc */
    public function attributeLabels()
    {
        return [
            'email'    => \Yii::t('user', 'Email'),
            'username' => \Yii::t('user', 'Username'),
            'password' => \Yii::t('user', 'Password'),
        ];
    }

    /** @inheritdoc */
    public function formName()
    {
        return 'register-form';
    }

    /**
     * Registers a new user account.
     * @return bool
     */
    public function register()
    {
        if (!$this->validate()) {
            return false;
        }

        $this->user->setAttributes([
            'email'    => $this->email,
            'username' => $this->username,
            'password' => $this->password
        ]);

        return $this->user->register();
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\dataInterface\connectors\generic;

use cascade\components\dataInterface\connectors\generic\Model as GenericModel;
use cascade\models\KeyTranslation;
use cascade\models\Relation;
use Yii;

/**
 * DataSource [[@doctodo class_description:cascade\components\dataInterface\connectors\generic\DataSource]].
 *
 * @author Jacob Morrison <email@ofjacob.com>
 */
abstract class DataSource extends \cascade\components\dataInterface\DataSource
{
    /**
     * @inheritdoc
     */
    public $fieldMapClass = 'cascade\components\dataInterface\connectors\generic\FieldMap';
    /**
     * @inheritdoc
     */
    public $dataItemClass = 'cascade\components\dataInterface\connectors\generic\DataItem';
    /**
     * @inheritdoc
     */
    public $searchClass = 'cascade\components\dataInterface\connectors\generic\Search';

    /**
     * @var [[@doctodo var_type:keys]] [[@doctodo var_description:keys]]
     */
    public $keys = [];

    /**
     * @var [[@doctodo var_type:foreignParentKeys]] [[@doctodo var_description:foreignParentKeys]]
     */
    public $foreignParentKeys = [];
    /**
     * @var [[@doctodo var_type:foreignChildKeys]] [[@doctodo var_description:foreignChildKeys]]
     */
    public $foreignChildKeys = [];

    /**
     * @inheritdoc
     */
    public function init()
    {
        $this->on(self::EVENT_LOAD_FOREIGN_DATA_ITEMS, [$this, 'loadForeignDataItems']);
        $this->on(self::EVENT_LOAD_LOCAL_DATA_ITEMS, [$this, 'loadLocalDataItems']);

        return parent::init();
    }

    /**
     * Get foreign data item.
     *
     * @param [[@doctodo param_type:key]] $key [[@doctodo param_description:key]]
     *
     * @return [[@doctodo return_type:getForeignDataItem]] [[@doctodo return_description:getForeignDataItem]]
     */
    public function getForeignDataItem($key)
    {
        if (!isset($this->_foreignDataItems[$key])) {
            $this->createForeignDataItem(null, ['foreignPrimaryKey' => $key]);
        }
        if (isset($this->_foreignDataItems[$key])) {
            return $this->_foreignDataItems[$key];
        }

        return false;
    }

    /**
     * Get foreign data model.
     *
     * @param [[@doctodo param_type:key]] $key [[@doctodo param_description:key]]
     */
    abstract public function getForeignDataModel($key);

    /**
     * [[@doctodo method_description:updateLocalObject]].
     *
     * @param [[@doctodo param_type:relatedType]] $relatedType [[@doctodo param_description:relatedType]]
     * @param [[@doctodo param_type:valueMap]]    $valueMap    [[@doctodo param_description:valueMap]]
     * @param [[@doctodo param_type:fieldMap]]    $fieldMap    [[@doctodo param_description:fieldMap]]
     * @param [[@doctodo param_type:localModel]]  $localModel  [[@doctodo param_description:localModel]]
     *
     * @throws \Exception [[@doctodo exception_description:\Exception]]
     * @return [[@doctodo return_type:updateLocalObject]] [[@doctodo return_description:updateLocalObject]]
     *
     */
    public function updateLocalObject($relatedType, $valueMap, $fieldMap, $localModel)
    {
        $localModelClass = $relatedType->primaryModel;
        // @todo eventually we'll probably take some keys out of this
        $searchMap = $valueMap;
        if (isset($fieldMap->searchFields) && is_array($fieldMap->searchFields)) {
            foreach ($searchMap as $field => $value) {
                if (!in_array($field, $fieldMap->searchFields)) {
                    unset($searchMap[$field]);
                }
            }
        }
        $fieldParts = explode(':', $fieldMap->localField);
        if ($fieldParts[0] === 'child') {
            $currentRelationsFunction = 'child';
        } else {
            $currentRelationsFunction = 'parent';
        }
        // first, lets see if it exists
        $relatedObject = null;
        $currentRelation = false;
        if (!empty($localModel) && !$localModel->isNewRecord) {
            $test = $localModel->{$currentRelationsFunction}($relatedType->primaryModel, [], ['where' => $searchMap, 'disableAccessCheck' => 1]);
            if ($test) {
                $relatedObject = $test;
                $currentRelation = true;
            }
        }

        if (empty($relatedObject)) {
            $relatedClass = $relatedType->primaryModel;
            $relatedObject = new $relatedClass();
        }
        $relatedObject->auditDataInterface = $this->module->collectorItem->interfaceObject->primaryKey;
        $relatedObject->attributes = $valueMap;
        if ($relatedObject->save()) {
            return $relatedObject;
        } else {
            $errors = $relatedObject->errors;
            foreach ($fieldMap->mute as $mute) {
                unset($errors[$mute]);
            }
            if (!empty($errors)) {
                \d($relatedObject->attributes);
                \d($errors);
                exit;
            }

            return false;
        }
    }

    /**
     * [[@doctodo method_description:buildLocalAttributes]].
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignModel [[@doctodo param_description:foreignModel]]
     * @param [[@doctodo param_type:localModel]]                        $localModel   [[@doctodo param_description:localModel]] [optional]
     * @param [[@doctodo param_type:fieldsMap]]                         $fieldsMap    [[@doctodo param_description:fieldsMap]] [optional]
     *
     * @return [[@doctodo return_type:buildLocalAttributes]] [[@doctodo return_description:buildLocalAttributes]]
     */
    public function buildLocalAttributes(Model $foreignModel, $localModel = null, $fieldsMap = null)
    {
        $a = [];
        if (is_null($fieldsMap)) {
            $fieldsMap = $this->map;
        }
        foreach ($fieldsMap as $localKey => $fieldMap) {
            if ($localKey === $this->localPrimaryKeyName) {
                continue;
            }
            $value = $fieldMap->extractValue($this, $foreignModel);
            if ($fieldMap->testIgnore($value)) {
                continue;
            }
            $taxonomyId = null;
            if (isset($fieldMap->taxonomy) && isset($fieldMap->taxonomy['taxonomy_type'])) {
                $taxonomyTypeItem = Yii::$app->collectors['taxonomies']->getOne($fieldMap->taxonomy['taxonomy_type']);
                if (($taxonomyType = $taxonomyTypeItem->object) && isset($taxonomyType)) {
                    if (isset($fieldMap->taxonomy['taxonomy_system_id'])
                        && ($taxonomy = $taxonomyTypeItem->getTaxonomy($fieldMap->taxonomy['taxonomy_system_id']))
                        && (isset($taxonomy))
                    ) {
                        $taxonomyId = [$taxonomy->primaryKey];
                    }
                }
            }

            if (strpos($fieldMap->localField, ':') !== false) {
                // we're feeding the relations
                $relationKey = $value;
                $value = false;
                $fields = [];
                if (!empty($localModel)) {
                    $fields = $localModel->getFields();
                }
                if (!empty($relationKey)) {
                    $fieldParts = explode(':', $fieldMap->localField);
                    $checkField = $fieldParts;
                    $checkField[2] = '';
                    $checkField = implode(':', $checkField);
                    if (isset($fields[$checkField]) && !empty($fields[$checkField]->model->taxonomy_id)) {
                        $taxonomyId = $fields[$checkField]->model->taxonomy_id;
                    }

                    if ($fieldParts[0] === 'child') {
                        $relationship = $this->dummyLocalModel->objectTypeItem->getChild($fieldParts[1]);
                        $relatedType = !empty($relationship) ? $relationship->child : false;
                        $currentRelationsFunction = 'child';
                    } else {
                        $relationship = $this->dummyLocalModel->objectTypeItem->getParent($fieldParts[1]);
                        $relatedType = !empty($relationship) ? $relationship->parent : false;
                        $currentRelationsFunction = 'parent';
                    }
                    if (!$relatedType) {
                        continue;
                    }

                    $relatedObject = null;
                    if (!isset($a['relationModels'])) {
                        $a['relationModels'] = [];
                    }
                    $fieldKey = $fieldParts[0] . '_object_id';
                    if (empty($fieldParts[2]) && (!is_array($relationKey) || isset($relationKey[0]))) {
                        if (!is_array($relationKey)) {
                            $relationKey = [$relationKey];
                        }
                        foreach ($relationKey as $subkey) {
                            // we're just matching to an existing object's primary key
                            if (($relatedObject = $this->module->getLocalObject($relatedType->primaryModel, $subkey)) && is_object($relatedObject)) {
                                $relation = [$fieldKey => $relatedObject->primaryKey];
                                if (isset($taxonomyId)) {
                                    $relation['taxonomy_id'] = $taxonomyId;
                                    $taxonomyId = null;
                                }
                                $a['relationModels'][] = $relation;
                            }
                        }
                    } else {
                        $valueMap = [];
                        // we're creating or updating an existing related object's field
                        if (is_array($relationKey)) {
                            // the localRelatedField is a dummy; build/search for object using this hash
                            $valueMap = $relationKey;
                        } elseif (isset($fieldParts[2])) {
                            $localRelatedField = $fieldParts[2];
                            $valueMap = [$localRelatedField => $relationKey];
                        }
                        if (($relatedObject = $this->updateLocalObject($relatedType, $valueMap, $fieldMap, $localModel)) && is_object($relatedObject)) {
                            $relation = [$fieldKey => $relatedObject->primaryKey];
                            if (isset($taxonomyId)) {
                                $relation['taxonomy_id'] = $taxonomyId;
                                $taxonomyId = null;
                            }
                            $a['relationModels'][] = $relation;
                        }
                    }
                }
            } elseif (!empty($fieldMap->foreignModel)) {
                $relationKey = $value;
                $value = false;
                if (!empty($relationKey)) {
                    // we're filling a local related _id field with another foreign object
                    if (($relatedObject = $this->module->getForeignObject($fieldMap->foreignModel, $relationKey)) && is_object($relatedObject)) {
                        $value = $relatedObject->primaryKey;
                    }
                }
            }
            if ($value !== false) {
                $a[$fieldMap->localField] = $value;
            }
        }

        return $a;
    }

    /**
     * Get unmapped keys.
     *
     * @return [[@doctodo return_type:getUnmappedKeys]] [[@doctodo return_description:getUnmappedKeys]]
     */
    public function getUnmappedKeys()
    {
        $u = [];
        $f = $this->unmappedForeignKeys;
        $l = $this->unmappedLocalKeys;
        if (!empty($f)) {
            $u['foreign'] = $f;
        }
        if (!empty($l)) {
            $u['local'] = $l;
        }

        return $u;
    }

    /**
     * Get unmapped local keys.
     *
     * @return [[@doctodo return_type:getUnmappedLocalKeys]] [[@doctodo return_description:getUnmappedLocalKeys]]
     */
    public function getUnmappedLocalKeys()
    {
        $u = array_diff(array_keys($this->localModel->getMetaData()->columns), array_keys($this->_map));
        unset($u[$this->localPrimaryKeyName]);

        return $u;
    }

    /**
     * Get unmapped foreign keys.
     *
     * @return [[@doctodo return_type:getUnmappedForeignKeys]] [[@doctodo return_description:getUnmappedForeignKeys]]
     */
    public function getUnmappedForeignKeys()
    {
        return [];
    }

    /**
     * Get local primary key name.
     *
     * @return [[@doctodo return_type:getLocalPrimaryKeyName]] [[@doctodo return_description:getLocalPrimaryKeyName]]
     */
    public function getLocalPrimaryKeyName()
    {
        return $this->dummyLocalModel->tableSchema->primaryKey;
    }

    /**
     * Get foreign primary key name.
     *
     * @return [[@doctodo return_type:getForeignPrimaryKeyName]] [[@doctodo return_description:getForeignPrimaryKeyName]]
     */
    public function getForeignPrimaryKeyName()
    {
        return $this->foreignModel->primaryKey();
    }

    /**
     * [[@doctodo method_description:isRelationKey]].
     *
     * @param [[@doctodo param_type:key]] $key [[@doctodo param_description:key]]
     *
     * @return [[@doctodo return_type:isRelationKey]] [[@doctodo return_description:isRelationKey]]
     */
    public function isRelationKey($key)
    {
        return substr($key, -3) === '_id';
    }

    /**
     * [[@doctodo method_description:generateKey]].
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignObject [[@doctodo param_description:foreignObject]]
     * @param [[@doctodo param_type:keyName]]                           $keyName       [[@doctodo param_description:keyName]]
     * @param [[@doctodo param_type:keyValue]]                          $keyValue      [[@doctodo param_description:keyValue]]
     *
     * @return [[@doctodo return_type:generateKey]] [[@doctodo return_description:generateKey]]
     */
    public function generateKey(GenericModel $foreignObject, $keyName, $keyValue)
    {
        if (is_null($this->keyGenerator)) {
            $self = $this;
            $this->keyGenerator = function ($foreignModel, $keyName, $keyValue) use ($self) {
                return [$self->module->systemId, $foreignModel->tableName, $keyName, $keyValue];
            };
        }
        $keyGen = $this->keyGenerator;
        $return = $keyGen($foreignObject, $keyName, $keyValue);

        if (isset($return)) {
            if (!is_array($return)) {
                $return = [$return];
            }
            $return = implode('.', $return);

            return $return;
        }

        return;
    }
    /**
     * Get key translation.
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignObject [[@doctodo param_description:foreignObject]]
     * @param [[@doctodo param_type:key]]                               $key           [[@doctodo param_description:key]] [optional]
     *
     * @return [[@doctodo return_type:getKeyTranslation]] [[@doctodo return_description:getKeyTranslation]]
     */
    public function getKeyTranslation(Model $foreignObject, $key = null)
    {
        if (isset($key)) {
            return $this->internalGetKeyTranslation($foreignObject, $key);
        }

        foreach ($this->keys as $keyName => $keyField) {
            if (!empty($foreignObject->{$keyField})) {
                $key = $this->generateKey($foreignObject, $keyName, $foreignObject->{$keyField});
                $result = $this->internalGetKeyTranslation($foreignObject, $key);
                if (!empty($result)) {
                    return $result;
                }
            }
        }

        return false;
    }

    /**
     * [[@doctodo method_description:internalGetKeyTranslation]].
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignObject [[@doctodo param_description:foreignObject]]
     * @param [[@doctodo param_type:key]]                               $key           [[@doctodo param_description:key]]
     *
     * @return [[@doctodo return_type:internalGetKeyTranslation]] [[@doctodo return_description:internalGetKeyTranslation]]
     */
    protected function internalGetKeyTranslation(Model $foreignObject, $key)
    {
        if ($this->settings['universalKey']) {
            return KeyTranslation::findOne(['key' => $key]);
        } else {
            return KeyTranslation::findOne(['key' => $key, 'data_interface_id' => $this->module->collectorItem->interfaceObject->primaryKey]);
        }
    }

    /**
     * Get reverse key translation.
     *
     * @param [[@doctodo param_type:localObject]] $localObject [[@doctodo param_description:localObject]]
     *
     * @return [[@doctodo return_type:getReverseKeyTranslation]] [[@doctodo return_description:getReverseKeyTranslation]]
     */
    public function getReverseKeyTranslation($localObject)
    {
        $key = is_object($localObject) ? $localObject->primaryKey : $localObject;
        if ($this->settings['universalKey']) {
            //return KeyTranslation::findOne(['registry_id' => $key]);
            return KeyTranslation::find()->where(['registry_id' => $key])->one();
        } else {
            //return KeyTranslation::findOne(['registry_id' => $key, 'data_interface_id' => $this->module->collectorItem->interfaceObject->primaryKey]);
            return KeyTranslation::find()->where(['registry_id' => $key, 'data_interface_id' => $this->module->collectorItem->interfaceObject->primaryKey])->one();
        }
    }

    /**
     * [[@doctodo method_description:saveKeyTranslation]].
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignObject [[@doctodo param_description:foreignObject]]
     * @param [[@doctodo param_type:localObject]]                       $localObject   [[@doctodo param_description:localObject]]
     *
     * @return [[@doctodo return_type:saveKeyTranslation]] [[@doctodo return_description:saveKeyTranslation]]
     */
    public function saveKeyTranslation(Model $foreignObject, $localObject)
    {
        $firstKey = null;
        foreach ($this->keys as $keyName => $keyField) {
            if (!empty($foreignObject->{$keyField})) {
                $key = $this->generateKey($foreignObject, $keyName, $foreignObject->{$keyField});
                $keySaved = $this->internalSaveKeyTranslation($foreignObject, $localObject, $key);
                if (!isset($firstKey)) {
                    $firstKey = $keySaved;
                }
            }
        }

        return $firstKey;
    }

    /**
     * [[@doctodo method_description:internalSaveKeyTranslation]].
     *
     * @param cascade\components\dataInterface\connectors\generic\Model $foreignModel [[@doctodo param_description:foreignModel]]
     * @param [[@doctodo param_type:localObject]]                       $localObject  [[@doctodo param_description:localObject]]
     * @param [[@doctodo param_type:key]]                               $key          [[@doctodo param_description:key]]
     *
     * @return [[@doctodo return_type:internalSaveKeyTranslation]] [[@doctodo return_description:internalSaveKeyTranslation]]
     */
    public function internalSaveKeyTranslation(Model $foreignModel, $localObject, $key)
    {
        $keyTranslation = $this->getKeyTranslation($foreignModel, $key);
        if (!$keyTranslation) {
            $keyTranslation = new KeyTranslation();
            $keyTranslation->data_interface_id = $this->module->collectorItem->interfaceObject->primaryKey;
            $keyTranslation->registry_id = $localObject->primaryKey;
            $keyTranslation->key = $key;
            if (!$keyTranslation->save()) {
                \d($keyTranslation->attributes);
                \d($keyTranslation->errors);
                exit;

                return false;
            }
        }

        return $keyTranslation;
    }
    /**
     * [[@doctodo method_description:loadForeignDataItems]].
     *
     * @return [[@doctodo return_type:loadForeignDataItems]] [[@doctodo return_description:loadForeignDataItems]]
     */
    protected function loadForeignDataItems()
    {
        return true;
    }

    /**
     * [[@doctodo method_description:createForeignDataItem]].
     *
     * @param [[@doctodo param_type:model]] $model  [[@doctodo param_description:model]]
     * @param array                         $config [[@doctodo param_description:config]] [optional]
     *
     * @return [[@doctodo return_type:createForeignDataItem]] [[@doctodo return_description:createForeignDataItem]]
     */
    public function createForeignDataItem($model, $config = [])
    {
        $config['isForeign'] = true;
        $config['foreignObject'] = $model;
        if (isset($model)) {
            $model->interface = $this->module;
        }
        $object = $this->createDataItem($config);

        return $this->_foreignDataItems[$object->id] = $object;
    }

    /**
     * [[@doctodo method_description:createLocalDataItem]].
     *
     * @param [[@doctodo param_type:model]] $model  [[@doctodo param_description:model]]
     * @param array                         $config [[@doctodo param_description:config]] [optional]
     *
     * @return [[@doctodo return_type:createLocalDataItem]] [[@doctodo return_description:createLocalDataItem]]
     */
    public function createLocalDataItem($model, $config = [])
    {
        $config['isForeign'] = false;
        $config['localObject'] = $model;

        return $this->createDataItem($config);
    }

    /**
     * [[@doctodo method_description:createDataItem]].
     *
     * @param array $config [[@doctodo param_description:config]] [optional]
     *
     * @return [[@doctodo return_type:createDataItem]] [[@doctodo return_description:createDataItem]]
     */
    protected function createDataItem($config = [])
    {
        if (!isset($config['class'])) {
            $config['class'] = $this->dataItemClass;
        }
        $config['dataSource'] = $this;

        return Yii::createObject($config);
    }

    /**
     * [[@doctodo method_description:loadLocalDataItems]].
     */
    protected function loadLocalDataItems()
    {
        $this->_localDataItems = [];
    }

    /**
     * Get module.
     *
     * @return [[@doctodo return_type:getModule]] [[@doctodo return_description:getModule]]
     */
    public function getModule()
    {
        return $this->dataSource->module;
    }
}


<?php
/**
 * This file is part of the RedKite CMS Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <info@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

namespace RedKiteCms\Bridge\Routing;

use RedKiteCms\Bridge\Routing\RoutingBackend;
use RedKiteCms\Bridge\Routing\RoutingFrontend;
use RedKiteCms\Configuration\ConfigurationHandler;

/**
 * This object defines the base class to instantiate a new routing environment
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package RedKiteCms\Bridge\Routing
 */
class Routing
{
    /**
     * @type null|\RedKiteCms\Bridge\Routing\RoutingBase
     */
    protected static $routing = null;

    /**
     * @return null|RoutingBase
     */
    public static function getRouting()
    {
        return self::$routing;
    }

    /**
     * @param \RedKiteCms\Configuration\ConfigurationHandler $configurationHandler
     * @param bool $debug
     *
     * @return null|\RedKiteCms\Bridge\Routing\RoutingBase
     */
    public static function create(ConfigurationHandler $configurationHandler, $debug = false)
    {
        if (null === self::$routing) {
            self::$routing = self::initRouter($configurationHandler);
            self::$routing->createRouter($debug);
        }

        return self::$routing;
    }

    private static function initRouter(ConfigurationHandler $configurationHandler)
    {
        if ($configurationHandler->isProduction()) {

            return new RoutingFrontend($configurationHandler);
        }

        return new RoutingBackend($configurationHandler);
    }
}


<?php
/**
 * @link http://psesd.org/
 *
 * @copyright Copyright (c) 2015 Puget Sound ESD
 * @license http://psesd.org/license/
 */

namespace cascade\components\web\widgets\base;

use canis\helpers\ArrayHelper;
use canis\helpers\Html;
use canis\web\bootstrap\ButtonDropdown;
use canis\web\grid\Cell;
use canis\web\grid\Row;

trait ListWidgetTrait
{
    public $renderPager = true;
    public $emptyMessage = 'No items exist.';
    public $defaultContentRow = [
        'class' => 'list-group-item-text',
        'tag' => 'div',
    ];
    protected $_renderContentTemplate;
    protected $_context;

    public function contentTemplate($model)
    {
        if ($model->objectType->hasDashboard && $model->can('read')) {
            return [
                'viewLink' => ['class' => 'list-group-item-heading', 'tag' => 'h5'],
                'subdescriptor' => ['class' => 'list-group-item-text ic-object-subheader'],
            ];
        } else {
            return [
                'descriptor' => ['class' => 'list-group-item-heading', 'tag' => 'h5'],
                'subdescriptor' => ['class' => 'list-group-item-text ic-object-subheader'],
            ];
        }
    }

    public function buildContext($object = null)
    {
        $context = [];

        return $context;
    }

    public function getContext($object = null)
    {
        if (!isset($this->_context)) {
            $this->_context = $this->buildContext($object);
        }

        return $this->_context;
    }

    public function getItemFieldValue($model, $fieldName, $settings = [])
    {
        if (is_array($fieldName)) {
            foreach ($fieldName as $fName => $fSettings) {
                if (is_numeric($fName)) {
                    $fName = $fSettings;
                    $fSettings = [];
                }
                $aSettings = array_merge($settings, $fSettings);
                $value = $this->getItemFieldValue($model, $fName, $aSettings);
                if (!empty($value)) {
                    return $value;
                }
            }

            return;
        }
        $settings = array_merge($this->defaultContentRow, $settings);
        $context = $this->getContext($model);

        $fieldOptions = isset($settings['fieldOptions']) ? $settings['fieldOptions'] : [];
        switch ($fieldName) {
            case 'subdescriptor':
                $functionName = 'get' . ucfirst($fieldName);
                $value = $model->{$functionName}($context);
            break;
            default:
                $value = $model->getFieldValue($fieldName, $fieldOptions, $context);
            break;
        }
        $depth = 3;
        while ($depth > 0 && is_array($value)) {
            $depth--;
            if (isset($value['rich'])) {
                $value = $value['rich'];
            } else {
                $value = array_shift($value);
            }
        }
        if (!empty($value)) {
            return $value;
        }

        return;
    }

    public function renderItemContent($model, $key, $index)
    {
        $template = $this->contentTemplate($model);
        $parts = [];
        if (isset($model->relationModel) && isset($model->relationModel['id'])) {
            // $parts[] = $model->relationModel['id'];
            $template = array_merge($template, [
                    'relationTaxonomies' => ['class' => 'list-group-item-post', 'tag' => 'div'],
                ]);
        }
        foreach ($template as $fieldName => $settings) {
            if (is_numeric($fieldName)) {
                $fieldName = $settings;
                $settings = [];
            }
            if (is_array($fieldName)) {
                $subparts = [];
                $subrowSettings = [];
                if (isset($fieldName['settings'])) {
                    $subrowSettings = $fieldName['settings'];
                }
                foreach ($fieldName as $subFieldName => $subSettings) {
                    if ($fieldName === 'settings') {
                        continue;
                    }
                    if (is_numeric($subFieldName)) {
                        $subFieldName = $subSettings;
                        $subSettings = [];
                    }
                    $this->renderItemContentRow($subparts, $subFieldName, $subSettings, $model, $key, $index);
                }
                if (!empty($subparts)) {
                    $row = new Row();
                    $columnSize = floor(12 / count($subparts));
                    foreach ($subparts as $subpart) {
                        $cell = new Cell(['content' => $subpart, 'phoneColumns' => $columnSize, 'phoneSize' => 'auto', 'tabletSize' => false, 'mediumDesktopSize' => false, 'largeDesktopSize' => false]);
                        $row->addCell($cell);
                    }
                    Html::addCssClass($subrowSettings, 'list-group-item-split');
                    $parts[] = Html::tag('div', $row->generate(), $subrowSettings);
                }
            } else {
                $this->renderItemContentRow($parts, $fieldName, $settings, $model, $key, $index);
            }
        }

        return implode("", $parts);
    }

    protected function renderItemContentRow(&$parts, $fieldName, $settings, $model, $key, $index)
    {
        $tag = isset($settings['tag']) ? $settings['tag'] : 'div';
        unset($settings['tag']);
        if (is_callable($fieldName)) {
            $value = call_user_func_array($fieldName, [$this, $model, $settings]);
        } else {
            $value = $this->getItemFieldValue($model, $fieldName, $settings);
        }
        if (!empty($value)) {
            $parts[] = Html::tag($tag, $value, $settings);
        }
    }

    public function getListOptions()
    {
        return ['class' => 'list-group'];
    }

    public function getListItemOptions($model, $key, $index)
    {
        return ['class' => 'list-group-item expandable'];
    }

    public function renderItem($model, $key, $index)
    {
        $listItemOptions = $this->getListItemOptions($model, $key, $index);
        $listTag = ArrayHelper::remove($listItemOptions, 'tag', 'li');

        $parts = [];
        $parts[] = $this->renderItemMenu($model, $key, $index);
        $parts[] = $this->renderItemContent($model, $key, $index);

        return Html::tag($listTag, implode('', $parts), $listItemOptions);
    }

    public function renderItemMenu($model, $key, $index)
    {
        $menuItems = $this->getMenuItems($model, $key, $index);
        if (!empty($menuItems)) {
            foreach ($menuItems as &$menuItem) {
                if (isset($menuItem['icon'])) {
                    if (!isset($menuItem['label'])) {
                        $menuItem['label'] = '';
                    }
                    $menuItem['label'] = '' . $menuItem['label'];
                    unset($menuItem['icon']);
                }
            }

            return ButtonDropdown::widget([
                    'label' => '',
                    'containerOptions' => ['class' => 'pull-right condensed-menu'],
                    'encodeLabel' => false,
                    'dropdown' => [
                        'options' => ['class' => 'pull-right'],
                        'encodeLabels' => false,
                        'items' => $menuItems,
                    ],
                    'iconOptions' => ['class' => 'fa fa-angle-down'],
                ]);
        }

        return;
    }

    public function generateContent()
    {
        if ($this->lazy && !empty($this->dataProvider->totalCount)) {
            return str_repeat(Html::tag('div', '', ['class' => 'widget-lazy-placeholder']), min($this->dataProvider->totalCount, $this->dataProvider->pagination->pageSize));
        }
        $results = $this->dataProvider;
        if (!empty($results->totalCount) && !empty($results->count)) {
            $models = $this->dataProvider->getModels();
            $keys = $this->dataProvider->getKeys();

            $listOptions = $this->listOptions;
            $listTag = ArrayHelper::remove($listOptions, 'tag', 'ul');

            $rows = [];
            $rows[] = Html::beginTag($listTag, $listOptions);
            foreach (array_values($models) as $index => $model) {
                $rows[] = $this->renderItem($model, $keys[$index], $index);
            }
            $rows[] = Html::endTag($listTag);

            return implode('', $rows);
        } else {
            return Html::tag('div', $this->emptyMessage, ['class' => 'empty-messages']);
        }
    }

    public function generateFooter()
    {
        $footer = '';
        if ($this->renderPager) {
            $pager = $this->renderPager();
            if ($pager) {
                $footer = Html::tag('div', $pager, ['class' => 'panel-footer clearfix']);
            }
        }

        return parent::generateFooter() . $footer;
    }

    /**
     * Renders the pager.
     *
     * @return string the rendering result
     */
    public function renderPager()
    {
        $pagination = $this->dataProvider->getPagination();
        //\d([get_class($this), $pagination]);
        if ($pagination === false || $pagination->getPageCount() <= 1) {
            return false;
        }
        /* @var LinkPager $class */
        $pager = $this->pagerSettings;
        $class = ArrayHelper::remove($pager, 'class', 'canis\widgets\LinkPager');
        $pager['pagination'] = $pagination;
        if (!isset($pager['options'])) {
            $pager['options'] = [];
        }
        $pager['maxButtonCount'] = 6;
        Html::addCssClass($pager['options'], 'pagination pull-right');

        return $class::widget($pager);
    }
}