<?php

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 LinguaLeo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace LinguaLeo\Cache\Decorator;

use LinguaLeo\Cache\CacheInterface;

class HotCacheDecorator implements CacheInterface
{
    /**
     * @var \LinguaLeo\Cache\CacheInterface
     */
    protected $cache;

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

    /**
     * @param CacheInterface $cache
     * @param bool $isCliRestricted
     * @throws \RuntimeException
     */
    public function __construct(CacheInterface $cache, $isCliRestricted = true)
    {
        $this->cache = $cache;
        if (PHP_SAPI === 'cli' && $isCliRestricted) {
            throw new \RuntimeException('Hot cache is not allowed to use in CLI mode.');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function get($key)
    {
        if (isset($this->hot[$key])) {
            return $this->hot[$key];
        }
        return $this->hot[$key] = $this->cache->get($key);
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $data, $ttl = 0)
    {
        $result = $this->cache->set($key, $data, $ttl);
        if ($result) {
            $this->hot[$key] = $data;
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function create($key, callable $modifier, $ttl = 0)
    {
        $data = $this->cache->create($key, $modifier, $ttl);
        if ($data) {
            $this->hot[$key] = $data;
        }
        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function update($key, callable $modifier, $ttl = 0)
    {
        $data = $this->cache->update($key, $modifier, $ttl);
        if ($data) {
            $this->hot[$key] = $data;
        }
        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        unset($this->hot[$key]);
        return $this->cache->delete($key);
    }

    /**
     * {@inheritdoc}
     */
    public function mdelete(array $keys)
    {
        foreach ($keys as $k) {
            unset($this->hot[$k]);
        }
        return $this->cache->mdelete($keys);
    }

    /**
     * {@inheritdoc}
     */
    public function increment($key, $value = 1)
    {
        $newValue = $this->cache->increment($key, $value);
        $this->hot[$key] = $newValue;
        return $newValue;
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        $this->hot = [];
        return $this->cache->flush();
    }

    /**
     * Flush only hot-cache
     */
    public function flushHot()
    {
        $this->hot = [];
    }

    /**
     * {@inheritdoc}
     */
    public function mget(array $keys)
    {
        $result = [];
        foreach ($keys as $index => $key) {
            if (!isset($this->hot[$key])) {
                continue;
            }
            $result[$key] = $this->hot[$key];
            unset($keys[$index]);
        }
        if (count($keys) > 0) {
            $cacheResult = $this->cache->mget(array_values($keys));
            foreach ($cacheResult as $key => $value) {
                $result[$key] = $this->hot[$key] = $value;
            }
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function mset(array $data, $ttl = 0)
    {
        $result = $this->cache->mset($data, $ttl);
        if ($result) {
            foreach ($data as $key => $value) {
                $this->hot[$key] = $value;
            }
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function add($key, $data, $ttl = 0)
    {
        $result = $this->cache->add($key, $data, $ttl);
        if ($result) {
            $this->hot[$key] = $data;
        }
        return $result;
    }
}


<?php

namespace Modules\Setting\Repositories;

use Modules\Setting\Models\Setting;
use Netcore\Translator\Helpers\TransHelper;

class SettingRepository
{
    /**
     * @var mixed
     */
    protected $cachedSettings;

    /**
     * @var \Illuminate\Config\Repository|mixed
     */
    protected $cacheKey;

    /**
     * SettingRepository constructor.
     */
    public function __construct()
    {
        $this->cacheKey = config('setting.cache_key', 'settings');
        $this->cachedSettings = cache()->rememberForever($this->cacheKey, function () {
            return Setting::all()->keyBy('key');
        });
    }

    /**
     * Get specified setting/s
     *
     * @param array|string $keys
     * @param array|null   $default
     * @return array|string
     */
    public function get($keys, $default = null)
    {
        $settings = $this->cachedSettings;

        if (is_array($keys)) {
            $array = [];
            foreach ($keys as $index => $key) {
                $setting = $settings->get($key);
                $array[$key] = $setting ? $setting->getValue() : (is_array($default) ? (isset($default[$index]) ? $default[$index] : null) : $default);
            }

            return $array;
        }

        $setting = $settings->get($keys);

        return $setting ? $setting->getValue() : (is_array($default) ? (isset($default[0]) ? $default[0] : null) : $default);
    }

    /**
     * Get all settings
     *
     * @return array
     */
    public function all(): array
    {
        return $this->cachedSettings->pluck('value', 'key')->toArray();
    }

    /**
     * Get grouped settings
     *
     * @return array
     */
    public function grouped()
    {
        return $this->cachedSettings->groupBy('group');
    }

    /**
     * Seed settings
     *
     * @param $data
     * @return void
     * @throws \Exception
     */
    public function seed($data)
    {
        if (!is_array($data)) {
            throw new \Exception('Passed settings should be an array');
        }

        foreach ($data as $item) {
            if (!isset($item['group'])) {
                throw new \Exception('Group does not exist for key: ' . $item['key']);
            }

            $item['key'] = implode('.', [
                $item['group'],
                $item['key']
            ]);

            $translations = [];
            if (isset($item['value']) && is_array($item['value'])) {
                foreach ($item['value'] as $locale => $value) {
                    $translations[$locale] = [
                        'value' => $value
                    ];
                }
            } else {
                foreach (TransHelper::getAllLanguages() as $language) {
                    $translations[$language->iso_code] = [
                        'value' => isset($item['value']) ? $item['value'] : '',
                    ];
                }
            }

            $setting = Setting::firstOrCreate([
                'key' => $item['key']
            ], array_except($item, 'value'));

            $setting->updateTranslations($translations);
        }
    }

    /**
     * Clear cache
     *
     * @return bool
     * @throws \Exception
     */
    public function clear_cache(): bool
    {
        return cache()->forget($this->cacheKey);
    }
}


<?php

namespace Wuunder\Api\Config;

abstract class Config implements \JsonSerializable
{

    protected $defaultFields;
    protected $requiredFields;
    protected $setFields;

    protected static $_underscoreCache = [];

    public function __construct()
    {
        $this->defaultFields = array();
        $this->setFields = array();
    }

    public function __call($method, $args)
    {
        switch (substr($method, 0, 3)) {
            case 'set' :
                $key = $this->_underscore(substr($method, 3));
                $this->setFields[$key] = isset($args[0]) ? $args[0] : null;
                break;
            case 'get' :
                $key = $this->_underscore(substr($method, 3));
                return isset($this->setFields[$key]) ? $this->setFields[$key] : null;
                break;
        }
    }

    /**
    * Adds together default and user input items
    *
    * @return array A full list of all the items that are set by user and default
    */
    public function jsonSerialize()
    {
        return array_merge($this->defaultFields, $this->setFields);
    }

    /**
    * Validates the user input data
    *
    * @return bool
    */
    public function validate()
    {
        $resultingData = array_merge($this->defaultFields, $this->setFields);
        return $this->_arrayKeysExists($this->requiredFields, $resultingData);
    }

    /**
    * Camelcase to underscore
    *
    * @param $name
    * @return $result
    */
    private function _underscore($name)
    {
        if (isset(self::$_underscoreCache[$name])) {
            return self::$_underscoreCache[$name];
        }
        $result = strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", $name));
        self::$_underscoreCache[$name] = $result;
        return $result;
    }

    /**
    * Checks wether all keys are used in array
    *
    * @param $keys, $arr
    * @return bool
    */
    private function _arrayKeysExists(array $keys, array $arr)
    {
        return !array_diff_key(array_flip($keys), $arr);
    }

}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper;

use Doctrine\ODM\MongoDB\Internal\CommitOrderCalculator;
use Sp\FixtureDumper\Mapping\MongoDB\ClassMetadataProxy;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class MongoDBDumper extends AbstractDumper
{
    /**
     * {@inheritdoc}
     */
    public function getDumpOrder(array $classes)
    {
        $calc = new CommitOrderCalculator();

        // See if there are any new classes in the changeset, that are not in the
        // commit order graph yet (don't have a node).
        // We have to inspect changeSet to be able to correctly build dependencies.
        // It is not possible to use IdentityMap here because post inserted ids
        // are not yet available.
        $newNodes = array();
        foreach ($classes as $class) {
            if ($calc->hasClass($class->getName())) {
                continue;
            }

            $calc->addClass($class);

            $newNodes[] = $class;
        }

        // Calculate dependencies for new nodes
        while ($class = array_pop($newNodes)) {
            $this->addDependencies($class, $calc);
        }

        return $calc->getCommitOrder();
    }

    /**
     * {@inheritdoc}
     */
    public function getAllMetadata()
    {
        $metadata = parent::getAllMetadata();

        $newMetadata = array();
        foreach ($metadata as $data) {
            $newMetadata[] = new ClassMetadataProxy($data);
        }

        return $newMetadata;
    }

    private function addDependencies(ClassMetadataProxy $class, CommitOrderCalculator $calc)
    {
        foreach ($class->origFieldMappings as $mapping) {
            $isOwningReference = isset($mapping['reference']) && $mapping['isOwningSide'];
            $isAssociation = isset($mapping['embedded']) || $isOwningReference;
            if (!$isAssociation || !isset($mapping['targetDocument'])) {
                continue;
            }

            $targetClass = $this->objectManager->getClassMetadata($mapping['targetDocument']);

            if ( ! $calc->hasClass($targetClass->name)) {
                $calc->addClass($targetClass);
            }

            $calc->addDependency($targetClass, $class);

            // If the target class has mapped subclasses, these share the same dependency.
            if (! $targetClass->subClasses) {
                continue;
            }

            $newNodes = array();
            foreach ($targetClass->subClasses as $subClassName) {
                $targetSubClass = $this->objectManager->getClassMetadata($subClassName);

                if ( ! $calc->hasClass($subClassName)) {
                    $calc->addClass($targetSubClass);

                    $newNodes[] = $targetSubClass;
                }

                $calc->addDependency($targetSubClass, $class);
            }

            // avoid infinite recursion
            if ($class !== $targetClass) {
                $this->addDependencies($targetClass, $calc);
            }
        }
    }
}


<?php

namespace Modules\Setting\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Setting\Models\Setting;
use Netcore\Translator\Helpers\TransHelper;
use Netcore\Translator\Models\Language;
use Nwidart\Modules\Facades\Module;

class SettingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('setting::index');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param Setting $setting
     * @return Response
     */
    public function edit(Setting $setting)
    {
        $mediaModule = Module::find('media');

        return view('setting::edit', compact('setting', 'mediaModule'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request       $request
     * @param Setting       $setting
     * @param Language|null $language
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Setting $setting, Language $language = null)
    {
        if ($setting->is_translatable && $language) {
            $translations[$language->iso_code]['value'] = $request->get('value', '');

            $setting->updateTranslations($translations);

            setting()->clear_cache();

            return response()->json([
                'status' => 'success'
            ]);
        }

        $translations = $request->get('translations', []);

        // Set universal value across all languages
        if (! $setting->is_translatable && ! $setting->is('file')) {
            foreach (TransHelper::getAllLanguages() as $language) {
                $translations[$language->iso_code] = [
                    'value' => $request->get('value', '')
                ];
            }
        }

        // Checkbox
        if ($setting->is('checkbox')) {
            foreach ($translations as $languageId => &$data) {
                $data['value'] = array_get($data, 'value', 0) ?: 0;
            }
        }

        // File
        if ($setting->is('file')) {
            $files = $setting->is_translatable ? $request->file('translations') : $request->file('value');

            $path = public_path(config('setting.upload_path'));
            if (! \File::exists($path)) {
                \File::makeDirectory($path, 0775, true);
            }

            if ($setting->is_translatable) {
                foreach (TransHelper::getAllLanguages() as $language) {
                    $file = isset($files[$language->iso_code]) ? $files[$language->iso_code]['value'] : null;
                    if (! $file) {
                        continue;
                    }

                    $fileName = str_slug($setting->key) . '-' . $language->iso_code . '.' . $file->getClientOriginalExtension();
                    $file->move($path, $fileName);

                    $translations[$language->iso_code] = [
                        'value' => $fileName
                    ];
                }
            } else {
                $file = $files;
                if (! $file) {
                    return back()->withErrors('File is required.');
                }

                $fileName = str_slug($setting->key) . '.' . $file->getClientOriginalExtension();
                $file->move($path, $fileName);

                foreach (TransHelper::getAllLanguages() as $language) {
                    $translations[$language->iso_code] = [
                        'value' => $fileName
                    ];
                }
            }
        }

        $setting->updateTranslations($translations);

        setting()->clear_cache();

        if ($request->ajax()) {
            return response()->json([
                'status' => 'success'
            ]);
        }

        return redirect()->route('admin::setting.index')->withSuccess('Successfully saved');
    }
}


<?php

namespace Wuunder\Api\Endpoints;

use Wuunder\Api\Config\ShipmentConfig;
use Wuunder\Api\Environment;
use Wuunder\Api\Key;
use Wuunder\Api\ShipmentApiResponse;
use Wuunder\Http\PostRequest;
use Wuunder\Util\Helper;

class Shipment {

    private $config;
    private $apiKey;
    private $apiEnvironment;
    private $shipmentResponse;
    private $logger;

    public function __construct(Key $apiKey, Environment $apiEnvironment)
    {
        $this->config = new ShipmentConfig();
        $this->apiKey = $apiKey;
        $this->apiEnvironment = $apiEnvironment;
        $this->logger = Helper::getInstance();
    }

    /**
     * Set data to send to API
     *
     * @param ShipmentConfig $config
     * @internal param mixed $data JSON encoded
     */
    public function setConfig(ShipmentConfig $config)
    {
        $this->config = $config;
    }

    /**
     * Return BookingConfig object of current booking
     *
     * @return ShipmentConfig
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Fires the request and handles the result.
     *
     * @return bool
     */
    public function fire()
    {
        $shipmentRequest = new PostRequest($this->apiEnvironment->getStageBaseUrl() . "/shipments",
            $this->apiKey->getApiKey(), json_encode($this->config));
        try {
            $shipmentRequest->send();
        } catch(Exception $e) {
            $this->logger->log($e);
        }

        $body = null;
        $header = null;
        $error = null;

        if (isset($shipmentRequest->getResponseHeaders()["http_code"]) && strpos($shipmentRequest->getResponseHeaders()["http_code"], "201 Created") !== false) {
            $body = $shipmentRequest->getBody();
            $header = $shipmentRequest->getResponseHeaders();
        } else {
            $error = $shipmentRequest->getResponse();
        }
        $this->shipmentResponse = new ShipmentApiResponse($header, $body, $error);

        return is_null($error);
    }

    /**
     * Returns shipment response object
     *
     * @return mixed
     */
    public function getShipmentResponse()
    {
        return $this->shipmentResponse;
    }
}


<?php

namespace Wuunder\Api\Endpoints;

use Wuunder\Api\Config\ParcelshopConfig;
use Wuunder\Api\Environment;
use Wuunder\Api\Key;
use Wuunder\Api\ParcelshopApiResponse;
use Wuunder\Http\GetRequest;
use Wuunder\Util\Helper;

class Parcelshop
{
    private $config;
    private $apiKey;
    private $apiEnvironment;
    private $parcelshopResponse;
    private $logger;

    public function __construct(Key $apiKey, Environment $apiEnvironment)
    {
        $this->config = new ParcelshopConfig();
        $this->apiKey = $apiKey;
        $this->apiEnvironment = $apiEnvironment;
        $this->logger = Helper::getInstance();
    }

    /**
     * Set data to send to API
     *
     * @param ParcelshopConfig $config Config of the request
     * @internal param mixed $data JSON encoded
     */
    public function setConfig(ParcelshopConfig $config)
    {
        $this->config = $config;
    }

    /**
     * Return BookingConfig object of current booking
     *
     * @return ParcelshopConfig
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Fires the request and handles the result.
     *
     * @return bool
     */
    public function fire()
    {
        $parcelshopRequest = new GetRequest($this->apiEnvironment->getStageBaseUrl() . "/parcelshops/" . $this->config->get("id"),
            $this->apiKey->getApiKey());
        try {
            $parcelshopRequest->send();
        } catch (\Exception $e) {
            $this->logger->log($e);
        }
        $body = null;
        $header = null;
        $error = null;

        if (isset($parcelshopRequest->getResponseHeaders()["http_code"])
            && strpos($parcelshopRequest->getResponseHeaders()["http_code"], "200 OK") !== false
        ) {
            $body = $parcelshopRequest->getBody();
            $header = $parcelshopRequest->getResponseHeaders();
        } else {
            $error = $parcelshopRequest->getResponse();
        }
        $this->parcelshopResponse = new ParcelshopApiResponse($header, $body, $error);

        return is_null($error);
    }

    /**
     * Returns parcelshop response object
     *
     * @return ParcelshopApiResponse
     */
    public function getParcelshopResponse()
    {
        return $this->parcelshopResponse;
    }
}


<?php

namespace Michaeljennings\Refinery;

use Michaeljennings\Refinery\Contracts\Refinery as RefineryContract;
use Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound;
use Michaeljennings\Refinery\Exceptions\RefineryMethodNotFound;
use Traversable;

abstract class Refinery implements RefineryContract
{
    /**
     * The items to be attached to the refined item.
     *
     * @var array
     */
    protected $attachments = [];

    /**
     * A filter to run on the raw data.
     *
     * @var callable
     */
    protected $filter;

    /**
     * The extra data which is available within a refinery.
     *
     * @var array
     */
    protected $attributes = [];

    /**
     * If we are iterating through a collection this will be the key of the current item.
     *
     * @var mixed
     */
    protected $key;

    /**
     * Set the template the refinery will use for each item passed to it
     *
     * @param mixed $item
     * @return mixed
     */
    abstract protected function setTemplate($item);

    /**
     * Refine the item(s) using the set template.
     *
     * @param  mixed $raw
     * @param bool   $retainKey
     * @return mixed
     */
    public function refine($raw, $retainKey = false)
    {
        if ((is_array($raw) && $this->isMultidimensional($raw)) || $raw instanceof Traversable) {
            return $this->refineCollection($raw, $retainKey);
        }

        return $this->refineItem($raw);
    }

    /**
     * Refine a single item using the supplied callback.
     *
     * @param  mixed $raw
     * @return mixed
     */
    public function refineItem($raw)
    {
        $refined = $this->setTemplate($raw);

        if ( ! empty($this->attachments)) {
            $refined = $this->merge($refined, $this->includeAttachments($raw));
        }

        return $refined;
    }

    /**
     * Refine a collection of raw items.
     *
     * @param mixed $raw
     * @param boolean $retainKey
     * @return array
     */
    public function refineCollection($raw, $retainKey = false)
    {
        $refined = [];

        foreach ($raw as $key => $item) {
            if ($retainKey) {
                $this->key = $key;
                $refined[ $key ] = $this->refineItem($item);
            } else {
                $refined[] = $this->refineItem($item);
            }
        }

        return $refined;
    }

    /**
     * Return any required attachments. Check if the attachment needs to
     * be filtered, if so they run the callback and then return the
     * attachments.
     *
     * @param  mixed $raw
     * @return mixed
     */
    protected function includeAttachments($raw)
    {
        $attachments = [];

        foreach ($this->attachments as $attachment => $refinery) {
            if (isset($refinery['raw'])) {
                $attachments[$attachment] = $refinery['raw']($raw);
            } else {
                $class = $refinery['class'];
                $callback = $refinery['callback'];

                if ( ! $callback) {
                    $items = $this->getItems($raw, $class, $attachment);
                } else {
                    $items = $this->getItemsUsingCallback($raw, $class, $callback);
                }

                $attachments[$attachment] = ! is_null($items) ? $class->refine($items) : null;
            }
        }

        return $attachments;
    }

    /**
     * Get the items to be refined from the raw object.
     *
     * @param mixed  $raw
     * @param mixed  $class
     * @param string $attachment
     * @return mixed
     */
    protected function getItems($raw, $class, $attachment)
    {
        if ($class->hasFilter()) {
            $query = $class->getFilter();

            return call_user_func_array($query, [$raw->$attachment()]);
        } else {
            return is_object($raw) ? $raw->$attachment : $raw[$attachment];
        }
    }

    /**
     * Run a callback on the raw item(s) and then return the items.
     *
     * @param mixed    $raw
     * @param mixed    $class
     * @param callable $callback
     * @return mixed
     */
    protected function getItemsUsingCallback($raw, $class, callable $callback)
    {
        if ($class->hasFilter()) {
            $query = $class->getFilter();
            $items = $callback($raw);

            return call_user_func_array($query, [$items]);
        } else {
            return $callback($raw);
        }
    }

    /**
     * Set the attachments you want to bring with the refined items.
     *
     * @param  string|array $attachments
     * @return $this
     */
    public function bring($attachments)
    {
        if (is_string($attachments)) {
            $attachments = func_get_args();
        }

        $this->attachments = $this->parseAttachments($attachments);

        return $this;
    }

    /**
     * Get the classes needed for each attachment.
     *
     * @param  array $relations
     * @return array
     */
    protected function parseAttachments(array $relations)
    {
        $parsedRelations = [];

        foreach ($relations as $key => $relation) {
            if ( ! is_numeric($key)) {
                if (is_callable($relation)) {
                    $parsedRelations[$key] = $this->attachItem($key);
                    $parsedRelations[$key]['class']->with($this->attributes)->filter($relation);
                } else {
                    $parsedRelations[$key] = $this->attachItem($key);
                    $parsedRelations[$key]['class']->with($this->attributes)->bring($relation);
                }
            } else {
                $parsedRelations[$relation] = $this->attachItem($relation);

                if (isset($parsedRelations[$relation]['class'])) {
                    $parsedRelations[$relation]['class']->with($this->attributes);
                }
            }
        }

        return $parsedRelations;
    }

    /**
     * Check the attachment method exists on the class being attached, if it
     * does then run the method.
     *
     * @param  string $attachment
     * @return mixed
     * @throws RefineryMethodNotFound
     */
    protected function attachItem($attachment)
    {
        if ( ! method_exists($this, $attachment)) {
            throw new RefineryMethodNotFound(
                "No attachment set with the name '{$attachment}' on '" . get_class($this) . "'."
            );
        }

        return $this->$attachment();
    }

    /**
     * Set the class to be used for the attachment.
     *
     * @param string|callable $className
     * @param callable|bool   $callback
     * @return array
     * @throws AttachmentClassNotFound
     */
    public function attach($className, callable $callback = null)
    {
        // If the user has passed through a callable item then we want
        // to attach the raw result of that call.
        if (is_callable($className)) {
            return ['raw' => $className];
        }

        if ( ! class_exists($className)) {
            throw new AttachmentClassNotFound("No class found with the name '{$className}'.");
        }

        return ['class' => new $className, 'callback' => $callback];
    }

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws AttachmentClassNotFound
     */
    public function embed($className, callable $callback = null)
    {
        return $this->attach($className, $callback);
    }

    /**
     * Alias for the attach method.
     *
     * @param string   $className
     * @param callable $callback
     * @return array
     * @throws AttachmentClassNotFound
     */
    public function nest($className, callable $callback = null)
    {
        return $this->attach($className, $callback);
    }

    /**
     * Set a filter to run on the raw data.
     *
     * @param  callable $filter
     * @return Refinery
     */
    protected function setFilter(callable $filter)
    {
        $this->filter = $filter;

        return $this;
    }

    /**
     * Alias for the setFilter method.
     *
     * @param  callable $filter
     * @return Refinery
     */
    protected function filter(callable $filter)
    {
        return $this->setFilter($filter);
    }

    /**
     * Check if a filter has been set
     *
     * @return boolean
     */
    protected function hasFilter()
    {
        return ! empty($this->filter);
    }

    /**
     * Return the filter callback
     *
     * @return Closure
     */
    protected function getFilter()
    {
        return $this->filter;
    }

    /**
     * Merge a set of data into another.
     *
     * @param mixed $original
     * @param mixed $merge
     * @return mixed
     */
    protected function merge($original, $merge)
    {
        if (is_array($original) && is_array($merge)) {
            return array_merge($original, $merge);
        }

        if (is_array($original)) {
            foreach ($merge as $key => $value) {
                $original[$key] = $value;
            }
        } else {
            foreach ($merge as $key => $value) {
                $original->$key = $value;
            }
        }

        return $original;
    }

    /**
     * Check if the provided array is multidimensional.
     *
     * @param array $array
     * @return bool
     */
    protected function isMultidimensional(array $array)
    {
        foreach ($array as $element) {
            if ( ! is_array($element) && ! is_object($element)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Store the passed items within the $attributes property.
     *
     * @param array $items
     * @return $this
     */
    public function with(array $items)
    {
        $this->attributes = $items;

        return $this;
    }

    /**
     * Get the current key.
     *
     * @return mixed
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Use the __get magic method to access the items within the $attributes
     * array is if you were accessing a property on the class.
     *
     * @param $key
     * @return null
     */
    public function __get($key)
    {
        if (array_key_exists($key, $this->attributes)) {
            return $this->attributes[$key];
        }

        return null;
    }
}


<?php

namespace Wuunder\Http;

abstract class Request
{

    protected $url;
    protected $apiKey;
    protected $result;
    protected $headerSize;

    public function __construct($url, $apiKey)
    {
        $this->url = $url;
        $this->apiKey = $apiKey;
    }

    abstract protected function send();

    /**
     * Returns the whole response from a response
     *
     * @return $result
     */
    public function getResponse()
    {
        return $this->result;
    }

    /**
     * Returns the response body from a response
     *
     * @return $result (body)
     */
    public function getBody()
    {
        return substr($this->result, $this->headerSize);
    }

    /**
     * Returns the headers from a response
     *
     * @return $headers
     */
    public function getResponseHeaders()
    {
        $headers = array();

        $header_text = substr($this->result, 0, $this->headerSize);

        foreach (explode("\r\n", $header_text) as $i => $line)
            if (strlen($line) > 4 && substr($line, 0, 4) === "HTTP") {
                $headers['http_code'] = $line;
            } else {
                list ($key, $value) = array_pad(explode(': ', $line, 2), 2, null);
                $headers[$key] = $value;
            }

        return $headers;
    }
}


<?php
/**
 * Fat Zebra REST Response
 */

namespace Omnipay\Fatzebra\Message;

use Omnipay\Common\Message\AbstractResponse;
use Omnipay\Common\Message\RequestInterface;

/**
 * Fat Zebra REST Response
 *
 * This is the response class for all Fat Zebra REST requests.
 *
 * @see \Omnipay\Fatzebra\FatzebraGateway
 */
class RestResponse extends AbstractResponse
{
    protected $statusCode;

    public function __construct(RequestInterface $request, $data, $statusCode = 200)
    {
        parent::__construct($request, $data);
        $this->statusCode = $statusCode;
    }

    public function isSuccessful()
    {
        // The Fat Zebra gateway returns errors in several possible different ways.
        if ($this->getCode() >= 400) {
            return false;
        }

        if (! empty($this->data['errors'])) {
            return false;
        }

        if (isset($this->data['response']['successful'])) {
            return $this->data['response']['successful'];
        }

        return true;
    }

    public function getTransactionReference()
    {
        // This is usually correct for payments, authorizations, etc
        if (! empty($this->data['response']) && ! empty($this->data['response']['id'])) {
            return $this->data['response']['id'];
        }

        // This is correct for tokenize
        if (! empty($this->data['response']) && ! empty($this->data['response']['token'])) {
            return $this->data['response']['token'];
        }

        // This is correct for create customer
        if (! empty($this->data['response']) && ! empty($this->data['response']['card_token'])) {
            return $this->data['response']['card_token'];
        }

        // This is correct for create plan
        if (! empty($this->data['response']) && ! empty($this->data['response']['plan'])) {
            return $this->data['response']['plan'];
        }

        return null;
    }

    /**
     * Get Card Reference
     *
     * This is used after createCard or createCustomer to get the credit card token to be
     * used in future transactions.
     *
     * @return string
     */
    public function getCardReference()
    {
        if (isset($this->data['response']['token'])) {
            return $this->data['response']['token'];
        }
        if (isset($this->data['response']['card_token'])) {
            return $this->data['response']['card_token'];
        }
    }

    /**
     * Get Customer Reference
     *
     * This is used after createCustomer to get the customer token to be
     * used in future transactions.
     *
     * @return string
     */
    public function getCustomerReference()
    {
        if (isset($this->data['response']['customer'])) {
            return $this->data['response']['customer'];
        }
        if (isset($this->data['response']['id'])) {
            return $this->data['response']['id'];
        }
    }

    /**
     * Get Plan Reference
     *
     * This is used after createPlan to get the plan token to be
     * used in future transactions.
     *
     * @return string
     */
    public function getPlanReference()
    {
        if (isset($this->data['response']['plan'])) {
            return $this->data['response']['plan'];
        }
    }

    /**
     * Get Subscription Reference
     *
     * This is used after createSubscription to get the subscription token to be
     * used in future transactions.
     *
     * @return string
     */
    public function getSubscriptionReference()
    {
        if (isset($this->data['response']['id'])) {
            return $this->data['response']['id'];
        }
    }

    public function getMessage()
    {
        if (isset($this->data['errors']) && count($this->data['errors']) > 0) {
            return implode(', ', $this->data['errors']);
        }

        if (isset($this->data['response']['message'])) {
            return $this->data['response']['message'];
        }

        return null;
    }

    public function getCode()
    {
        if (isset($this->data['response']['response_code'])) {
            return $this->data['response']['response_code'];
        }

        return $this->statusCode;
    }
}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Util;

use InvalidArgumentException;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
final class ClassUtils
{
    private function __construct()
    {}

    /**
     * Strip the namespace from a given class or object and get only the class name.
     *
     * @param mixed $class
     *
     * @throws \InvalidArgumentException
     * @return bool|string
     */
    public static function getClassName($class)
    {
        if (!is_object($class) && !is_string($class)) {
            throw new InvalidArgumentException(sprintf('$object must be a string or an object, %s given', gettype($class)));
        }

        $className = is_string($class) ? $class : get_class($class);
        $pos = strrpos($className, '\\');

        if ($pos !== false) {
            $className = substr($className, ($pos + 1));
        }

        return $className;
    }

    /**
     * Get the namespace from a given class or object.
     *
     * @param mixed $class
     *
     * @return string
     * @throws \InvalidArgumentException
     */
    public static function getNamespace($class)
    {
        if (!is_object($class) && !is_string($class)) {
            throw new InvalidArgumentException('$object must be a string or an object');
        }

        $class = (is_string($class) ? $class : get_class($class));
        $pos = strrpos($class, '\\');

        return substr($class, 0, $pos);
    }
}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class DefaultNamingStrategy implements NamingStrategyInterface
{
    /**
     * {@inheritdoc}
     */
    public function fixtureName(ClassMetadata $metadata)
    {
        return ClassUtils::getClassName($metadata->getName());
    }

    /**
     * {@inheritdoc}
     */
    public function modelName($model, ClassMetadata $metadata)
    {
        $identifiers = $metadata->getIdentifierValues($model);
        $className = lcfirst(ClassUtils::getClassName($metadata->getName()));

        return $className . implode('_', $identifiers);
    }

}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Util\ClassUtils;
use CG\Generator\Writer;
use CG\Generator\PhpClass;
use CG\Core\DefaultGeneratorStrategy;
use CG\Generator\PhpMethod;
use CG\Generator\PhpParameter;
use Sp\FixtureDumper\Converter\PhpVisitor;
use Symfony\Component\PropertyAccess\StringUtil;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class ClassFixtureGenerator extends AbstractGenerator
{
    /**
     * {@inheritdoc}
     */
    public function createFilename(ClassMetadata $metadata, $multipleFiles = true)
    {
        if ($multipleFiles) {
            return $this->namingStrategy->fixtureName($metadata) .'.php';
        }

        return 'Fixtures.php';
    }

    /**
     * {@inheritdoc}
     */
    public function prepareForWrite($fixture)
    {
        return "<?php\n\n". $fixture;
    }

    /**
     * {@inheritdoc}
     */
    protected function doGenerate(ClassMetadata $metadata, array $data, array $options = array())
    {
        static $docBlock;
        if (empty($docBlock)) {
            $writer = new Writer();
            $writer
                ->writeln('/**')
                ->writeln(' * This code was generated automatically by the FixtureDumper library, manual changes to it')
                ->writeln(' * may be lost upon next generation.')
                ->write(' */');

            $docBlock = $writer->getContent();
        }

        $fixtureClass = new PhpClass($options['namespace'] .'\\'. $this->namingStrategy->fixtureName($metadata));
        $fixtureClass->setDocblock($docBlock);
        $fixtureClass->setParentClassName('Doctrine\\Common\\DataFixtures\\AbstractFixture');
        $fixtureClass->addUseStatement($metadata->getName());

        if (count($metadata->getAssociationNames()) !== 0) {
            $this->addDependentFixtureInterface($fixtureClass, $metadata, $options);
        }

        $this->generateLoadMethod($fixtureClass, $metadata, $data);

        $generator = new DefaultGeneratorStrategy();
        $content = $generator->generate($fixtureClass);

        return $content;
    }

    protected function generateLoadMethod(PhpClass $class, ClassMetadata $metadata, array $data)
    {
        $writer = new Writer();
        $method = PhpMethod::create('load');
        $managerParameter = PhpParameter::create('manager');
        $managerParameter->setType('Doctrine\\Common\\Persistence\\ObjectManager');
        $method->addParameter($managerParameter);
        $class->setMethod($method);

        foreach ($data as $modelName => $modelData) {
            $search = array(' ', '-', 'á', 'é', 'í', 'ó', 'ú', 'ñ');
            $replace = array('_', '_', 'a', 'e', 'i', 'o', 'u', 'n');
            $withoutSpace = str_replace($search, $replace, $modelName);
            $this->generateModel($withoutSpace, $modelData, $metadata, $writer);
            $writer->writeln("");
        }

        $writer->writeln('$manager->flush();');
        $method->setBody($writer->getContent());
    }

    protected function generateModel($modelName, $modelData, ClassMetadata $metadata, Writer $writer)
    {
        $writer->writeln(sprintf("$%s = new %s();", $modelName, ClassUtils::getClassName($metadata->getName())));
        foreach ($modelData['fields'] as $key => $value) {
            $setter = sprintf('set%s', ucfirst($key));
            $writer->writeln(sprintf("$%s->%s(%s);", $modelName, $setter, $value));
        }

        foreach ($modelData['associations'] as $assocName => $reference) {
            $this->writeReference($metadata, $modelName, $assocName, $reference, $writer);
        }

        $writer->writeln(sprintf('$manager->persist($%s);', $modelName));
        $writer->writeln(sprintf('$this->addReference(\'%1$s\', $%1$s);', $modelName));
    }

    protected function writeReference(ClassMetadata $metadata, $modelName, $assocName, $reference, Writer $writer)
    {
        $setter = sprintf('set%s', ucfirst($assocName));
        if ($metadata->isSingleValuedAssociation($assocName)) {
            $reference = sprintf("\$this->getReference('%s')", $reference);
            $writer->writeln(sprintf("$%s->%s(%s);", $modelName, $setter, $reference));
        } else {
            $class = $metadata->getName();
            if ($adder = $this->findAdderMethod(new $class(), ucfirst($assocName))) {
                foreach ($reference as $ref) {
                    $refString = sprintf("\$this->getReference('%s')", $ref);
                    $writer->writeln(sprintf("$%s->%s(%s);", $modelName, $adder, $refString));
                }
            } else {
                $result = array();
                foreach ($reference as $key => $ref) {
                    $result[] = sprintf("\$this->getReference('%s')", $ref);
                }
                $writer->writeln(sprintf("$%s->%s(array(%s));", $modelName, $setter, implode(', ', $result)));
            }
        }
    }

    protected function addDependentFixtureInterface(PhpClass $class, ClassMetadata $metadata, array $options)
    {
        $class->addInterfaceName('Doctrine\\Common\\DataFixtures\\DependentFixtureInterface');
        $writer = new Writer();
        $method = PhpMethod::create('getDependencies');

        $writer->writeln("return array(");
        $associations = array();
        foreach ($metadata->getAssociationNames() as $assocName) {
            $targetClass = $metadata->getAssociationTargetClass($assocName);
            $associations[] = sprintf("'%s\\%s'", $options['namespace'], $this->namingStrategy->fixtureName($this->getManager()->getClassMetadata($targetClass)));
        }

        $writer->indent();
        $writer->writeln(implode(",\n", $associations));
        $writer->outdent();
        $writer->writeln(");");

        $method->setBody($writer->getContent());

        $class->setMethod($method);
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultVisitor()
    {
        return new PhpVisitor();
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultNamingStrategy()
    {
        return new ClassNamingStrategy();
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredOptions()
    {
        return array('namespace');
    }

    /**
     * Finds an adder method for the given object.
     * Thanks to the alice library for this code snippet.
     *
     * @param mixed  $obj
     * @param string $key
     *
     * @return string|null
     */
    private function findAdderMethod($obj, $key)
    {
        if (method_exists($obj, $method = 'add'.$key)) {
            return $method;
        }

        foreach ((array) StringUtil::singularify($key) as $singularForm) {
            if (method_exists($obj, $method = 'add'.$singularForm)) {
                return $method;
            }
        }

        if (method_exists($obj, $method = 'add'.rtrim($key, 's'))) {
            return $method;
        }

        if (substr($key, -3) === 'ies' && method_exists($obj, $method = 'add'.substr($key, 0, -3).'y')) {
            return $method;
        }
    }
}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Mapping\MongoDB;

use InvalidArgumentException;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use \Doctrine\ODM\MongoDB\Mapping\ClassMetadata as BaseClassMetadata;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class ClassMetadataProxy implements ClassMetadata
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var array
     */
    public $origFieldMappings;

    /**
     * @var \Doctrine\ODM\MongoDB\Mapping\ClassMetadata
     */
    protected $classMetadata;

    /**
     * @var array
     */
    protected $fieldMappings = array();

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

    /**
     * @var array
     */
    protected $associationMappings = array();

    /**
     * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $classMetadata
     */
    public function __construct(BaseClassMetadata $classMetadata)
    {
        $this->name = $classMetadata->name;
        $this->origFieldMappings = $classMetadata->fieldMappings;
        $this->classMetadata = $classMetadata;
    }

    /**
     * {@inheritdoc}
     */
    public function getAssociationNames()
    {
        $this->initMappings();

        return array_keys($this->associationMappings);
    }

    /**
     * {@inheritdoc}
     */
    public function getAssociationTargetClass($assocName)
    {
        $this->initMappings();

        if ( ! isset($this->associationMappings[$assocName])) {
            throw new InvalidArgumentException("Association name expected, '" . $assocName ."' is not an association.");
        }

        return $this->associationMappings[$assocName]['targetDocument'];
    }

    /**
     * {@inheritdoc}
     */
    public function getFieldNames()
    {
        $this->initMappings();

        return array_keys($this->fieldMappings);
    }

    /**
     * Initialize the mappings from the class metadata.
     * The mapping will be split in field mappings and association mappings.
     *
     * @return ClassMetadataProxy
     */
    protected function initMappings()
    {
        if ($this->initialized) {
            return $this;
        }

        foreach ($this->classMetadata->fieldMappings as $key => $mapping) {
            if (isset($mapping['reference'])) {
                $this->associationMappings[$key] = $mapping;
            } else {
                $this->fieldMappings[$key] = $mapping;
            }
        }

        $this->initialized = true;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->classMetadata->getName();
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifier()
    {
        return $this->classMetadata->getIdentifier();
    }

    /**
     * {@inheritdoc}
     */
    public function getReflectionClass()
    {
        return $this->classMetadata->getReflectionClass();
    }

    /**
     * {@inheritdoc}
     */
    public function isIdentifier($fieldName)
    {
        return $this->classMetadata->isIdentifier($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function hasField($fieldName)
    {
        return $this->classMetadata->hasField($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function hasAssociation($fieldName)
    {
        return $this->classMetadata->hasAssociation($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function isSingleValuedAssociation($fieldName)
    {
        return $this->classMetadata->isSingleValuedAssociation($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function isCollectionValuedAssociation($fieldName)
    {
        return $this->classMetadata->isCollectionValuedAssociation($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifierFieldNames()
    {
        return $this->classMetadata->getIdentifierFieldNames();
    }

    /**
     * {@inheritdoc}
     */
    public function getTypeOfField($fieldName)
    {
        return $this->classMetadata->getTypeOfField($fieldName);
    }

    /**
     * {@inheritdoc}
     */
    public function isAssociationInverseSide($assocName)
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getAssociationMappedByTargetField($assocName)
    {
        return $this->classMetadata->getAssociationMappedByTargetField($assocName);
    }

    /**
     * {@inheritdoc}
     */
    public function getIdentifierValues($object)
    {
        return $this->classMetadata->getIdentifierValues($object);
    }

}


<?php

namespace Wuunder\Util;

class Helper
{

    private $logger;
    private $translationData;

    /**
     * Creates a new instance of the Helper
     *
     * @return Helper
     */
    public static function getInstance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new Helper();
        }
        return $inst;
    }

    /**
     * Sets the native logger
     *
     * @param $logger callback, possible array with first element class reference and second element function name.
     */
    public function setLogger($logger)
    {
        $this->logger = $logger;
    }

    /**
     * Calls the log function.
     *
     * @param $logText
     */
    public function log($logText)
    {
        if (isset($this->logger)) {
            call_user_func_array($this->logger, array($logText));
        }
    }

    private function __construct()
    {

    }

    /**
     * Sets data used for translations
     *
     * @param $lang
     */
    public function setTranslationLang($lang)
    {
        global $translationData;
        $translationData = array();
        $file = realpath(dirname(dirname(__FILE__)) . "/etc/lang/en-" . strtolower($lang) . ".csv");
        if (file_exists($file)) {
            if (($handle = fopen($file, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if (count($data) == 2) {
                        $translationData[$data[0]] = $data[1];
                    }
                }
                fclose($handle);
            }

        }
    }

    public function translate($val)
    {
        global $translationData;

        if (is_array($translationData) && !in_array(strtolower($val), $translationData)) {
            $translatedVal = $translationData[strtolower($val)];
            if ($this->_startsWithUpper($val)) {
                $translatedVal = ucfirst($translatedVal);
            }
            return $translatedVal;
        }

        return $val;
    }

    private function _startsWithUpper($str)
    {
        $chr = mb_substr($str, 0, 1, "UTF-8");
        return ctype_upper($chr);
    }

}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Converter\Handler;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class HandlerRegistry implements HandlerRegistryInterface
{
    /**
     * @var array
     */
    protected $handlers;

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

    /**
     * {@inheritdoc}
     */
    public function addSubscribingHandler(HandlerSubscriberInterface $handler)
    {
        $methods = $handler->getSubscribedMethods();

        foreach ($methods as $method) {
            if (!isset($method['format'], $method['type'], $method['method'])) {
                throw new \RuntimeException(sprintf('For each subscribing method a "type", "format" and "method" attribute must be given, but only got "%s" for %s.', implode('" and "', array_keys($method)), get_class($handler)));
            }

            $this->addHandler($method['type'], $method['format'], array($handler, $method['method']));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function addHandler($type, $format, $handler)
    {
        if (!is_callable($handler)) {
            throw new \InvalidArgumentException('$handler must be callable');
        }

        $this->handlers[$type][$format] = $handler;
    }

    /**
     * {@inheritdoc}
     */
    public function getHandler($type, $format)
    {
        if (!isset($this->handlers[$type][$format])) {
            return null;
        }

        return $this->handlers[$type][$format];
    }
}


<?php

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 LinguaLeo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace LinguaLeo\Cache\Provider;

class HotCache extends CacheProvider
{
    protected $cache = [];

    /**
     * {@inheritdoc}
     */
    public function get($key)
    {
        return isset($this->cache[$key]) ? $this->cache[$key] : false;
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $data, $ttl = 0)
    {
        $this->cache[$key] = $data;
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function create($key, callable $modifier, $ttl = 0)
    {
        $data = $this->get($key);
        $modifier($data);
        $this->set($key, $data);
        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function update($key, callable $modifier, $ttl = 0)
    {
        if (array_key_exists($key, $this->cache)) {
            $modifier($this->cache[$key]);
            return $this->cache[$key];
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        if (isset($this->cache[$key])) {
            unset($this->cache[$key]);
            return true;
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function mdelete(array $keys)
    {
        foreach ($keys as $key) {
            unset($this->cache[$key]);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function increment($key, $value = 1)
    {
        if ($value < 1) {
            throw new \InvalidArgumentException('Value of incrementation must be greater that nil.');
        }

        if (isset($this->cache[$key])) {
            $this->cache[$key] += $value;
        } else {
            $this->cache[$key] = $value;
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function mget(array $keys)
    {
        $result = array();

        foreach ($keys as $key) {
            if (isset($this->cache[$key])) {
                $result[$key] = $this->cache[$key];
            }
        }

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function mset(array $data, $ttl = 0)
    {
        $count = 0;
        foreach ($data as $key => $value) {
            if ($this->set($key, $value, $ttl)) {
                $count++;
            }
        }
        return $count;
    }

    /**
     * {@inheritdoc}
     */
    public function add($key, $data, $ttl = 0)
    {
        if (isset($this->cache[$key])) {
            return false;
        }

        $this->cache[$key] = $data;
        return true;
    }
}


<?php

/*
 * (c) Jeroen van den Enden <info@endroid.nl>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Endroid\TwitterBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $treeBuilder
            ->root('endroid_twitter')
                ->children()
                    ->scalarNode('consumer_key')->isRequired()->cannotBeEmpty()->end()
                    ->scalarNode('consumer_secret')->isRequired()->cannotBeEmpty()->end()
                    ->scalarNode('access_token')->defaultValue(null)->end()
                    ->scalarNode('access_token_secret')->defaultValue(null)->end()
                    ->scalarNode('api_url')->defaultValue(null)->end()
                    ->scalarNode('proxy')->defaultValue(null)->end()
                    ->integerNode('timeout')->defaultValue(5)->end()
                    ->booleanNode('verify_peer')->defaultValue(true)->end()
                ->end()
        ;

        return $treeBuilder;
    }
}


<?php

namespace Wuunder\Api\Endpoints;

use Wuunder\Api\Config\ParcelshopsConfig;
use Wuunder\Api\Environment;
use Wuunder\Api\Key;
use Wuunder\Api\ParcelshopsApiResponse;
use Wuunder\Http\GetRequest;

class Parcelshops
{
    private $config;
    private $apiKey;
    private $apiEnvironment;
    private $parcelshopsResponse;

    public function __construct(Key $apiKey, Environment $apiEnvironment)
    {
        $this->config = new ParcelshopsConfig();
        $this->apiKey = $apiKey;
        $this->apiEnvironment = $apiEnvironment;
    }

    /**
     * Set data to send to API
     *
     * @param ParcelshopsConfig $config
     * @internal param mixed $data JSON encoded
     */
    public function setConfig(ParcelshopsConfig $config)
    {
        $this->config = $config;
    }

    /**
     * Return BookingConfig object of current booking
     *
     * @return ParcelshopsConfig
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Fires the request and handles the result.
     *
     * @return bool
     */
    public function fire()
    {
        $parcelshopsRequest = new GetRequest($this->apiEnvironment->getStageBaseUrl() . "/parcelshops_by_address" . $this->config->toGetParameters(),
            $this->apiKey->getApiKey());
        try {
            $parcelshopsRequest->send();
        } catch(Exception $e) {
            $this->logger->log($e);
        }

        $body = null;
        $header = null;
        $error = null;

        if (isset($parcelshopsRequest->getResponseHeaders()["http_code"]) && strpos($parcelshopsRequest->getResponseHeaders()["http_code"], "200 OK") !== false) {
            $body = $parcelshopsRequest->getBody();
            $header = $parcelshopsRequest->getResponseHeaders();
        } else {
            $error = $parcelshopsRequest->getResponse();
        }
        $this->parcelshopsResponse = new ParcelshopsApiResponse($header, $body, $error);

        return is_null($error);
    }

    /**
     * Returns parcelshop models
     *
     * @return ParcelshopsApiResponse
     */
    public function getParcelshopsResponse()
    {
        return $this->parcelshopsResponse;
    }
}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator\Alice;

use Symfony\Component\Yaml\Yaml;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Converter\Alice\YamlVisitor;
use Sp\FixtureDumper\Generator\AbstractAliceGenerator;

/**
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
class YamlFixtureGenerator extends AbstractAliceGenerator
{

    /**
     * {@inheritdoc}
     */
    public function createFilename(ClassMetadata $metadata, $multipleFiles = true)
    {
        if ($multipleFiles) {
            return lcfirst($this->namingStrategy->fixtureName($metadata) .'.yml');
        }

        return 'fixtures.yml';
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareData(ClassMetadata $metadata, array $data)
    {
        $yaml = new Yaml();

        return $yaml->dump(array($metadata->getName() => $data), 3);
    }

    /**
     * {@inheritdoc}
     */
    protected function getDefaultVisitor()
    {
        return new YamlVisitor();
    }
}


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Sp\FixtureDumper\Exception\InvalidPropertyException;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\Common\Persistence\ObjectManager;
use Sp\FixtureDumper\Converter\VisitorInterface;
use Sp\FixtureDumper\Converter\DefaultVisitor;

/**
 * Base class for generating fixtures.
 *
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
abstract class AbstractGenerator
{
    /**
     * @var NamingStrategyInterface
     */
    protected $namingStrategy;

    /**
     * @var \Doctrine\Common\Persistence\ObjectManager
     */
    protected $manager;

    /**
     * @var \Sp\FixtureDumper\Converter\DefaultNavigator
     */
    protected $navigator;

    /**
     * @var \Sp\FixtureDumper\Converter\VisitorInterface
     */
    protected $visitor;

    /**
     * @var array
     */
    protected $models;

    /**
     * @var array
     */
    protected $propertyReader = array();

    /**
     * @var array
     */
    protected $fieldNamesPostProcessors = array();

    /**
     * @var bool
     */
    protected $skipNullValues = false;

    /**
     * @param \Doctrine\Common\Persistence\ObjectManager|null   $manager
     * @param NamingStrategyInterface|null                      $namingStrategy
     * @param \Sp\FixtureDumper\Converter\VisitorInterface|null $visitor
     */
    public function __construct(ObjectManager $manager = null, NamingStrategyInterface $namingStrategy = null, VisitorInterface $visitor = null)
    {
        $this->manager = $manager;
        $this->namingStrategy = $namingStrategy ?: $this->getDefaultNamingStrategy();
        $this->visitor = $visitor ?: $this->getDefaultVisitor();
    }

    /**
     * Adds a PropertyReader
     *
     * @param PropertyReaderInterface $propertyReader
     */
    public function addPropertyReader(PropertyReaderInterface $propertyReader)
    {
        $this->propertyReader[] = $propertyReader;
    }

    /**
     * adds a postprocessor
     *
     * @param FieldNamesPostProcessorInterface $postProcessor
     */
    public function addFieldNamesPostProcessor(FieldNamesPostProcessorInterface $postProcessor)
    {
        $this->fieldNamesPostProcessors[] = $postProcessor;
    }

    /**
     * @return boolean
     */
    public function isSkipNullValues()
    {
        return $this->skipNullValues;
    }

    /**
     * if set to true, null values won't be dumped
     *
     * @param boolean $skipNullValues
     */
    public function setSkipNullValues($skipNullValues)
    {
        $this->skipNullValues = $skipNullValues;
    }

    /**
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param array|null                                         $models
     * @param array                                              $options
     *
     * @return string
     */
    public function generate(ClassMetadata $metadata, array $models = null, array $options = array())
    {
        $resolver = new OptionsResolver();
        $resolver->setRequired($this->getRequiredOptions());
        $this->setDefaultOptions($resolver);
        $options = $resolver->resolve($options);
        if (null === $models) {
            $models = $this->getModels($metadata);
        }

        $preparedData = array();
        foreach ($models as $model) {
            $data = array();
            $data['fields'] = $this->processFieldNames($metadata, $model);
            $data['associations'] = $this->processAssociationNames($metadata, $model);

            $preparedData[$this->namingStrategy->modelName($model, $metadata)] = $data;
        }

        return $this->doGenerate($metadata, $preparedData, $options);
    }

    /**
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    public function setDefaultOptions(OptionsResolver $resolver)
    {}

    /**
     * @return array
     */
    public function getRequiredOptions()
    {
        return array();
    }

    /**
     * @param \Sp\FixtureDumper\Converter\VisitorInterface $visitor
     */
    public function setVisitor(VisitorInterface $visitor)
    {
        $this->visitor = $visitor;
    }

    /**
     * @return \Sp\FixtureDumper\Converter\VisitorInterface
     */
    public function getVisitor()
    {
        return $this->visitor;
    }

    /**
     * @param \Sp\FixtureDumper\Converter\DefaultNavigator $navigator
     */
    public function setNavigator($navigator)
    {
        $this->navigator = $navigator;
    }

    /**
     * @return \Sp\FixtureDumper\Converter\DefaultNavigator
     */
    public function getNavigator()
    {
        return $this->navigator;
    }

    /**
     * @param \Doctrine\Common\Persistence\ObjectManager $manager
     */
    public function setManager($manager)
    {
        $this->manager = $manager;
    }

    /**
     * @throws \RuntimeException
     * @return \Doctrine\Common\Persistence\ObjectManager
     */
    public function getManager()
    {
        if (null === $this->manager) {
            throw new \RuntimeException(sprintf('No manager was configured for the class "%s%, use "%s" to set one.', __CLASS__, 'setManager'));
        }

        return $this->manager;
    }

    /**
     * @param \Sp\FixtureDumper\Generator\NamingStrategyInterface $namingStrategy
     */
    public function setNamingStrategy($namingStrategy)
    {
        $this->namingStrategy = $namingStrategy;
    }

    /**
     * @return \Sp\FixtureDumper\Generator\NamingStrategyInterface
     */
    public function getNamingStrategy()
    {
        return $this->namingStrategy;
    }

    /**
     * Prepares the given fixture for writing to a file.
     *
     * @param $fixture
     *
     * @return mixed
     */
    public function prepareForWrite($fixture)
    {
        return $fixture;
    }

    /**
     * Creates the filename for this fixture.
     *
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param bool                                               $multipleFiles
     *
     * @return mixed
     */
    abstract public function createFilename(ClassMetadata $metadata, $multipleFiles = true);

    /**
     * Generates the fixture for the specified metadata.
     *
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param array                                              $data
     * @param array                                              $options
     *
     * @return string
     */
    abstract protected function doGenerate(ClassMetadata $metadata, array $data, array $options = array());

    /**
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param                                                    $model
     *
     * @return array
     */
    protected function processFieldNames(ClassMetadata $metadata, $model)
    {
        $data = array();
        foreach ($metadata->getFieldNames() as $fieldName) {
            if ($metadata->isIdentifier($fieldName) && $metadata->usesIdGenerator()) {
                continue;
            }

            $value = $this->readProperty($model, $fieldName);
            if ($this->skipNullValues && $value === null) {
                continue;
            }

            $data[$fieldName] = $this->navigator->accept($this->getVisitor(), $value);
        }

        foreach ($this->fieldNamesPostProcessors as $postProcessor) {
            /** @var FieldNamesPostProcessorInterface $postProcessor */
            if ($postProcessor->supports($model, $metadata, $data)) {
                $data = $postProcessor->getData($model, $metadata, $data);
            }
        }

        return $data;
    }

    /**
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param                                                    $model
     *
     * @return array
     */
    protected function processAssociationNames(ClassMetadata $metadata, $model)
    {
        $data = array();
        foreach ($metadata->getAssociationNames() as $assocName) {
            $propertyValue = $this->readProperty($model, $assocName);
            if (null === $propertyValue || $metadata->isAssociationInverseSide($assocName)) {
                continue;
            }

            if ($metadata->isSingleValuedAssociation($assocName)) {
                $assocValue = $this->namingStrategy->modelName($propertyValue, $this->getManager()->getClassMetadata(get_class($propertyValue)));
                $assocValue = $this->navigator->accept($this->getVisitor(), $assocValue, 'reference');
                $data[$assocName] = $assocValue;
            } else {
                $data[$assocName] = array();
                foreach ($propertyValue as $value) {
                    $assocValue = $this->namingStrategy->modelName($value, $this->getManager()->getClassMetadata(get_class($value)));
                    $assocValue = $this->navigator->accept($this->getVisitor(), $assocValue, 'reference');
                    $data[$assocName][] = $assocValue;
                }
            }
        }

        return $data;
    }

    /**
     * @return \Sp\FixtureDumper\Converter\VisitorInterface
     */
    protected function getDefaultVisitor()
    {
        return new DefaultVisitor();
    }

    /**
     * @return DefaultNamingStrategy
     */
    protected function getDefaultNamingStrategy()
    {
        return new DefaultNamingStrategy();
    }

    /**
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     *
     * @return array
     */
    protected function getModels(ClassMetadata $metadata)
    {
        return $this->getManager()->getRepository($metadata->getName())->findAll();
    }

    /**
     * Reads a property from an object.
     *
     * @param $object
     * @param $property
     *
     * @return mixed
     * @throws InvalidPropertyException
     */
    protected function readProperty($object, $property)
    {
        foreach ($this->propertyReader as $reader) {
            /** @var PropertyReaderInterface $reader */
            if ($reader->supports($object, $property)) {
                return $reader->getValue($object, $property);
            }
        }

        $camelProp = ucfirst($property);
        $getter = 'get'.$camelProp;
        $isser = 'is'.$camelProp;

        if (method_exists($object, $getter)) {
            return $object->$getter();
        } elseif (method_exists($object, $isser)) {
            return $object->$isser();
        } elseif (property_exists($object, $property)) {
            $reflectionProperty = new \ReflectionProperty($object, $property);
            $reflectionProperty->setAccessible(true);

            return $reflectionProperty->getValue($object);
        }

        throw new InvalidPropertyException(sprintf('Neither property "%s" nor method "%s()" nor method "%s()" exists in class "%s"', $property, $getter, $isser, get_class($object)));
    }
}


<?php

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 LinguaLeo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace LinguaLeo\Cache\Provider;

use \Memcached;

use LinguaLeo\Cache\Exception\AtomicViolationException;

class MemCache extends CacheProvider
{
    /**
     * Memcached instance
     * @var Memcached
     */
    protected $memcached;

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

    /**
     * {@inheritdoc}
     */
    public function get($key)
    {
        return $this->memcached->get($key);
    }

    /**
     * {@inheritdoc}
     */
    public function mget(array $keys)
    {
        return $this->memcached->getMulti($keys);
    }

    /**
     * {@inheritdoc}
     */
    public function mset(array $data, $ttl = 0)
    {
        if ($this->memcached->setMulti($data, $ttl)) {
            return count($data);
        }
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $data, $ttl = 0)
    {
        return $this->memcached->set($key, $data, $ttl);
    }

    /**
     * {@inheritdoc}
     */
    public function add($key, $data, $ttl = 0)
    {
        return $this->memcached->add($key, $data, $ttl);
    }

    /**
     * {@inheritdoc}
     */
    public function create($key, callable $modifier, $ttl = 0)
    {
        list($data, $token) = $this->get_with_cas($key);
        if (false === $data) {
            $modifier($data);
            $result = $this->memcached->add($key, $data, $ttl);
        } else {
            $modifier($data);
            $result = $this->memcached->cas($token, $key, $data, $ttl);
        }
        if (!$result) {
            throw new AtomicViolationException(
                sprintf(
                    'Atomic violation occurred "%s" when adding the key "%s" with the token "%g".',
                    $this->memcached->getResultMessage(),
                    $key,
                    $token
                )
            );
        }
        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function update($key, callable $modifier, $ttl = 0)
    {
        list($data, $token) = $this->get_with_cas($key);
        if (false === $data) {
            return false;
        }
        $modifier($data);
        if ($this->memcached->cas($token, $key, $data, $ttl)) {
            return $data;
        }
        throw new AtomicViolationException(
            sprintf(
                'Atomic violation occurred "%s" when updating the key "%s" with the token "%g".',
                $this->memcached->getResultMessage(),
                $key,
                $token
            )
        );
    }

    protected function get_with_cas($key)
    {
        if (defined('Memcached::GET_EXTENDED')) { // php-memcached >= 3.0.0a1 (?)
            $entry = $this->memcached->get($key, null, Memcached::GET_EXTENDED);
            $value  = $entry['value'] ?? false;
            $cas    = $entry['cas']   ?? null;
        } else {
            $cas = null;
            $value = $this->memcached->get($key, null, $cas);
        }
        return [$value, $cas];
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        return $this->memcached->delete($key);
    }

    /**
     * {@inheritdoc}
     */
    public function increment($key, $value = 1)
    {
        if ($value < 1) {
            throw new \InvalidArgumentException('Value of incrementation must be greater that nil.');
        }
        $result = $this->memcached->increment($key, $value);
        if (false === $result) {
            if (false === $this->add($key, $value)) {
                throw new AtomicViolationException(sprintf('In incremention can\'t add key "%s".', $key));
            }
            $result = $value;
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        return $this->memcached->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function mdelete(array $keys)
    {
        $count = 0;
        /**
         * @array An array with a keys which was deleted, the value if the operation was successful true,
         * otherwise the value that was set in the method deleteMulti
         */
        $results = $this->memcached->deleteMulti($keys);
        foreach ($results as $key => $result) {
            if ($result === true) {
                $count++;
            }
        }
        return $count;
    }

}


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNetcoreSettingSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('netcore_setting__settings', function (Blueprint $table) {
            $table->increments('id');
            $table->string('group')->nullable();
            $table->string('name')->nullable();
            $table->string('key')->unique()->index();
            $table->string('type')->default('text');
            $table->text('meta')->nullable();
            $table->boolean('has_manager')->default(0);
            $table->boolean('is_translatable')->default(0);
            $table->timestamps();
        });

        Schema::create('netcore_setting__setting_translations', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('setting_id');
            $table->foreign('setting_id')->references('id')->on('netcore_setting__settings')->onDelete('cascade');

            $table->string('locale')->index();
            $table->mediumText('value')->nullable();
        });
    }

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


<?php

/*
 * This file is part of the FixtureDumper library.
 *
 * (c) Martin Parsiegla <martin.parsiegla@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sp\FixtureDumper\Generator;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;

/**
 * Base class for generating fixtures for the alice library.
 *
 * @author Martin Parsiegla <martin.parsiegla@gmail.com>
 */
abstract class AbstractAliceGenerator extends AbstractGenerator
{

    /**
     * {@inheritdoc}
     */
    protected function doGenerate(ClassMetadata $metadata, array $data, array $options = array())
    {
        foreach ($data as $modelName => $values) {
            $data[$modelName] = array_merge($values['fields'], $values['associations']);
        }

        return $this->prepareData($metadata, $data);
    }

    /**
     * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata
     * @param array                                              $data
     *
     * @return mixed
     */
    abstract protected function prepareData(ClassMetadata $metadata, array $data);
}


<?php

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 LinguaLeo
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace LinguaLeo\Cache\Provider;

use LinguaLeo\Cache\Exception\AtomicViolationException;

class RedisCache extends CacheProvider
{
    /**
     * @var \Redis|\RedisArray
     */
    protected $redis;

    /**
     * @param \Redis|\RedisArray $redis
     */

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

    /**
     * {@inheritdoc}
     */
    public function get($key)
    {
        return $this->redis->get($key);
    }

    /**
     * {@inheritdoc}
     */
    public function set($key, $data, $ttl = 0)
    {
        if ($ttl > 0) {
            return $this->redis->setex($key, (int)$ttl, $data);
        }
        return $this->redis->set($key, $data);
    }

    /**
     * {@inheritdoc}
     */
    public function create($key, callable $modifier, $ttl = 0)
    {
        $this->redis->watch($key);
        $data = $this->redis->get($key);
        $modifier($data);
        if ($this->setInTransaction($key, $data, (int)$ttl)) {
            return $data;
        }
        throw new AtomicViolationException("Atomic violation occurred when adding key \"{$key}\".");
    }

    /**
     * {@inheritdoc}
     */
    public function update($key, callable $modifier, $ttl = 0)
    {
        $this->redis->watch($key);
        $data = $this->redis->get($key);
        if ($data === false) {
            $this->redis->unwatch();
            return false;
        } else {
            $modifier($data);
            if ($this->setInTransaction($key, $data, (int)$ttl)) {
                return $data;
            }
        }
        throw new AtomicViolationException("Atomic violation occurred when updating key \"{$key}\".");
    }

    /**
     * @param string $key
     * @param mixed $data
     * @param int $ttl
     * @return bool
     */
    private function setInTransaction($key, $data, $ttl = 0)
    {
        if ($ttl > 0) {
            $result = $this->multi($key)
                ->setex($key, (int)$ttl, $data)
                ->exec();
        } else {
            $result = $this->multi($key)
                ->set($key, $data)
                ->exec();
        }
        return $result !== false;
    }

    /**
     * {@inheritdoc}
     */
    public function delete($key)
    {
        return (bool)$this->redis->delete($key);
    }

    /**
     * {@inheritdoc}
     */
    public function mdelete(array $keys)
    {
        return $this->redis->delete($keys);
    }

    /**
     * {@inheritdoc}
     */
    public function flush()
    {
        return $this->redis->flushDB();
    }

    /**
     * {@inheritdoc}
     */
    public function increment($key, $value = 1)
    {
        if ($value < 1) {
            throw new \InvalidArgumentException('Value of incrementation must be greater that nil.');
        }
        if ($value === 1) {
            return $this->redis->incr($key);
        }
        return $this->redis->incrBy($key, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function mget(array $keys)
    {
        $result = array();
        $keys = array_values($keys);

        $values = $this->redis->mget($keys);
        foreach ($values as $i => $value) {
            if ($value !== false) {
                $result[$keys[$i]] = $value;
            }
        }
        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function mset(array $data, $ttl = 0)
    {
        if ($ttl === 0) {
            if ($this->redis->mset($data)) {
                return count($data);
            }
            return 0;
        }
        $count = 0;
        foreach ($data as $key => $value) {
            if ($this->set($key, $value, $ttl)) {
                $count++;
            }
        }
        return $count;
    }

    /**
     * {@inheritdoc}
     */
    public function add($key, $data, $ttl = 0)
    {
        if ($ttl > 0) {
            $uid = uniqid('temp_key', true);
            $result = $this->multi($key)
                ->setex($uid, (int)$ttl, $data)
                ->renameNx($uid, $key)
                ->delete($uid)
                ->exec();
            return !empty($result[1]);
        }
        return $this->redis->setnx($key, $data);
    }

    /**
     * @param string $key
     * @return \Redis
     */
    protected function multi($key)
    {
        if ($this->redis instanceof \RedisArray) {
            $host = $this->redis->_target($key);
            return $this->redis->multi($host);
        }
        return $this->redis->multi();
    }
}


<?php

use Potter\Theme\Options;

class OPT
{
    /**
     * @var Options
     */
    private static $instance = null;

    public static function setInstanse(Options $instance)
    {
        self::$instance = $instance;
    }

    /**
     * @param string $option
     * @param string $default
     *
     * @return null|string
     */
    public static function get($option, $default = null)
    {
        return ot_get_option($option, $default);
    }

    /**
     * @param string $option
     * @param string $default
     *
     * @return void
     */
    public static function _get($option, $default = null)
    {
        echo self::get($option, $default);
    }

    /**
     * @param        $option
     * @param string $default
     *
     * @return string
     */
    public static function get_nl2br($option, $default = null)
    {
        return nl2br(self::get($option, $default));
    }

    /**
     * @param string $option
     * @param null   $default
     *
     * @return void
     */
    public static function _get_nl2br($option, $default = null)
    {
        echo self::get_nl2br($option, $default);
    }

    /**
     * @param   string $option
     * @param   string $size
     * @param string   $default
     *
     * @return null|string
     */
    public static function get_optImg($option, $size, $default = null)
    {
        $id = self::get($option, $default);
        if (empty($id)):
            return null;
        endif;

        $image = wp_get_attachment_image_src($id, $size);

        return array_get($image, 0, null);
    }

    /**
     * @param string $name
     * @param array  $args
     *
     * @return null|string
     */
    public static function __callStatic($name, $args)
    {
        $default = (empty($args)) ? null : $args[0];

        return self::get($name, $default);
    }

    /**
     * @return Options
     */
    public static function getInstance()
    {
        return self::$instance;
    }

}

/**
 * @param string $str
 *
 * @return string
 */
function cleanURI($str)
{
    return preg_replace('/([^:])(\/{2,})/', '$1/', $str);
}

/**
 * @param null $path
 *
 * @return string
 */
function theme_url($path = null)
{
    return cleanURI(THEME_URL . $path);
}