<?php

namespace Ntavelis\AuthEmail\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Ntavelis\AuthEmail\Commands\Actions\Actions;
use Ntavelis\AuthEmail\Commands\Actions\ShouldQueue;

class AuthEmail extends Command {

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auth:email {--o|only : Do not run make:auth command. }
                                        {--m|migrate : After setup run migrations. }
                                        {--s|queue : The Activation Email should queue. }';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generates Email Authentication on top of artisan\'s make:auth command.';

    /**
     * @var Composer
     */
    private $composer;

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->composer = app()['composer'];
    }

    /**
     * Execute the console command.
     *
     * @param Actions $actions
     */
    public function handle(Actions $actions)
    {
        /**
         * Unless flag --only is passed, call the `make:auth` artisan command.
         */
        if (!$this->option('only')) {
            $this->call('make:auth');
        }

        /**
         * If flag --queue is passed, make the mailable implement ShouldQueue interface.
         */
        if ($this->option('queue')) {
            ShouldQueue::$bool = true;
        }

        /**
         * We iterate through all the Actions and
         * execute run() method on each one.
         */
        foreach ($actions->actions as $action) {
            $action->run();
        }

        /**
         * If the flag --migrate is passed, call the `migrate` artisan command.
         */
        if ($this->option('migrate')) {
            $this->call('migrate');
        }

        $this->Success();
    }

    /**
     * Show success message and run composer dump-autoload.
     */
    private function Success()
    {
        $migrated = '';

        if ($this->option('migrate')) {
            $migrated = ' and migrated database';
        }

        $this->info('Email authentication generated successfully' . $migrated . '.');

        $this->composer->dumpAutoloads();
    }
}


<?php
/**
 * @link https://github.com/borodulin/yii2-i18n-google
 * @copyright Copyright (c) 2015 Andrey Borodulin
 * @license https://github.com/borodulin/yii2-i18n-google/blob/master/LICENSE
 */

namespace conquer\i18n\models;

use conquer\i18n\Module;
use yii\helpers\ArrayHelper;
use yii\db\Query;

/**
 * This is the model class for table "{{%i18n_message}}".
 *
 * @property integer $message_id
 * @property string $category
 * @property string $message
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property I18nTranslation[] $i18nTranslations
 *
 * @author Andrey Borodulin
 */
class I18nMessage extends \yii\db\ActiveRecord
{

    private static $_messages;

    public static function tableName()
    {
        return '{{%i18n_message}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['category', 'message'], 'required'],
            [['message'], 'string'],
            [['created_at', 'updated_at'], 'integer'],
            [['category'], 'string', 'max' => 32]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'message_id' => 'Message ID',
            'category' => 'Category',
            'message' => 'Message',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function behaviors()
    {
        return [
            ['class' => \yii\behaviors\TimestampBehavior::className()],
        ];
    }

    /**
     * @param string $category
     * @param string $message
     * @return \conquer\i18n\models\I18nMessage
     */
    public static function getMessage($category, $message)
    {
        $i18nMessage = I18nMessage::findOne([
            'category' => $category,
            'message' => $message,
        ]);

        if(empty($i18nMessage)){
            $i18nMessage = new I18nMessage([
                'category' => $category,
                'message' => $message,
            ]);
            $i18nMessage->save(false);
        }

        return $i18nMessage;
    }
    /**
     *
     * @param string $language
     * @param I18nTranslator $translator
     * @return \conquer\i18n\models\I18nTranslation
     */
    public function getTranslation($language)
    {
        $i18nTranslation= I18nTranslation::findOne([
            'message_id' => $this->message_id,
            'language' => $language,
        ]);

        if(empty($i18nTranslation)){
            $i18nTranslation = new I18nTranslation([
                'message_id' => $this->message_id,
                'language' => $language,
            ]);
        }
        return $i18nTranslation;
    }

    /**
     * Loads the messages from database.
     *
     * @param string $category the message category.
     * @param string $language the target language.
     * @return array the messages loaded from database.
     */
    public static function loadMessagesFromDb($category, $language)
    {
        $mainQuery = new Query();
        $mainQuery->select(['t1.message', 't2.translation'])
            ->from([I18nMessage::tableName().' t1', I18nTranslation::tableName().' t2'])
            ->where('t1.message_id = t2.message_id AND t1.category = :category AND t2.language = :language')
            ->params([':category' => $category, ':language' => $language]);

        $messages = $mainQuery->createCommand()->queryAll();

        return ArrayHelper::map($messages, 'message', 'translation');
    }

}


<?php
/**
 * Analyze PHP Framework
 *
 * @link https://github.com/AnalyzePHP/framework
 * @copyright Copyright (C) 2018 Matt Sparks
 * @license MIT <https://github.com/AnalyzePHP/framework/blob/master/LICENSE>
 */
namespace Analyze\Container;

use Closure;
use Psr\Container\ContainerInterface;
use Analyze\Container\Definitions\ClassDefinition;
use Analyze\Container\Exceptions\NotFoundException;
use Analyze\Container\Definitions\SetterDefinition;
use Analyze\Container\Definitions\FactoryDefinition;
use Analyze\Container\Definitions\DefinitionInterface;

class Container implements ContainerInterface
{
    /**
     * Arguments
     * @var array
     */
    private $arguments = [];

    /**
     * Definitions
     * @var array
     */
    private $definitions = [];

    /**
     * Add
     *
     * Adds a definition to the $definition array.
     *
     * @param string              $alias
     * @param DefinitionInterface $definition
     */
    public function add(string $alias, DefinitionInterface $definition) : void
    {
        $this->definitions[$alias] = $definition;
    }

    /**
     * Add Class
     *
     * Add a class to the container.
     *
     * @param string $alias
     * @param string $concrete
     */
    public function addClass(string $alias, string $concrete) : void
    {
        $definition = new ClassDefinition($concrete);

        $this->add($alias, $definition);
    }

    /**
     * Add Factory
     *
     * Adds a factory definition to the container.
     *
     * @param string  $alias
     * @param Closure $callback
     */
    public function addFactory(string $alias, Closure $callback) : void
    {
        $definition = new FactoryDefinition($callback);

        $this->add($alias, $definition);
    }

    /**
     * Add Setter
     *
     * @param string $alias
     * @param string $concrete
     * @param array  $methods
     */
    public function addSetter(string $alias, string $concrete, array $methods) : void
    {
        $definition = new SetterDefinition($concrete, $methods);

        $this->add($alias, $definition);
    }

    /**
     * Get
     *
     * Returns the passed alias.
     *
     * @param  string $id
     * @return mixed
     * @throws NotFoundException
     */
    public function get($id)
    {
        if (!$this->has($id)) {
            throw new NotFoundException(sprintf('%s is not defined.', $id));
        }

        $definition = $this->definitions[$id];
        $definition->addArguments($this->arguments);

        return $definition->build();
    }

    /**
     * Has
     *
     * Does the given alias exist in the container?
     *
     * @param  string $id
     * @return bool
     */
    public function has($id) : bool
    {
        return array_key_exists($id, $this->definitions);
    }

    /**
     * With Arguments
     *
     * Pass arguments to a definition.
     *
     * @param  array $args
     * @return self
     */
    public function withArguments(array $args) : self
    {
        $this->arguments = $args;

        return $this;
    }
}


<?php

namespace Ntavelis\AuthEmail;

use App\User;
use Ntavelis\AuthEmail\Repository\Activation;
use Ntavelis\AuthEmail\Repository\ActivationInterface;
use Ntavelis\AuthEmail\Services\Interfaces\Email;

/**
 * Class ActivationService
 * @package App
 */
class EmailService {

    /**
     * Instance of the class that implements Activation Interface
     * @var Activation
     */
    protected $activationRepo;

    /**
     * Hours to pass before resending is possible.
     * @var int
     */
    protected $resendAfter = 6;

    /**
     * Gets the instance of the class that implements Email interface
     * @var Email
     */
    protected $mailer;

    /**
     * ActivationService constructor.
     * @param ActivationInterface $activationRepo
     * @param Email $mailer
     */
    public function __construct(ActivationInterface $activationRepo, Email $mailer)
    {
        $this->activationRepo = $activationRepo;
        $this->mailer = $mailer;
    }

    /**
     * Sends activation mail.
     * @param $user
     */
    public function sendActivationMail($user)
    {

        if ($user->activated || !$this->shouldSend($user)) {
            return;
        }

        $token = $this->activationRepo->createActivation($user);

        $link = route('user.activate', $token);

        $this->mailer->sendTo($user, $link);
    }

    /**
     * Activates the user.
     * @param $token
     * @return mixed|null
     */
    public function activateUser($token)
    {
        $activation = $this->activationRepo->getActivationByToken($token);

        if ($activation === null) {
            return null;
        }

        $user = User::find($activation->user_id);

        $user->activated = true;

        $user->save();

        $this->activationRepo->deleteActivation($token);

        return $user;

    }

    /**
     * Calculate when it is appropriate to resend the activation mail.
     * @param $user
     * @return bool
     */
    private function shouldSend($user)
    {
        $activation = $this->activationRepo->getActivation($user);

        return $activation === null || strtotime($activation->created_at) + 60 * 60 * $this->resendAfter < time();
    }

}


<?php namespace Fuzzy;

class Fuzzy {

    /**
     * Perform a fuzzy string searching.
     *
     * @param array $rows
     * @param string $query
     * @param integer $threshold
     * @return array
     */
    public function search(array $rows, $query, $threshold = 3)
    {
        $matched = [];

        foreach($rows as $row)
        {
            $distance = $this->calculateDistance($query, $row);

            if ($threshold >= $distance)
            {
                $matched[] = [$distance, $row];
            }
        }

        return $this->transformResult($this->sortMatchedStrings($matched));
    }

    /**
     * Calculate the Levenshtein distance between two strings.
     *
     * @param string $one
     * @param string $two
     * @return int
     */
    protected function calculateDistance($one, $two)
    {
        return levenshtein($one, $two);
    }

    /**
     * Sort the matched strings.
     *
     * @param array $matched
     * @return array
     */
    protected function sortMatchedStrings(array $matched)
    {
        usort($matched, function(array $left, array $right)
        {
            return ($left[0] - $right[0]);
        });

        return $matched;
    }

    /**
     * Transform a given array of matches.
     *
     * @param array $matched
     * @return array
     */
    protected function transformResult(array $matched)
    {
        $iterator = function(array $element)
        {
            return $element[1];
        };

        return array_map($iterator, $matched);
    }

}


<?php

namespace Cundd\Noshi\Ui;

use Cundd\Noshi\Ui\Exception\InvalidExpressionException;
use Cundd\Noshi\Utilities\ObjectUtility;

/**
 * A simple template
 *
 * @package Cundd\Noshi\Ui
 */
class Template extends AbstractUi
{
    /**
     * Data
     *
     * @var array
     */
    protected $data = [];

    /**
     * Raw template data to be parsed
     *
     * @var string
     */
    protected $template = '';

    /**
     * Assign value for variable key
     *
     * @param string $key
     * @param mixed  $value
     * @return $this
     */
    public function assign($key, $value)
    {
        $this->data[$key] = $value;

        return $this;
    }

    /**
     * Assign multiple values
     *
     * @param array $values
     * @return $this
     */
    public function assignMultiple($values)
    {
        $this->data = array_merge($this->data, (array)$values);
    }

    /**
     * Renders the template
     *
     * @throws Exception\InvalidExpressionException if the rendered expression can not be converted to a string
     * @return string
     */
    public function render()
    {
        $template = $this->getTemplate();

        // Find the expressions
        $matches = [];
        if (!preg_match_all('!\{([\w\.\\\ \/]*)\}!', $template, $matches)) {
            return $template;
        }

        $expressions = $matches[1];
        $expressions = array_unique($expressions);
        foreach ($expressions as $expression) {
            $renderedExpression = $this->renderExpression($expression);
            if (is_object($renderedExpression) && !method_exists($renderedExpression, '__toString')) {
                throw new InvalidExpressionException(
                    'Could not convert object of class ' . get_class(
                        $renderedExpression
                    ) . ' for expression ' . $expression . ' to string', 1401543101
                );
            }
            $template = str_replace('{' . $expression . '}', $renderedExpression, $template);
        }

        return $template;
    }

    /**
     * Renders the given expression
     *
     * @param string $expression
     * @return string
     */
    public function renderExpression($expression)
    {
        if (strpos($expression, '\\') !== false) {
            $expressionParts = explode(' ', $expression);
            $viewClass = '\\' . array_shift($expressionParts);

            /** @var UiInterface $newView */
            if (!class_exists($viewClass)) {
                return '<!-- view class ' . $viewClass . ' not found -->';
            }
            $newView = new $viewClass();
            if ($newView instanceof UiInterface) {
                $newView->setContext($this);
                if ($expressionParts) {
                    return call_user_func_array([$newView, 'render'], $expressionParts);
                }

                return $newView->render();
            }
            try {
                return (string)$newView;
            } catch (\Exception $exception) {
            }
        } else {
            if (substr($expression, 0, 2) === '//') { // Handle expressions like "{//please.output.me}"

            }
        }

        return $this->resolveExpressionKeyPath($expression);
    }

    /**
     * Returns the assigned variable value
     *
     * @param string $keyPath
     * @return string
     */
    public function resolveExpressionKeyPath($keyPath)
    {
        if (isset($this->data[$keyPath])) {
            return $this->data[$keyPath];
        }

        return ObjectUtility::valueForKeyPathOfObject($keyPath, $this->data);
    }

    /**
     * Returns the raw template
     *
     * @return string
     */
    public function getTemplate()
    {
        return $this->template;
    }

    /**
     * Sets the raw template
     *
     * @param string $template
     * @return $this
     */
    public function setTemplate($template)
    {
        $this->template = $template;

        return $this;
    }
}


<?php

namespace Darsyn\ClassFinder;

use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\KernelInterface;

/**
 * @author Zander Baldwin <hello@zanderbaldwin.com>
 */
class BundleClassFinder extends ClassFinder implements BundleAwareInterface
{
    /**
     * @access protected
     * @var \SplObjectStorage
     */
    protected $bundles;

    /**
     * Constructor
     *
     * @access public
     * @param \Symfony\Component\HttpKernel\KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel = null)
    {
        $this->bundles = new \SplObjectStorage;
        if ($kernel instanceof KernelInterface) {
            $this->setBundles($kernel->getBundles());
        }
    }

    /**
     * Set Bundles
     *
     * @access public
     * @param array $bundles
     * @return self
     */
    public function setBundles(array $bundles)
    {
        $this->bundles = new \SplObjectStorage;
        foreach ($bundles as $bundle) {
            if ($bundle instanceof BundleInterface) {
                $this->addBundle($bundle);
            }
        }
        return $this;
    }

    /**
     * Add Bundle
     *
     * @access public
     * @param \Symfony\Component\HttpKernel\Bundle\BundleInterface $bundle
     * @return self
     */
    public function addBundle(BundleInterface $bundle)
    {
        $this->bundles->attach($bundle);
        return $this;
    }

    /**
     * Find Classes in Bundles
     *
     * @access public
     * @param string $subDir
     * @param string $suffix
     * @param string $parent
     * @param boolean $reflection
     * @return array
     */
    public function findClasses($subDir = null, $suffix = null, $parent = null, $reflection = false)
    {
        $classes = [];
        foreach ($this->bundles as $bundle) {
            $this->setRootDirectory($bundle->getPath());
            $this->setRootNamespace($bundle->getNamespace());
            $classes = array_merge($classes, parent::findClasses($subDir, $suffix, $parent, $reflection));
        }
        return $classes;
    }
}


<?php

namespace Cundd\Noshi;

use Cundd\Noshi\Exception\SecurityException;

/**
 * Configuration container
 *
 * @method string getBasePath()
 * @method string getDataPath()
 * @method string getTemplatePath()
 */
class Configuration implements \ArrayAccess
{
    /**
     * @var bool
     */
    protected $_useVendorDirectory = true;

    /**
     * @var array
     */
    protected $configuration = [
        'dataPath'     => 'data/',
        'dataSuffix'   => 'md',
        'templatePath' => 'Resources/Private/Templates/',
        'resourcePath' => 'Resources/Public/',

        'metaData' => [
            'title' => 'NoShi',
        ],
    ];

    function __construct($configuration = [])
    {
        $this->configuration = array_merge(
            $this->configuration,
            $this->prepareConfigurationArray((array)$configuration)
        );
        $this->_useVendorDirectory = file_exists($this->getThemePath());
    }

    /**
     * Prepare the configuration values
     *
     * Append a slash at the end of directory configurations
     *
     * @param array $configuration
     * @return array
     */
    private function prepareConfigurationArray(array $configuration)
    {
        $pathConfiguration = [
            'dataPath',
            'templatePath',
            'resourcePath',
        ];
        foreach ($pathConfiguration as $key) {
            if (isset($configuration[$key])) {
                $configuration[$key] = rtrim($configuration[$key], '/') . '/';
            }
        }

        return $configuration;
    }

    /**
     * Returns the base URL
     *
     * @return string
     */
    public function getBaseUrl()
    {
        $baseUrl = $this->_get('baseUrl');
        if (!$baseUrl) {
            $baseUrl = ''
                . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http')
                . '://'
                . $this->getHost()
                . '/';
        }

        $requestBasePath = $this->getRequestBasePath();
        if ($requestBasePath) {
            return $baseUrl . $requestBasePath;
        }

        return $baseUrl;
    }

    /**
     * Returns the sanitized hostname
     *
     * @throws Exception\SecurityException if the host could not be detected
     * @return string
     */
    public function getHost()
    {
        $host = '';

        if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] !== '0.0.0.0') {
            $host = $_SERVER['SERVER_NAME'];
            if (!$this->_validateHost($host)) {
                $host = '';
            }

            // Add the port
            if ($host && isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']) {
                $port = $_SERVER['SERVER_PORT'];
                if (ctype_digit($port)) {
                    $host .= ':' . $port;
                }
            }
        }

        if (!$host && isset($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
            if (!$this->_validateHost($host)) {
                $host = '';
            }
        }
        if (!$host) {
            throw new SecurityException('Host could not be detected', 1394796366);
        }

        return $host;
    }

    /**
     * Returns if the given host is valid
     *
     * @param string $host
     * @return boolean
     */
    protected function _validateHost($host)
    {
        // Remove any dash ('-'), dot ('.') and colon (':', allowed because of the port)
        return ctype_alnum(str_replace(['-', '.', ':'], '', $host));
    }

    /**
     * Returns the path to the configured theme
     *
     * @return string
     */
    public function getThemePath()
    {
        return $this->get('basePath') .
            ($this->_useVendorDirectory ? 'vendor/' . $this->get('theme') : '')
            . '/';
    }

    /**
     * Returns the URI of the path to the configured theme
     *
     * @return string
     */
    public function getThemeUri()
    {
        return $this->getBaseUrl() .
            ($this->_useVendorDirectory ? 'vendor/' . $this->get('theme') : '')
            . '/';
    }

    /**
     * Returns the URI of the resource directory
     *
     * @return string
     */
    public function getResourceDirectoryUri()
    {
        return $this->getThemeUri() . $this->get('resourcePath');
    }

    /**
     * Returns the name of the subdirectory the project is installed in
     *
     * @return string
     */
    public function getRequestBasePath()
    {
        $trimmedBasePath = trim($this->_get('requestBasePath'), '/');

        if (!$trimmedBasePath) {
            return '/';
        }

        return '/'
            . $trimmedBasePath
            . '/';
    }

    /**
     * Returns if the website is in Development Mode
     *
     * @return bool
     */
    public function isDevelopmentMode()
    {
        return (bool)$this->get('developmentMode');
    }

    /**
     * Returns the configuration (without checking for an accessor method)
     *
     * @param string $key
     * @return mixed
     */
    protected function _get($key)
    {
        if (isset($this->configuration[$key])) {
            return $this->configuration[$key];
        }

        return null;
    }

    /**
     * Returns the configuration
     *
     * If an accessor method (i.e.: "getMyKey") is available it will be called
     *
     * @param string $key
     * @return mixed
     */
    public function get($key)
    {
        $accessorMethod = 'get' . ucfirst($key);
        if (method_exists($this, $accessorMethod)) {
            return $this->$accessorMethod();
        }

        return $this->_get($key);
    }

    /**
     * Set the configuration
     *
     * @param string $key
     * @param mixed  $value
     * @return $this
     */
    public function set($key, $value)
    {
        $this->configuration[$key] = $value;

        return $this;
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Whether a offset exists
     *
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $offset

     *                      An offset to check for.
     *

     * @return boolean true on success or false on failure.
     *

     *

     *                      The return value will be casted to boolean if non-boolean was returned.
     */
    public function offsetExists($offset)
    {
        return isset($this->configuration[$offset]);
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to retrieve
     *
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $offset

     *                      The offset to retrieve.
     *

     * @return mixed Can return all value types.
     */
    public function offsetGet($offset)
    {
        return $this->get($offset);
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to set
     *
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $offset

     *                      The offset to assign the value to.
     *

     * @param mixed $value

     *                      The value to set.
     *

     * @return void
     */
    public function offsetSet($offset, $value)
    {
        $this->set($offset, $value);
    }

    /**
     * (PHP 5 >= 5.0.0)

     * Offset to unset
     *
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $offset

     *                      The offset to unset.
     *

     * @return void
     */
    public function offsetUnset($offset)
    {
        $this->set($offset, null);
    }

    function __call($name, $arguments)
    {
        if (substr($name, 0, 3) === 'get') {
            return $this->get(lcfirst(substr($name, 3)));
        }

        return null;
    }
}


<?php
/**
 * @link https://github.com/borodulin/yii2-i18n-google
 * @copyright Copyright (c) 2015 Andrey Borodulin
 * @license https://github.com/borodulin/yii2-i18n-google/blob/master/LICENSE
 */

namespace conquer\i18n\translators;

use yii\base\Object;
use yii\base\InvalidConfigException;
use conquer\i18n\TranslatorInterface;
use conquer\helpers\CurlTrait;
use yii\helpers\Json;

/**
 *
 * @author Andrey Borodulin
 */
class GoogleTranslator extends Object implements TranslatorInterface
{
    use CurlTrait;

    public $apiKey;

    public $prettyprint = false;

    public function init()
    {
        parent::init();

        if(empty($this->apiKey))
            throw new InvalidConfigException('Google Api key required');
    }

    public function translate($text, $sourceLang, $targetLang, $format = 'text')
    {
        $this->setUrl('https://www.googleapis.com/language/translate/v2?'.http_build_query([
            'key' => $this->apiKey,
            'q' => $text,
            'source' =>$sourceLang,
            'target' => $targetLang,
            'format' => $format,
            'prettyprint' => $this->prettyprint,
        ]));
        $this->curl_execute();
        if($this->isHttpOK()){
            return isset($result['data']['translations'][0]['translatedText']) ?
                $result['data']['translations'][0]['translatedText'] : null;
        }
        return null;
    }

    public function languages()
    {
        $this->setUrl('https://www.googleapis.com/language/translate/v2/languages?'.http_build_query([
            'key' => $this->apiKey,
        ]));
        if($this->execute()){

        }
    }

        /**
         * Detect Language
         * @param string $text
        */
    public function detect($text)
    {
        $this->setUrl('https://www.googleapis.com/language/translate/v2/detect?'.http_build_query([
                'key' => $this->apiKey,
                'q' => $text,
        ]));
        if($this->execute()){

        }
    }

    public function getError()
    {
        return $this->_errorMessage ? $this->_errorMessage : $this->_content;
    }
}


<?php

namespace app\controllers;

use Yii;
use conquer\i18n\models\I18nTranslation;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * I18nTranslationController implements the CRUD actions for I18nTranslation model.
 */
class I18nTranslationController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all I18nTranslation models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => I18nTranslation::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single I18nTranslation model.
     * @param integer $message_id
     * @param string $language
     * @return mixed
     */
    public function actionView($message_id, $language)
    {
        if(Yii::$app->request->isAjax)
            return $this->renderAjax('view', [
                'model' => $this->findModel($message_id, $language),
            ]);
        else
            return $this->render('view', [
                'model' => $this->findModel($message_id, $language),
            ]);
    }

    /**
     * Creates a new I18nTranslation model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new I18nTranslation();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(Yii::$app->request->isAjax)
                return $this->redirect(['index']);
            else
                return $this->redirect(['view', 'message_id' => $model->message_id, 'language' => $model->language]);
        } else {
            if(Yii::$app->request->isAjax)
                return $this->renderAjax('create', [
                    'model' => $model,
                ]);
            else
                return $this->render('create', [
                    'model' => $model,
                ]);
        }
    }

    /**
     * Updates an existing I18nTranslation model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $message_id
     * @param string $language
     * @return mixed
     */
    public function actionUpdate($message_id, $language)
    {
        $model = $this->findModel($message_id, $language);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if(Yii::$app->request->isAjax)
                return $this->redirect(['index']);
            else
                return $this->redirect(['view', 'message_id' => $model->message_id, 'language' => $model->language]);
        } else {
            if(Yii::$app->request->isAjax)
                return $this->renderAjax('update', [
                    'model' => $model,
                ]);
            else
                return $this->render('update', [
                    'model' => $model,
                ]);
        }
    }

    /**
     * Deletes an existing I18nTranslation model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $message_id
     * @param string $language
     * @return mixed
     */
    public function actionDelete($message_id, $language)
    {
        $this->findModel($message_id, $language)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the I18nTranslation model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $message_id
     * @param string $language
     * @return I18nTranslation the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($message_id, $language)
    {
        if (($model = I18nTranslation::findOne(['message_id' => $message_id, 'language' => $language])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


<?php

namespace Cundd\Noshi\Command;

use Cundd\Noshi\Domain\Model\Page;
use Cundd\Noshi\Domain\Repository\PageRepository;

/**
 * NoshiCommandController
 *
 * @package Cundd\Noshi\Command
 */
class NoshiCommandController extends AbstractCommandController
{
    /**
     * Lists all pages
     */
    public function listPagesCommand()
    {
        $pageRepository = new PageRepository();
        $pages = $pageRepository->findAll();
        $tableData = [];
        /** @var Page $page */
        foreach ($pages as $page) {
            $tableData[] = [
                'identifier'   => $page->getIdentifier(),
                'title'        => $page->getTitle(),
                'is directory' => $page->getIsDirectory(),
                'is virtual'   => $page->getIsVirtual(),
                'sorting'      => $page->getSorting(),
            ];
        }
        $this->outputTable($tableData);
    }
}


<?php

namespace Cundd\Noshi\Domain\Model;

use Cundd\Noshi\Helpers\MarkdownFactory;
use Cundd\Noshi\Utilities\ObjectUtility;

/**
 * Page model
 *
 * @package Cundd\Noshi\Domain\Model
 */
class Page
{
    const DEFAULT_SORTING = 9000;

    /**
     * Character to replace whitespaces in the URI
     */
    const URI_WHITESPACE_REPLACE = '_';

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

    /**
     * Meta data
     *
     * @var array
     */
    protected $meta = [];

    /**
     * Raw content
     *
     * @var string
     */
    protected $rawContent = null;

    /**
     * Parsed content
     *
     * @var string
     */
    protected $parsedContent = '';

    /**
     * Sorting position in a menu
     *
     * @var int
     */
    protected $sorting;

    /**
     * Defines if the Page is a directory
     *
     * @var bool
     */
    protected $isDirectory = false;

    /**
     * Page URI
     *
     * @var string
     */
    protected $uri = '';

    function __construct($identifier = '', $rawContent = '', $meta = [])
    {
        $this->meta = $meta;
        $this->rawContent = $rawContent;
        $this->identifier = $identifier;
    }

    /**
     * Sets the page's unique identifier
     *
     * @param string $identifier
     * @return $this
     */
    public function setIdentifier($identifier)
    {
        $this->identifier = $identifier;

        return $this;
    }

    /**
     * Returns the page's unique identifier
     *
     * @return string
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * Sets the meta data
     *
     * @param array $meta
     * @return $this
     */
    public function setMeta($meta)
    {
        $this->meta = $meta;

        return $this;
    }

    /**
     * Returns the meta data
     *
     * @return array
     */
    public function getMeta()
    {
        return $this->meta;
    }

    /**
     * Sets the raw content
     *
     * @param string $rawContent
     * @return $this
     */
    public function setRawContent($rawContent)
    {
        $this->rawContent = $rawContent;
        $this->parsedContent = null;

        return $this;
    }

    /**
     * Returns the raw content
     *
     * @return string
     */
    public function getRawContent()
    {
        return $this->rawContent;
    }

    /**
     * Returns the parsed content
     *
     * @return string
     */
    public function getContent()
    {
        if (!$this->parsedContent) {
            $this->parsedContent = MarkdownFactory::getMarkdownRenderer()->transform($this->getRawContent());
        }

        return $this->parsedContent;
    }

    /**
     * Sets the sorting position in a menu
     *
     * @param int $sorting
     * @return $this
     */
    public function setSorting($sorting)
    {
        $this->sorting = $sorting;

        return $this;
    }

    /**
     * Returns the sorting position in a menu
     *
     * @return int
     */
    public function getSorting()
    {
        if (!$this->sorting) {
            $sorting = ObjectUtility::valueForKeyPathOfObject('meta.sorting', $this);
            if (!$sorting) {
                $sorting = self::DEFAULT_SORTING;
            }
            $this->sorting = $sorting;
        }

        return $this->sorting;
    }

    /**
     * Returns the URI of the page
     *
     * @return string
     */
    public function getUri()
    {
        if (!$this->uri) {
            if (($url = $this->_getUrlFromMeta())) {
                $this->uri = $url;
            } else {
                if ($this->getIsVirtual()) {
                    $this->uri = '#';
                } else {
                    $uriParts = explode(DIRECTORY_SEPARATOR, $this->getIdentifier());
                    array_walk(
                        $uriParts,
                        function (&$uriPart) {
                            $uriPart = urlencode($uriPart);
                        }
                    );
                    $this->uri = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $uriParts) . DIRECTORY_SEPARATOR;
                }
            }
        }

        return $this->uri;
    }

    /**
     * Returns the URL read from the meta data or NULL if it is not set
     *
     * @return string
     */
    protected function _getUrlFromMeta()
    {
        $url = ObjectUtility::valueForKeyPathOfObject('meta.url', $this);
        if (!$url) {
            return null;
        }
        if (substr($url, 0, 11) === '/Resources/') {
            return $url;
        }
        if (substr($url, 0, 10) === 'Resources/') {
            return $url;
        }
        if (strpos($url, '://') === false) {
            $url = 'http://' . $url;
        }

        return $url;
    }

    /**
     * Returns the pages title
     *
     * @return string
     */
    public function getTitle()
    {
        $title = ObjectUtility::valueForKeyPathOfObject('meta.title', $this);
        if (!$title) {
            $title = $this->getIdentifier();
            $slashPosition = strpos($title, DIRECTORY_SEPARATOR);
            if ($slashPosition !== false) {
                $title = substr($title, $slashPosition + 1);
            }
            $title = str_replace(self::URI_WHITESPACE_REPLACE, ' ', $title);
        }

        return $title;
    }

    /**
     * Sets if the Page is a directory
     *
     * @param boolean $isDirectory
     * @return $this
     */
    public function setIsDirectory($isDirectory)
    {
        $this->isDirectory = $isDirectory;

        return $this;
    }

    /**
     * Returns if the Page is a directory
     *
     * @return boolean
     */
    public function getIsDirectory()
    {
        return $this->isDirectory;
    }

    /**
     * Returns if the Page isn't a real Page
     *
     * A directory without an associated content file (i.e. "About/" exists but "About.md" do not) is virtual.
     *
     * @return boolean
     */
    public function getIsVirtual()
    {
        return $this->getRawContent() === null;
    }

    /**
     * Returns if the Page is an external link
     *
     * @return bool
     */
    public function getIsExternalLink()
    {
        return ObjectUtility::valueForKeyPathOfObject('meta.url', $this) ? true : false;
    }
}


<?php
namespace DevIT\Hasoffers;

use GuzzleHttp\Client as GuzzleClient;

class Client
{
    /**
     * API Base URL - Brand.
     *
     * @var string
     */
    private $apiUrlBrand = 'https://api.hasoffers.com/Apiv3/json?NetworkId=%s&Target=%s&Method=%s&NetworkToken=%s';

    /**
     * API Base URL - Affiliate.
     *
     * @var string
     */
    private $apiUrlAffiliate = 'https://api.hasoffers.com/Apiv3/json?NetworkId=%s&Target=%s_%s&Method=%s&api_key=%s';

    /**
     * HTTP Headers.
     *
     * @var array
     */
    private $headers = ['User-Agent' => 'DevIT-HasOffers/1.0.0'];

    /**
     * HTTP Client.
     *
     * @var object
     */
    private $httpClient;

    /**
     * API Key.
     *
     * @var string
     */
    private $apiKey;

    /**
     * Network ID.
     *
     * @var string
     */
    private $networkId;

    /**
     * API Type.
     *
     * @var string
     */
    private $apiType;

    /**
     * API Namespace.
     *
     * @var string
     */
    private $apiNamespace;

    /**
     * Constructor.
     *
     * @param string $apiKey
     * @param string $networkId
     */
    public function __construct($apiKey, $networkId = null)
    {
        $this->setApiKey($apiKey);

        $this->setNetworkId($networkId);

        $this->setHttpClient(new GuzzleClient([
            'defaults' => [
                'headers'  => $this->getHeaders(),
            ],
        ]));
    }

    /**
     * Initialize the given API class.
     *
     * @param string $class
     *
     * @return object
     */
    public function api($class)
    {
        $class = "DevIT\\Hasoffers\\Api\\".$class;

        return new $class($this);
    }

    /**
     * Send a GET request.
     *
     * @param string $apiMethod
     * @param array  $parameters
     *
     * @return object
     */
    public function get($apiMethod, $parameters = [])
    {
        $requestUrl = $this->buildUrl($apiMethod, $parameters);
        $requestUrl = urldecode($requestUrl);

        $response   = $this->getHttpClient()->get($requestUrl);

        return $this->handleResponse($response);
    }

    /**
     * Build the request url.
     *
     * @param string $apiMethod
     * @param array  $parameter
     *
     * @return string
     */
    private function buildUrl($apiMethod, $parameters)
    {
        switch ($this->getApiType()) {
            case 'Brand':
                $url = sprintf($this->apiUrlBrand, $this->getNetworkId(), $this->getApiNamespace(), $apiMethod, $this->getApiKey());
            break;

            case 'Affiliate':
                $url = sprintf($this->apiUrlAffiliate, $this->getNetworkId(), $this->getApiType(), $this->getApiNamespace(), $apiMethod, $this->getApiKey());
            break;
        }

        return $url.'&'.http_build_query($parameters);
    }

    /**
     * Handle the response.
     *
     * @param object $response
     *
     * @return object
     */
    private function handleResponse($response)
    {
        $statusCode = $response->getStatusCode();
        $body = json_decode($response->getBody());

        if ($statusCode >= 200 && $statusCode < 300) {
            return $body;
        }

        throw new \Exception($response->getBody(), $statusCode);
    }

    /**
     * Get the Affiliate API Base URL.
     *
     * @return string
     */
    public function getApiUrlAffiliate()
    {
        return $this->apiUrlAffiliate;
    }

    /**
     * Set the Affiliate API Base URL.
     *
     * @param string $apiUrlAffiliate
     */
    public function setApiUrlAffiliate($apiUrlAffiliate)
    {
        $this->apiUrlAffiliate = $apiUrlAffiliate;
    }

    /**
     * Get the Brand API Base URL.
     *
     * @return string
     */
    public function getApiUrlBrand()
    {
        return $this->apiUrlBrand;
    }

    /**
     * Set the Brand API Base URL.
     *
     * @param string $apiUrlBrand
     */
    public function setApiUrlBrand($apiUrlBrand)
    {
        $this->apiUrlBrand = $apiUrlBrand;
    }

    /**
     * Get the HTTP Headers.
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * Set the HTTP Headers.
     *
     * @param array $headers
     */
    public function setHeaders($headers)
    {
        $this->headers = $headers;
    }

    /**
     * Get the API Key.
     *
     * @return string
     */
    public function getApiKey()
    {
        return $this->apiKey;
    }

    /**
     * Set the API Key.
     *
     * @param string $apiKey
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * Get the Network ID.
     *
     * @return string
     */
    public function getNetworkId()
    {
        return $this->networkId;
    }

    /**
     * Set the Network ID.
     *
     * @param string $networkId
     */
    public function setNetworkId($networkId)
    {
        $this->networkId = $networkId;
    }

    /**
     * Get the API Type.
     *
     * @return string
     */
    public function getApiType()
    {
        return $this->apiType;
    }

    /**
     * Set the API Type.
     *
     * @param string $apiType
     */
    public function setApiType($apiType)
    {
        $this->apiType = $apiType;
    }

    /**
     * Get the API Namespace.
     *
     * @return string
     */
    public function getApiNamespace()
    {
        return $this->apiNamespace;
    }

    /**
     * Set the API Namespace.
     *
     * @param string $apiNamespace
     */
    public function setApiNamespace($apiNamespace)
    {
        $this->apiNamespace = $apiNamespace;
    }

    /**
     * Get the HTTP Client.
     *
     * @return object
     */
    public function getHttpClient()
    {
        return $this->httpClient;
    }

    /**
     * Set the HTTP Client.
     *
     * @param object $httpClient
     */
    public function setHttpClient($httpClient)
    {
        $this->httpClient = $httpClient;
    }
}


<?php

namespace Cundd\Noshi;

class ConfigurationManager
{
    /**
     * @var Configuration
     */
    static protected $sharedConfiguration;

    /**
     * Initializes the shared configuration
     *
     * @param string $basePath
     * @return Configuration
     */
    static public function initializeConfiguration($basePath)
    {
        // Read the configurations file
        $configuration = [];
        $configurationFile = $basePath . 'Configurations/Configuration.json';
        if (file_exists($configurationFile) && is_readable($configurationFile)) {
            $configuration = json_decode(file_get_contents($configurationFile), true);
        }

        self::$sharedConfiguration = new Configuration($configuration);
        self::$sharedConfiguration->set('basePath', $basePath);

        return self::$sharedConfiguration;
    }

    /**
     * Returns the shared configuration
     *
     * @return Configuration
     */
    static public function getConfiguration()
    {
        return self::$sharedConfiguration;
    }
}


<?php

namespace Cundd\Noshi\Utilities;

class DebugUtility
{
    /**
     * Print debug information about the given values (arg0, arg1, ... argN)
     *
     * @param $variable
     */
    static public function debug($variable)
    {
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10);
        $caller = $backtrace[1];

        echo PHP_EOL;
        echo '
';
        $variables = func_get_args();
        foreach ($variables as $variable) {
            var_dump($variable);
            echo PHP_EOL;
        }
        echo '';

        // Debug info
        $file = $caller['file'];
        $line = $caller['line'];
        echo "$file @ $line" . PHP_EOL;

        echo '
';
        echo PHP_EOL;

    }

}


<?php
/**
 * Analyze PHP Framework
 *
 * @link https://github.com/AnalyzePHP/framework
 * @copyright Copyright (C) 2018 Matt Sparks
 * @license MIT <https://github.com/AnalyzePHP/framework/blob/master/LICENSE>
 */
namespace Analyze\Container\Definitions;

use ReflectionClass;

class ClassDefinition extends AbstractDefinition
{
    /**
     * Concrete
     * @var string
     */
    private $concrete;

    /**
     * Constructor
     *
     * @param string $concrete
     */
    public function __construct(string $concrete)
    {
        $this->concrete = $concrete;
    }

    /**
     * Build
     *
     * @return object
     */
    public function build()
    {
        if ($this->hasArguments()) {
            $reflection = new ReflectionClass($this->concrete);

            return $reflection->newInstanceArgs($this->arguments);
        }

        return new $this->concrete;
    }
}


<?php

namespace Cundd\Noshi\Utilities;

/**
 * Profiler
 *
 * @package Cundd\Noshi\Utilities
 */
class Profiler
{
    /**
     * Start time of the profiler
     *
     * @var float
     */
    static protected $startTime;

    /**
     * URI of the stream to write the profiler information to
     *
     * @var string
     */
    static protected $streamUri = 'php://stdout';

    /**
     * Show the processing time
     *
     * @param string $message Optional profiling message
     */
    static public function profile($message = null)
    {
        static $fileHandle = null;

        // Make sure the start time is defined
        if (!static::$startTime) {
            static::$startTime = microtime(true);
        }

        // Make sure the file handle exists
        if (!$fileHandle) {
            $fileHandle = fopen(static::$streamUri, 'w');
        }

        $output = sprintf('Profiler: %.4f', microtime(true) - static::$startTime);
        if ($message) {
            $output .= ' - ' . $message;
        }
        $output .= PHP_EOL;
        fwrite($fileHandle, $output);
    }

    /**
     * Show the processing time
     *
     * @return bool Returns if the profiler just has been started
     */
    static public function start()
    {
        if (!static::$startTime) {
            static::$startTime = microtime(true);

            return true;
        }

        return false;
    }
}


<?php

namespace Cundd\Noshi\Ui;

/**
 * A view
 *
 * @package Cundd\Noshi
 */
class View extends Template implements UiInterface
{
    /**
     * @var string
     */
    protected $templatePath = '';

    /**
     * Sets the path to the template
     *
     * @param string $templatePath
     * @return $this
     */
    public function setTemplatePath($templatePath)
    {
        $this->templatePath = $templatePath;

        return $this;
    }

    /**
     * Returns the path to the template
     *
     * @return string
     */
    public function getTemplatePath()
    {
        return $this->templatePath;
    }

    /**
     * Returns the template
     *
     * @return string
     */
    public function getTemplate()
    {
        if (file_exists($this->templatePath)) {
            return file_get_contents($this->templatePath);
        }

        return '<!-- Template file ' . $this->templatePath . ' not found -->' . PHP_EOL . '{content}';
    }
}


<?php

namespace Cundd\Noshi\Utilities;

/**
 * Utility class for accessing object properties
 *
 * @package Cundd\Noshi\Utilities
 */
class ObjectUtility
{
    /**
     * Returns the value for the key path of the given object
     *
     * @param string $keyPath      Key path of the property to fetch
     * @param object|array $object Source to fetch the data from
     * @param mixed $default       An optional default value to return if the path could not be resolved. If a callback is passed, it's return value is used
     * @throws \LogicException if the given key path is no string
     * @return mixed
     */
    static public function valueForKeyPathOfObject($keyPath, $object, $default = null)
    {
        $i = 0;
        $keyPathParts = explode('.', $keyPath);
        $keyPathPartsLength = count($keyPathParts);
        $currentValue = $object;

        if (!is_string($keyPath)) {
            throw new \LogicException(
                'Given key path is not of type string (maybe arguments are ordered incorrect)',
                1395484136
            );
        }

        for ($i = 0; $i < $keyPathPartsLength; $i++) {
            $key = $keyPathParts[$i];
            $accessorMethod = 'get' . ucfirst($key);

            switch (true) {
                // Current value is an array
                case is_array($currentValue) && isset($currentValue[$key]):
                    $currentValue = $currentValue[$key];
                    break;

                // Current value is an object
                case is_object($currentValue):
                    if (method_exists($currentValue, $accessorMethod)) { // Getter method
                        $currentValue = $currentValue->$accessorMethod();
                    } else {
                        if (method_exists($currentValue, 'get')) { // General "get" method
                            $currentValue = $currentValue->get($key);
                        } else {
                            if (in_array($key, get_object_vars($currentValue))) { // Direct access
                                $currentValue = $currentValue->$key;
                            } else {
                                $currentValue = null;
                            }
                        }
                    }
                    break;

                default:
                    $currentValue = null;
            }

            if ($currentValue === null) {
                break;
            }
        }

        if ($i !== $keyPathPartsLength && func_num_args() > 2) {
            if (is_object($default) && ($default instanceof \Closure)) {
                $currentValue = $default();
            } else {
                $currentValue = $default;
            }
        }

        return $currentValue;
    }
}


<?php

namespace Darsyn\ClassFinder;

use Darsyn\ClassFinder\Reflection\ReflectionClass;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;

/**
 * @author Zander Baldwin <hello@zanderbaldwin.com>
 */
class ClassFinder implements ClassFinderInterface
{
    /**
     * @access protected
     * @var string
     */
    protected $directory;

    /**
     * @access protected
     * @var string
     */
    protected $namespace;

    /**
     * @access protected
     * @var string
     */
    protected $extension = '.php';

    /**
     * Set Root Directory
     *
     * @access public
     * @throws \DomainException
     * @param string $directory
     * @return self
     */
    public function setRootDirectory($directory)
    {
        if (!is_dir($directory)) {
            throw new \DomainException(sprintf(
                'The value "%s" defined as the root directory does not exist.',
                $directory
            ));
        }
        $this->directory = $directory;
        return $this;
    }

    /**
     * Get Root Directory
     *
     * @access public
     * @return string
     */
    public function getRootDirectory()
    {
        return $this->directory;
    }

    /**
     * Set Root Namespace
     *
     * @access public
     * @param string $namespace
     * @return self
     */
    public function setRootNamespace($namespace)
    {
        $this->namespace = $namespace;
        return $this;
    }

    /**
     * Get Root Namespace
     *
     * @access public
     * @return string
     */
    public function getRootNamespace()
    {
        return $this->namespace;
    }

    /**
     * Set the file extension to search for (with leading full-stop).
     *
     * @access public
     * @param string $extension
     * @return self
     */
    public function setExtension($extension)
    {
        $this->extension = $extension !== null ? '.' . trim($extension, '.') : '';
        return $this;
    }

    /**
     * Get File Extension
     *
     * @access public
     * @return string
     */
    public function getExtension()
    {
        return $this->extension;
    }

    /**
     * Find Class Reflections
     *
     * @access public
     * @param string $subDir
     * @param string $suffix
     * @param string $parent
     * @param integer $allowedParameters
     * @return array
     */
    public function findClassReflections($subDir = null, $suffix = null, $parent = null, $allowedParameters = 0)
    {
        $classes = [];
        $subDir = trim(preg_replace('#//{2,}#', '/', strtr($subDir, '\\', '/')), '/');
        $namespace = trim($this->namespace, '\\') . '\\' . strtr($subDir, '/', '\\') . '\\';
        $finder = $this->directory !== null
               && is_dir($directory = $this->directory . DIRECTORY_SEPARATOR . strtr($subDir, '/', DIRECTORY_SEPARATOR))
            ? (new Finder)->files()->name(sprintf('*%s', $this->extension))->in($directory)
            : [];
        foreach ($finder as $file) {
            try {
                $class = $this->getClassReflection($file, $namespace, $suffix, $parent, $allowedParameters);
                $classes[] = $class;
            } catch (\Exception $exception) {
                continue;
            }
        }
        return $classes;
    }

    /**
     * Find Classes
     *
     * @access public
     * @param string $subDir
     * @param string $suffix
     * @param string $parent
     * @param integer $allowedParameters
     * @return \Darsyn\ClassFinder\Reflection\Class|array
     */
    public function findClasses($subDir = null, $suffix = null, $parent = null, $allowedParameters = 0)
    {
        return array_map(function (ReflectionClass $class) {
            return $class->getName();
        }, $this->findClassReflections($subDir, $suffix, $parent, $allowedParameters));
    }

    /**
     * Get Class Reflection Instance
     *
     * @access protected
     * @throws \LogicException
     * @param \Symfony\Component\Finder\SplFileInfo $file
     * @param string $namespace
     * @param string $suffix
     * @param string $parent
     * @param integer $allowedParameters
     * @return \Darsyn\ClassFinder\Reflection\ReflectionClass
     */
    protected function getClassReflection(SplFileInfo $file, $namespace, $suffix, $parent, $allowedParameters)
    {
        // Determine the fully-qualified class name of the found file.
        $class = preg_replace('#\\\\{2,}#', '\\', sprintf(
            '%s\\%s\\%s',
            $namespace,
            strtr($file->getRelativePath(), '/', '\\'),
            $file->getBasename($this->extension)
        ));
        // Make sure that the class name has the correct suffix.
        if (!empty($suffix) && substr($class, 0 - strlen($suffix)) !== $suffix) {
            throw new \LogicException(sprintf(
                'The file found at "%s" does not end with the required suffix of "%s".',
                $file->getRealPath(),
                $suffix
            ));
        }
        // We have to perform a few checks on the class before we can return it.
        // - It must be an actual class; not interface, abstract or trait types.
        // - For this to work the constructor must not have more than the expected number of required parameters.
        // - And finally make sure that the class loaded was actually loaded from the directory we found it in.
        //   TODO: Make sure that the final (file path) check doesn't cause problems with proxy classes or
        //         bootstraped/compiled class caches.
        $reflect = new ReflectionClass($class, $file->getRelativePath());
        if ((is_object($construct = $reflect->getConstructor())
                && $construct->getNumberOfRequiredParameters() > $allowedParameters
            )
            || $reflect->isAbstract() || $reflect->isInterface() || $reflect->isTrait()
            || (is_string($parent) && !empty($parent) && !$reflect->isSubclassOf($parent))
            || $reflect->getFileName() !== $file->getRealPath()
        ) {
            throw new \LogicException(sprintf('The class definition for "%s" is invalid.', $class));
        }
        return $reflect;
    }
}


<?php

namespace kato\modules\media;

use Yii;
use yii\web\BadRequestHttpException;
use yii\web\UploadedFile;
use kato\helpers\KatoBase;
use kato\modules\media\models\Media as MediaModel;

/**
 * Class Media
 * @package kato\modules\media
 *
 * @property string $adminView
 * @property string $adminLayout
 */
class Media extends \yii\base\Module
{
    public $controllerNamespace = 'kato\modules\media\controllers';

    public $adminView = 'index';
    public $adminLayout = null;

    public function init()
    {
        parent::init();

        Yii::setAlias('@media', dirname(__FILE__));
    }

    /**
     * Uploads the file
     * if success returns json array for media data
     *
     * @param string $fileName
     * @param bool $useFile
     * @return bool|string
     * @throws \yii\web\BadRequestHttpException
     */
    public function mediaUpload($fileName = 'file', $useFile = false)
    {
        $file = UploadedFile::getInstanceByName($fileName);

        if ($useFile !== false) {
            $file = $file[0];
        }

        if (is_null($file)) {
            throw new BadRequestHttpException('No file specified to upload.');
        }

        return $this->insertMedia($file);
    }

    /**
     * Upload to file and insert into media table
     * @param $file
     * @return array
     */
    private function insertMedia($file)
    {
        /**
         * @var \yii\web\UploadedFile $file
         */

        $result = ['success' => false, 'message' => 'File could not be saved.'];

        if ($file->size > Yii::$app->params['maxUploadSize']) {
            $result['message'] = 'Max upload size limit reached';
        }

        $uploadTime = date("Y-m-W");
        $media = new MediaModel();

        $media->filename = KatoBase::sanitizeFile($file->baseName) . '-' . KatoBase::genRandomString(4) . '.' . $file->extension;
        $media->mimeType = $file->type;
        $media->byteSize = $file->size;
        $media->extension = $file->extension;
        $media->source = basename(\Yii::$app->params['uploadPath']) . '/' . $uploadTime . '/' . $media->filename;

        if (!is_file($media->source)) {
            //If saved upload the file
            $uploadPath = \Yii::$app->params['uploadPath'] . $uploadTime;
            if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true);

            if ($file->saveAs($uploadPath . '/' . $media->filename)) {
                //Save to media table
                if ($media->save(false)) {
                    $result['success'] = true;
                    $result['message'] = 'Upload Success';
                    $result['data'] = $media;
                } else {
                    $result['message'] = "Database record could not be saved.";
                }
            } else {
                $result['message'] = "File could not be saved.";
            }
        } else {
            $result['message'] = "File already exists.";
        }

        return $result;
    }
}


<?php namespace Kalani\DateRange;

/**
 * An example of how to use your own calculator object
 * for calculating all numbers
 */
class ExampleCalculator extends Calculator
{
    /**
     * Round down to the nearest 15 minutes
     * As a special case, round the first period
     * down to 0.
     */
    public function hours($downTo=15, $decimalPlaces=2)
    {
        if (! $this->has(['start','end']))
            return 0;

        $diff = $this->start->diffInMinutes($this->end);
        $minutes = $diff - ($downTo / 2);

        $hours = $minutes / 60;
        $periodsPerHour = 60 / $downTo;
        $roundedHours = round(
            round($hours * $periodsPerHour) / $periodsPerHour,
            $decimalPlaces
        );

        $whole = floor($roundedHours);
        $fraction = round($roundedHours - $whole,2);
        $periodLength = round(1.0 / $periodsPerHour,2);

        if ($fraction == $periodLength && $diff % $downTo === 0)
            return ($roundedHours - $periodLength);

        return $roundedHours;
    }

}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk;

use Mapado\RestClientSdk\Helper\ArrayHelper;
use Mapado\RestClientSdk\Mapping\ClassMetadata;
use Mapado\RestClientSdk\Mapping\Relation;

/**
 * UnitOfWork
 */
class UnitOfWork
{
    /**
     * mapping
     *
     * @var Mapping
     */
    private $mapping;

    /**
     * storage for every entity retrieved
     *
     * @var array<string, object>
     */
    private $storage;

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

    /**
     * return the new serialized model with only needed fields to update
     */
    public function getDirtyData(
        array $newSerializedModel,
        array $oldSerializedModel,
        ClassMetadata $classMetadata
    ): array {
        return $this->getDirtyFields(
            $newSerializedModel,
            $oldSerializedModel,
            $classMetadata
        );
    }

    /**
     * Register a net entity in the UnitOfWork storage
     */
    public function registerClean(string $id, object $entity): self
    {
        $entityStored = clone $entity;
        $this->storage[$id] = $entityStored;

        return $this;
    }

    public function getDirtyEntity(string $id): ?object
    {
        return $this->storage[$id] ?? null;
    }

    public function clear(string $id): self
    {
        unset($this->storage[$id]);

        return $this;
    }

    /**
     * Compare serialize object and returns only modified fields
     */
    private function getDirtyFields(
        array $newSerializedModel,
        array $oldSerializedModel,
        ClassMetadata $classMetadata
    ): array {
        $dirtyFields = [];

        foreach ($newSerializedModel as $key => $value) {
            if (!array_key_exists($key, $oldSerializedModel)) {
                // a new key has been found, add it to the dirtyFields
                $dirtyFields[$key] = $value;
                continue;
            }

            $oldValue = $oldSerializedModel[$key];

            $currentRelation = $classMetadata->getRelation($key);

            if (!$currentRelation) {
                if (
                    is_array($value) &&
                    !ArrayHelper::arraySame($value, $oldValue ?: []) ||
                    $value !== $oldValue
                ) {
                    $dirtyFields[$key] = $value;
                }
                continue;
            }

            $currentClassMetadata = $this->mapping->getClassMetadata(
                $currentRelation->getTargetEntity()
            );

            $idSerializedKey = $currentClassMetadata->getIdSerializeKey();

            if (Relation::MANY_TO_ONE === $currentRelation->getType()) {
                if ($value !== $oldValue) {
                    if (is_string($value) || is_string($oldValue)) {
                        $dirtyFields[$key] = $value;
                    } else {
                        $recursiveDiff = $this->getDirtyFields(
                            $value,
                            $oldValue,
                            $currentClassMetadata
                        );

                        if (!empty($recursiveDiff)) {
                            $recursiveDiff[
                                $idSerializedKey
                            ] = self::getEntityId($value, $idSerializedKey);
                            $dirtyFields[$key] = $recursiveDiff;
                        }
                    }
                }

                continue;
            }

            // ONE_TO_MANY relation
            if (count($value ?? []) !== count($oldValue ?? [])) {
                // get all objects ids of new array
                $dirtyFields[$key] = $this->addIdentifiers(
                    $value,
                    [],
                    $idSerializedKey
                );
            }

            if (!empty($value)) {
                foreach ($value as $relationKey => $relationValue) {
                    $oldRelationValue = $this->findOldRelation(
                        $relationValue,
                        $oldValue,
                        $currentClassMetadata
                    );

                    if ($relationValue !== $oldRelationValue) {
                        if (
                            is_string($relationValue) ||
                            is_string($oldRelationValue)
                        ) {
                            $dirtyFields[$key][$relationKey] = $relationValue;
                        } else {
                            $recursiveDiff = $this->getDirtyFields(
                                $relationValue,
                                $oldRelationValue,
                                $currentClassMetadata
                            );

                            if (!empty($recursiveDiff)) {
                                $idSerializedKey = $currentClassMetadata->getIdSerializeKey();

                                $entityId = self::getEntityId(
                                    $relationValue,
                                    $idSerializedKey
                                );
                                if (null !== $entityId) {
                                    $recursiveDiff[
                                        $idSerializedKey
                                    ] = $entityId;
                                }
                                $dirtyFields[$key][
                                    $relationKey
                                ] = $recursiveDiff;
                            }
                        }
                    }
                }
            }
        }

        return $dirtyFields;
    }

    /**
     * add defined identifiers to given model
     *
     * @param ?mixed $idSerializedKey
     */
    private function addIdentifiers(
        $newSerializedModel,
        array $dirtyFields,
        $idSerializedKey = null
    ): array {
        foreach ($newSerializedModel as $key => $value) {
            if ($idSerializedKey && isset($value[$idSerializedKey])) {
                $dirtyFields[$key][$idSerializedKey] = $value[$idSerializedKey];
            } elseif (is_string($value) && is_int($key)) {
                $dirtyFields[$key] = $value;
            }
        }

        return $dirtyFields;
    }

    /**
     * @param string|array $relationValue
     *
     * @return array|string
     */
    private function findOldRelation(
        $relationValue,
        array $oldValue,
        ClassMetadata $classMetadata
    ) {
        $idSerializedKey = $classMetadata->getIdSerializeKey();

        $relationValueId = self::getEntityId($relationValue, $idSerializedKey);

        foreach ($oldValue as $oldRelationValue) {
            $oldRelationValueId = self::getEntityId(
                $oldRelationValue,
                $idSerializedKey
            );

            if ($relationValueId === $oldRelationValueId) {
                return $oldRelationValue;
            }
        }

        return $classMetadata->getDefaultSerializedModel();
    }

    /**
     * get entity id from string or array
     *
     * @param string|array $stringOrEntity
     * @param string $idSerializedKey
     *
     * @return ?mixed
     */
    private static function getEntityId(
        $stringOrEntity,
        string $idSerializedKey
    ) {
        if (!is_array($stringOrEntity)) {
            return $stringOrEntity;
        }

        return $stringOrEntity[$idSerializedKey] ?? null;
    }
}


<?php namespace Kalani\DateRange;

use Illuminate\Support\ServiceProvider;
use Kalani\DateRange\DateRange;

class DateRangeServiceProvider extends ServiceProvider
{

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Perform post-registration booting of services.
	 *
	 * @return void
	 */
	public function boot()
	{
	    $this->publishes([
	        __DIR__.'/../../config/date-range.php' => config_path('date-range.php'),
	    ]);
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['date-range'] = $this->app->share(function($app){
			$config = $this->app['config'];
			return new DateRange($config);
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array('date-range');
	}

}


<?php

namespace BugBuster\BeUserOnlineBundle\EventListener;

use Contao\CoreBundle\Framework\ContaoFrameworkInterface;
use Contao\FrontendUser;
use Contao\BackendUser;
use Contao\User;
use Contao\Config;

class UserLoginListener
{
    /**
     * @var ContaoFrameworkInterface
     */
    private $framework;

    /**
     * Contructor
     *
     * @param ContaoFrameworkInterface $framework
     */
    public function __construct(ContaoFrameworkInterface $framework)
    {
        $this->framework = $framework;
    }

    /**
     * onSetUserLogin
     *
     * @return array                Add your custom modules to the list and return the array of back end modules.
     */
    public function onSetUserLogin(User $user)
    {
        $time    = time();
        $strHash = '';

        $intUserId = $user->getData()['id']; // for user id, ugly, but I don't know what's better.

        $this->framework->initialize();

        /** @var Config $config */
        $config  = $this->framework->getAdapter(Config::class);
        $timeout = (int) $config->get('sessionTimeout');

        // Generate the cookie hash

        if ($user instanceof FrontendUser)
        {
            $strCookie = 'FE_USER_AUTH';
        }

        if ($user instanceof BackendUser)
        {
            $strCookie = 'BE_USER_AUTH';
        }
        $token = $_COOKIE["csrf_contao_csrf_token"];
        $strHash = sha1($token.$strCookie);

        // Clean up old sessions
        \Database::getInstance()->prepare("DELETE FROM tl_beuseronline_session WHERE tstamp<? OR hash=?")
                                ->execute( ($time - $timeout), $strHash );

        // Save the session in the database
        \Database::getInstance()->prepare("INSERT INTO tl_beuseronline_session (pid, tstamp, name, hash) VALUES (?, ?, ?, ?)")
                                ->execute($intUserId, $time, $strCookie, $strHash);

        //use app_dev.php to dump
        //dump from Symfony\Component\VarDumper\VarDumper
        //dump($arrModules['content']['modules']);

    }
}


<?php

namespace kato\modules\tag\widgets;

use yii\helpers\Html;
use kato\modules\tag\models\Tag;

/**
 * Class Tags
 * Usage:
 * \kato\widgets\Tags::widget([
 *  'model' => $model,
 *  ]);
 *
 * @package kato\widgets
 */
class Tags extends \yii\bootstrap\Widget
{
    public $model;
    public $options = [];
    public $containerOptions = ['class' => 'tags-list'];

    /**
     * @return string
     */
    public function run()
    {
        if ($this->getAllTags()->count() < 1) {
            return false;
        }

        return Html::tag('ul', $this->getTags(), $this->containerOptions);
    }

    /**
     * Look into Tag model by tag type
     * @return mixed
     */
    private function getAllTags()
    {
        return Tag::find()
            ->where(['tag_type' => $this->model->className()])
            ->limit(20);
    }

    /**
     * Returns list of tags from model
     * @return string
     */
    private function getTags()
    {
        $allTags = $this->getAllTags()->all();
        $tags = '';

        $total=0;
        foreach ($allTags as $tag) {
            $total += $tag->frequency;
        }

        foreach($allTags as $tag) {
            $weight = 8 + (int)(16*$tag->frequency/($total+10));
            $this->options['style'] = "font-size:{$weight}pt";

            if (isset($_GET[$this->get_real_class($this->model)]['tags']) && $_GET[$this->get_real_class($this->model)]['tags'] === $tag->name) {
                $this->options['class'] = 'tag active';
            } else {
                $this->options['class'] = 'tag';
            }
            $tags .= Html::tag('li', Html::a($tag->name, ['/blog/index', $this->get_real_class($this->model) . '[tags]' => $tag->name]), $this->options);
        }

        $tags .= Html::tag('li', '', ['class' => 'clearfix']);

        return $tags;
    }

    /**
     * Obtains an object class name without namespaces
     * @param $obj
     * @return string
     */
    private function get_real_class($obj) {
        $classname = get_class($obj);

        if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
            $classname = $matches[1];
        }

        return $classname;
    }

}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\DependencyInjection;

use ContaoBootstrap\Tab\Component\ContentElement\TabElementFactory;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class ContaoBootstrapTabExtension
 */
final class ContaoBootstrapTabExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader(
            $container,
            new FileLocator(dirname(__DIR__) . '/Resources/config')
        );

        $loader->load('services.xml');
        $loader->load('listener.xml');

        $this->configureTabElementFactory($container);
    }

    /**
     * Configure the tab element factory.
     *
     * @param ContainerBuilder $container The container builder.
     *
     * @return void
     */
    private function configureTabElementFactory(ContainerBuilder $container): void
    {
        $definition = $container->findDefinition(TabElementFactory::class);
        if (!$definition) {
            return;
        }

        $bundles = $container->getParameter('kernel.bundles');

        if (!isset($bundles['ContaoBootstrapGridBundle'])) {
            return;
        }

        $definition->setArgument(5, new Reference('contao_bootstrap.grid.grid_provider'));
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\Component\ContentElement;

/**
 * Class TabSeparatorElement
 */
final class TabEndElement extends AbstractTabElement
{
    /**
     * Template name.
     *
     * @var string
     */
    protected $templateName = 'ce_bs_tab_end';

    /**
     * {@inheritDoc}
     */
    protected function prepareTemplateData(array $data): array
    {
        $data         = parent::prepareTemplateData($data);
        $data['grid'] = $this->getGridIterator();

        if ($iterator = $this->getIterator()) {
            $data['navigation'] = $iterator->navigation();
        }

        if ($parent = $this->getParent()) {
            $data['showNavigation'] = $parent->bs_tab_nav_position === 'after';
            $data['navClass']       = $parent->bs_tab_nav_class;
        }

        return $data;
    }
}


<?php

namespace kato\modules\media\models;

use Yii;
use yii\helpers\Html;
use yii\imagine\Image;
use kato\ActiveRecord;

/**
 * This is the model class for table "kato_media".
 *
 * @property string $id
 * @property string $title
 * @property string $filename
 * @property string $source
 * @property string $source_location
 * @property string $create_time
 * @property string $extension
 * @property string $mimeType
 * @property string $byteSize
 * @property integer $status
 * @property string $content_type
 * @property string $baseSource
 * @property string $baseSourceUrl
 */
class Media extends ActiveRecord
{
    const STATUS_NOT_PUBLISHED = 0;
    const STATUS_PUBLISHED = 1;

    public $file;
    public $cacheDir = 'cache';

    public $uploadedTo = null;

    public function init()
    {
        parent::init();

        Yii::setAlias('cacheDir', '/files/' . $this->cacheDir);
        Yii::setAlias('cachePath', Yii::$app->params['uploadPath'] . $this->cacheDir);
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'kato_media';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['filename', 'source'], 'required'],
            [['create_time', 'media_type', 'title'], 'safe'],
            [['byteSize', 'status'], 'integer'],
            [['filename', 'source', 'source_location', 'title'], 'string', 'max' => 255],
            [['extension', 'mimeType'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'filename' => 'Filename',
            'source' => 'Source',
            'source_location' => 'Source Location',
            'create_time' => 'Create Time',
            'extension' => 'Extension',
            'mimeType' => 'Mime Type',
            'byteSize' => 'Byte Size',
            'status' => 'Status',
            'media_type' => 'Media Type',
        ];
    }

    /**
     * Actions to be taken before saving the record.
     * @param bool $insert
     * @return bool whether the record can be saved
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->createTitle();
            }

            return true;
        }
        return false;
    }

    /**
     * Before deletion, remove media file from source and also delete from relation table
     * @inheritdoc
     */
    public function beforeDelete()
    {
        if (parent::beforeDelete()) {
            //Remove file from system
            if (file_exists($this->baseSource)) {
                unlink($this->baseSource);
            }

            //Delete from relation table
            if ($contentMedia = ContentMedia::find()->where(['media_id' => $this->id])->all()) {
                foreach ($contentMedia as $data) {
                    $data->delete();
                }
            }

            return true;
        }

        return false;
    }

    public function afterFind()
    {
        $this->getUploadedTo();

        parent::afterFind();
    }

    /**
     * Attached Content Media, by type
     * @return static
     */
    public function getMediaContent()
    {
        return $this->hasOne(ContentMedia::className(), ['id' => 'content_id']);
        //->where('content_type = :type', [':type' => $this->className()]);
    }

    /**
     * Relate Content
     * @param null $type
     * @return static
     */
    public function getContent($type = null)
    {
        $media = $this->hasMany(Media::className(), ['id' => 'media_id']);
        if ($type !== null) {
            $media->where('media_type = :type', [':type' => $type]);
        }
        $media->via('contentMedia');

        return $media;
    }

    /**
     * Create title for media
     */
    private function createTitle()
    {
        $title_parts = pathinfo($this->filename);
        $this->title = $title_parts['filename'];
        $this->title = \kato\helpers\KatoBase::sanitizeFile($this->title);
        $this->title = str_replace('_', ' ', str_replace('-', ' ', $this->title));
        $this->title = ucwords($this->title);
    }

    /**
     * Returns base path for file
     * @return string
     */
    public function getBaseSource()
    {
        return dirname(Yii::$app->params['uploadPath']) . '/' . $this->source;
    }

    public function listMediaType()
    {
        $types = [];
        if (!empty(Yii::$app->params['mediaTypes'])) {
            foreach (Yii::$app->params['mediaTypes'] as $key => $value) {
                $types[$value] = ucfirst($value);
            }
        }
        return $types;
    }

    public function statusDropDownList()
    {
        $data = [];
        if ($this->listStatus()) {
            foreach ($this->listStatus() as $key => $value) {
                $data[] = [
                    'id' => $key,
                    'text' => $value,
                ];
            }
        }

        return $data;
    }

    public function getUploadedTo()
    {
        $this->uploadedTo = 'todo';
    }

    /**
     * Renders PDF File
     * @param array $data
     * @return string
     */
    public function renderPdf($data = [])
    {
        if (isset($data['imgTag'])) {
            $pdfPreview = Yii::$app->request->baseUrl . '/theme-assets/img/pdf-preview.jpg';

            $options = [];
            if (isset($data['width'])) $options['width'] = $data['width'];
            if (isset($data['height'])) $options['height'] = $data['height'];
            return Html::img($pdfPreview, $options);
        }

        return '/' . $this->source;
    }

    /**
     * Renders all supported image files
     * @param array $data
     * @return bool|string
     */
    public function renderImage($data = [])
    {
        ini_set('memory_limit', '512M');
        $cacheFile = Yii::getAlias('@cachePath/' . $this->filename);
        $baseSource = $this->baseSource;

        if (!isset($data['width']) && !isset($data['height'])) {
            if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $this->filename))) {
                //only cache if not available
                try {
                    $image = Image::getImagine();
                    $newImage = $image->open($baseSource);
                    $newImage->save($cacheFile);
                } catch (\Exception $e) {
                    //seems like image is corrupt!
                }
            }

            return Yii::getAlias('@cacheDir/' . $this->filename);
        } else {
            $path_parts = pathinfo($cacheFile);
            $newFileName = $path_parts['filename'] . '-' . $data['width'] . '-' . $data['height'] . '.' . $path_parts['extension'];
            //http://imagine.readthedocs.org/en/latest/
            if (!file_exists(Yii::getAlias('@root') . Yii::getAlias('@cacheDir/' . $newFileName))) {
                //only cache if not available
                try {
                    Image::thumbnail($baseSource, $data['width'], $data['height'])
                        ->save(Yii::getAlias('@cachePath/' . $newFileName));
                } catch (\Exception $e) {
                    //seems like image is corrupt!
                }
            }

            if (isset($data['imgTag'])) {
                return Html::img(Yii::getAlias('@cacheDir/' . $newFileName));
            } else {
                return Yii::getAlias('@cacheDir/' . $newFileName);
            }
        }
    }

    /**
     * Renders media
     * @param array $data
     * @return bool|string
     */
    public function render($data = [])
    {
        //if file local does not exists
        if (!file_exists($this->baseSource)) {
            return '';
        }

        //check if it's pdf file
        if ($this->mimeType === 'application/pdf') {
            return $this->renderPdf($data);
        } else {
            return $this->renderImage($data);
        }
    }

}


<?php

declare(strict_types=1);

namespace Mapado\RestClientSdk\Model;

use Mapado\RestClientSdk\Collection\Collection;
use Mapado\RestClientSdk\Collection\HalCollection;
use Mapado\RestClientSdk\Collection\HydraPaginatedCollection;
use Mapado\RestClientSdk\Helper\ArrayHelper;
use Mapado\RestClientSdk\SdkClient;

/**
 * Class ModelHydrator
 *
 * @author Julien Deniau <julien.deniau@mapado.com>
 */
class ModelHydrator
{
    /**
     * @var SdkClient
     */
    protected $sdk;

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

    /**
     * @param string|int|mixed $id
     */
    public function convertId($id, string $modelName): string
    {
        $id = (string) $id;

        // add slash if needed to have a valid hydra id
        if (false === mb_strpos($id, '/')) {
            $mapping = $this->sdk->getMapping();
            $key = $mapping->getKeyFromModel($modelName);
            $id = '/' . $key . '/' . $id;

            if ($prefix = $mapping->getIdPrefix()) {
                $id = $prefix . $id;
            }
        }

        return $id;
    }

    /**
     * convert data as array to entity
     */
    public function hydrate(?array $data, string $modelName): ?object
    {
        $mapping = $this->sdk->getMapping();
        $key = $mapping->getKeyFromModel($modelName);
        $modelName = $mapping->getModelName($key);

        return $this->deserialize($data, $modelName);
    }

    /**
     * convert API response to Collection containing entities
     */
    public function hydrateList(?array $data, string $modelName): Collection
    {
        $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey'];

        if (is_array($data) && ArrayHelper::arrayHas($data, $collectionKey)) {
            return $this->deserializeAll($data, $modelName);
        }

        return new Collection();
    }

    /**
     * convert list of data as array to Collection containing entities
     */
    private function deserializeAll(array $data, string $modelName): Collection
    {
        $collectionKey = $this->sdk->getMapping()->getConfig()['collectionKey'];

        $itemList = array_map(function ($member) use ($modelName) {
            return $this->deserialize($member, $modelName);
        }, ArrayHelper::arrayGet($data, $collectionKey));

        $extraProperties = array_filter(
            $data,
            function ($key) use ($collectionKey) {
                return $key !== $collectionKey;
            },
            ARRAY_FILTER_USE_KEY
        );

        $collectionClassName = $this->guessCollectionClassname($data);

        return new $collectionClassName($itemList, $extraProperties);
    }

    /**
     * convert array to entity
     */
    private function deserialize(?array $data, string $modelName): ?object
    {
        if (null === $data) {
            return null;
        }

        return $this->sdk->getSerializer()->deserialize($data, $modelName);
    }

    /**
     * guess collection classname according to response data
     */
    private function guessCollectionClassname(array $data): string
    {
        switch (true) {
            case !empty($data['@type']) &&
            'hydra:PagedCollection' === $data['@type']:
                return HydraPaginatedCollection::class;

            case array_key_exists('_embedded', $data):
                return HalCollection::class;

            default:
                return Collection::class;
        }
    }
}


<?php

namespace kato\modules\sitemap;

use Yii;
use yii\base\InvalidConfigException;
use yii\caching\Cache;

/**
 * Class Sitemap
 * @package kato\modules\sitemap
 */
class Sitemap extends \yii\base\Module
{
    public $controllerNamespace = 'kato\modules\sitemap\controllers';

    /** @var int */
    public $cacheExpire = 86400;

    /** @var Cache|string */
    public $cacheProvider = 'cache';

    /** @var string */
    public $cacheKey = 'sitemap';

    /** @var boolean Use php's gzip compressing. */
    public $enableGzip = false;

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

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

    public function init()
    {
        parent::init();

        if (is_string($this->cacheProvider)) {
            $this->cacheProvider = Yii::$app->{$this->cacheProvider};
        }
        if (!$this->cacheProvider instanceof Cache) {
            throw new InvalidConfigException('Invalid `cacheKey` parameter was specified.');
        }
    }

    /**
     * Build and cache a site map.
     * @param bool $returnAsArray
     * @return array|string
     * @throws InvalidConfigException
     */
    public function buildSitemap($returnAsArray = false)
    {
        $urls = $this->urls;
        foreach ($this->models as $modelName) {
            /** @var \kato\modules\sitemap\behaviors\SitemapBehavior $model */
            if (is_array($modelName)) {
                $model = new $modelName['class'];
                if (isset($modelName['behaviors'])) {
                    $model->attachBehaviors($modelName['behaviors']);
                }
            } else {
                $model = new $modelName;
            }
            $urls = array_merge($urls, $model->generateSiteMap());
        }

        if ($returnAsArray === true) {
            return $urls;
        }

        $sitemapData = $this->createControllerByID('default')->renderPartial('index', [
            'urls' => $urls
        ]);

        $this->cacheProvider->set($this->cacheKey, $sitemapData, $this->cacheExpire);
        return $sitemapData;
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\View\Tab;

use Assert\Assertion;
use Contao\ContentModel;

/**
 * Class TabRegistry
 *
 * @package ContaoBootstrap\Tab\View\Tab
 */
final class TabRegistry
{
    /**
     * Cached navigation instances.
     *
     * @var array|Navigation[]
     */
    private $navigations = [];

    /**
     * Cached navigation iterators.
     *
     * @var NavigationIterator[]
     */
    private $iterators = [];

    /**
     * Get a navigation.
     *
     * @param string $elementId The element id.
     *
     * @return Navigation
     *
     * @throws \Assert\AssertionFailedException When an invalid element is given.
     */
    public function getNavigation(string $elementId): Navigation
    {
        if (!isset($this->navigations[$elementId])) {
            $element = ContentModel::findByPk($elementId);
            Assertion::isInstanceOf($element, ContentModel::class);
            Assertion::eq($element->type, 'bs_tab_start');

            $this->navigations[$elementId] = Navigation::fromSerialized((string) $element->bs_tabs, $elementId);
        }

        return $this->navigations[$elementId];
    }

    /**
     * Get the iterator.
     *
     * @param string $elementId The element id.
     *
     * @return NavigationIterator
     *
     * @throws \Assert\AssertionFailedException When an invalid element is given.
     */
    public function getIterator(string $elementId): NavigationIterator
    {
        if (!isset($this->iterators[$elementId])) {
            $this->iterators[$elementId] = new NavigationIterator($this->getNavigation($elementId));
        }

        return $this->iterators[$elementId];
    }
}


<?php

/**
 * Contao Bootstrap
 *
 * @package    contao-bootstrap
 * @subpackage Tab
 * @author     David Molineus <david.molineus@netzmacht.de>
 * @copyright  2013-2018 netzmacht David Molineus. All rights reserved.
 * @license    LGPL-3.0 https://github.com/contao-bootstrap/tab
 * @filesource
 */

declare(strict_types=1);

namespace ContaoBootstrap\Tab\Component\ContentElement;

use Contao\ContentModel;

/**
 * Class TabSeparatorElement
 */
final class TabStartElement extends AbstractTabElement
{
    /**
     * Template name.
     *
     * @var string
     */
    protected $templateName = 'ce_bs_tab_start';

    /**
     * {@inheritDoc}
     */
    protected function prepareTemplateData(array $data): array
    {
        $data = parent::prepareTemplateData($data);

        $data['fade']     = $this->get('bs_tab_fade') ? ' fade' : '';
        $data['grid']     = $this->getGridIterator();
        $data['navClass'] = $this->get('bs_tab_nav_class');

        $iterator = $this->getIterator();
        if ($iterator) {
            $iterator->rewind();

            $currentItem = $iterator->current();

            $data['navigation']  = $iterator->navigation();
            $data['currentItem'] = $currentItem;

            if ($this->get('bs_tab_fade') && $currentItem && $currentItem->active()) {
                $data['fade'] = rtrim($data['fade'] .= ' show');
            }
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function generate(): string
    {
        if ($this->isBackendRequest()) {
            $iterator = $this->getIterator();

            if ($iterator) {
                $iterator->rewind();
            }
        }

        return parent::generate();
    }

    /**
     * {@inheritdoc}
     */
    protected function getParent(): ?ContentModel
    {
        return $this->getModel();
    }
}