<?php declare(strict_types=1);

namespace Kuria\ClassLoader;

/**
 * PSR-0 and PSR-4 class loader implementation
 */
class ClassLoader
{
    const PSR0 = 0;
    const PSR4 = 1;

    /** @var bool */
    private $debug;

    /** @var bool */
    private $usePrefixes;

    /** @var string[] */
    private $fileSuffixes = ['.php'];

    /** @var array class name => path / false */
    private $classMap = [];

    /** @var array index => array(array(0 => type, 1 => prefix, 2 => prefix_len, 3 => paths), ...) */
    private $prefixes = [];

    /** @var array type => paths */
    private $fallbacks = [];

    function __construct(bool $debug = false, bool $usePrefixes = true)
    {
        $this->debug = $debug;
        $this->usePrefixes = $usePrefixes;
    }

    /**
     * Register the class loader
     */
    function register(bool $prepend = false): bool
    {
        return spl_autoload_register([$this, 'loadClass'], true, $prepend);
    }

    /**
     * Unregister the class loader
     */
    function unregister(): bool
    {
        return spl_autoload_unregister([$this, 'loadClass']);
    }

    function isDebugEnabled(): bool
    {
        return $this->debug;
    }

    function setDebug(bool $debug): void
    {
        $this->debug = $debug;
    }

    /**
     * Set whether prefixes should be searched when locating a class file
     *
     * If prefix usage is disabled, only the class map is searched.
     */
    function setUsePrefixes(bool $usePrefixes): void
    {
        $this->usePrefixes = $usePrefixes;
    }

    function getFileSuffixes(): array
    {
        return $this->fileSuffixes;
    }

    function addFileSuffix(string $fileSuffix): void
    {
        if (array_search($fileSuffix, $this->fileSuffixes, true) === false) {
            $this->fileSuffixes[] = $fileSuffix;
        }
    }

    /**
     * Set file suffixes
     *
     * This replaces any previously set suffixes.
     */
    function setFileSuffixes(array $fileSuffixes): void
    {
        $this->fileSuffixes = $fileSuffixes;
    }

    function loadClass(string $className): void
    {
        $path = $this->findFile($className);

        if ($path !== null) {
            include $path;

            if ($this->debug) {
                $this->checkLoadedClass($className, $path);
            }
        }
    }

    /**
     * Register a single class
     */
    function addClass(string $class, string $path): void
    {
        $this->classMap[$class] = $path;
    }

    /**
     * Register a class map
     */
    function addClassMap(array $classMap): void
    {
        $this->classMap = $classMap + $this->classMap;
    }

    /**
     * Register a prefix
     *
     * - adding an empty prefix will register a fallback.
     * - see ClassLoader::PSR* constants for available types
     *
     * @throws \UnexpectedValueException if an invalid type is given
     * @throws \InvalidArgumentException if an invalid prefix is given
     */
    function addPrefix(string $prefix, $paths, int $type = self::PSR4): void
    {
        if ($type !== static::PSR4 && $type !== static::PSR0) {
            throw new \UnexpectedValueException('Invalid prefix type');
        }

        if ($prefix === '') {
            foreach ((array) $paths as $path) {
                $this->fallbacks[$type][] = $path;
            }

            return;
        }

        $firstNsSep = strpos($prefix, '\\');
        $prefixLength = strlen($prefix);

        // determine index
        if ($firstNsSep === false) {
            // no namespace
            if ($type === static::PSR4) {
                throw new \InvalidArgumentException(sprintf(
                    'PSR-4 prefixes must contain a top level namespace (got "%s")',
                    $prefix
                ));
            }

            // use first character
            $index = $prefix[0];
        } else {
            // has namespace
            if ($type === static::PSR4 && $prefix[$prefixLength - 1] !== '\\') {
                throw new \InvalidArgumentException(sprintf(
                    'PSR-4 prefixes must end with a namespace separator (got "%s")',
                    $prefix
                ));
            }

            // use vendor namespace
            $index = substr($prefix, 0, $firstNsSep);
        }

        // register
        $this->prefixes[$index][] = [$type, $prefix, $prefixLength, (array) $paths];
    }

    /**
     * Register a prefix => paths map
     *
     * @see ClassLoader::addPrefix()
     */
    function addPrefixes(array $prefixes, int $type = self::PSR4): void
    {
        foreach ($prefixes as $prefix => $paths) {
            $this->addPrefix($prefix, $paths, $type);
        }
    }

    /**
     * Find a file for the given class name
     *
     * Returns NULL on failure.
     */
    function findFile(string $className): ?string
    {
        if ($className[0] === '\\') {
            $className = substr($className, 1);
        }

        // check class map
        if (isset($this->classMap[$className])) {
            return $this->classMap[$className];
        }

        if ($this->usePrefixes) {
            // determine index
            $firstNsSep = strpos($className, '\\');
            if ($firstNsSep === false) {
                $isPsr4Compatible = false;
                $index = $className[0];
                $firstNsSep = null;
            } else {
                $isPsr4Compatible = true;
                $index = substr($className, 0, $firstNsSep);
            }

            // cache PSR-0 subpath
            $subpathPsr0 = null;

            // scan prefixes
            if (
                isset($this->prefixes[$index])
                || ($isPsr4Compatible && isset($this->prefixes[$index = $className[0]]))
            ) {
                foreach ($this->prefixes[$index] as $prefix) {
                    // 0 => type, 1 => prefix, 2 => prefix_len, 3 => paths
                    if (
                        ($isPsr4 = ($prefix[0] === static::PSR4)) && !$isPsr4Compatible
                        || strncmp($prefix[1], $className, $prefix[2]) !== 0
                    ) {
                        // no match or we are locating a PSR-0 class but the prefix is PSR-4
                        continue;
                    }

                    // compose subpath
                    if ($isPsr4) {
                        // PSR-4 subpath must be built for different prefix lengths
                        $subpath = $this->buildPsr4Subpath($className, $prefix[2]);
                    } else {
                        // PSR-0 subpath contains the entire namespace so it needs to be built only once
                        if ($subpathPsr0 === null) {
                            $subpathPsr0 = $this->buildPsr0Subpath($className, $firstNsSep);
                        }

                        $subpath = $subpathPsr0;
                    }

                    // iterate over possible paths
                    foreach ($prefix[3] as $path) {
                        if (($filePath = $this->findFileWithKnownSuffix($path . $subpath)) !== null) {
                            return $filePath;
                        }
                    }
                }
            }

            // scan fallbacks
            if (isset($this->fallbacks[static::PSR0])) {
                $subpath = $subpathPsr0 ?: $this->buildPsr0Subpath($className, $firstNsSep);

                foreach ($this->fallbacks[static::PSR0] as $fallback) {
                    if (($filePath = $this->findFileWithKnownSuffix($fallback . $subpath)) !== null) {
                        return $filePath;
                    }
                }
            }

            if (isset($this->fallbacks[static::PSR4])) {
                $subpath = $this->buildPsr4Subpath($className, 0);

                foreach ($this->fallbacks[static::PSR4] as $fallback) {
                    if (($filePath = $this->findFileWithKnownSuffix($fallback . $subpath)) !== null) {
                        return $filePath;
                    }
                }
            }

            // cache failed lookup
            $this->classMap[$className] = false;
        }

        return null;
    }

    private function buildPsr0Subpath(string $className, ?int $firstNsSep): string
    {
        $subpath = '/';

        if ($firstNsSep !== null) {
            $lastNsSep = strrpos($className, '\\');
            $namespace = substr($className, 0, $lastNsSep);
            $plainClassName = substr($className, $lastNsSep + 1);

            $subpath .= strtr($namespace, '\\', '/') . '/';
        } else {
            $plainClassName = $className;
        }

        $subpath .= strtr($plainClassName, '_', '/');

        return $subpath;
    }

    private function buildPsr4Subpath(string $className, int $prefixLength): string
    {
        return '/' . strtr($prefixLength > 0 ? substr($className, $prefixLength) : $className, '\\', '/');
    }

    /**
     * Try locating the given path using all registered suffixes
     *
     * Returns NULL on failure.
     */
    private function findFileWithKnownSuffix(string $pathWithoutSuffix): ?string
    {
        foreach ($this->fileSuffixes as $fileSuffix) {
            if (is_file($filePath = $pathWithoutSuffix . $fileSuffix)) {
                return $filePath;
            }
        }

        return null;
    }

    private function checkLoadedClass(string $className, string $path): void
    {
        // check if the class was actually loaded
        if (
            !class_exists($className, false)
            && !interface_exists($className, false)
            && !trait_exists($className, false)
        ) {
            throw new \RuntimeException(sprintf(
                'Class, interface or trait "%s" was not found in file "%s" - possible typo in the name or namespace',
                $className,
                $path
            ));
        }
    }
}


<?php

namespace Onoi\Tesa;

use Onoi\Tesa\Tokenizer\Tokenizer;
use Onoi\Tesa\Synonymizer\Synonymizer;
use Onoi\Tesa\StopwordAnalyzer\StopwordAnalyzer;
use RuntimeException;

/**
 * @license GNU GPL v2+
 * @since 0.1
 *
 * @author mwjames
 */
class Normalizer {

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 *
	 * @param integer $flag
	 */
	public static function applyTransliteration( $text, $flag = Transliterator::DIACRITICS ) {
		return Transliterator::transliterate( $text, $flag );
	}

	/**
	 * @see Localizer::convertDoubleWidth
	 *
	 * @since 0.1
	 *
	 * @param string $text
	 *
	 * @return string
	 */
	public static function convertDoubleWidth( $text ) {
		static $full = null;
		static $half = null;

		//,。／？《》〈〉；：“”＂〃＇｀［］｛｝＼｜～！－＝＿＋）（()＊…—─％￥＃
		//,./?«»();:“”

		if ( $full === null ) {
			$fullWidth = "０１２３４５６７８９ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚ";
			$halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

			// http://php.net/manual/en/function.str-split.php, mb_str_split
			$length = mb_strlen( $fullWidth, "UTF-8" );
			$full = array();

			for ( $i = 0; $i < $length; $i += 1 ) {
				$full[] = mb_substr( $fullWidth, $i, 1, "UTF-8" );
			}

			$half = str_split( $halfWidth );
		}

		return str_replace( $full, $half, trim( $text ) );
	}

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 *
	 * @return string
	 */
	public static function toLowercase( $text ) {
		return mb_strtolower( $text, mb_detect_encoding( $text ) );
	}

	/**
	 * @since 0.1
	 *
	 * @param string $text
	 * @param integer|null $length
	 *
	 * @return string
	 */
	public static function reduceLengthTo( $text, $length = null ) {

		if ( $length === null || mb_strlen( $text ) <= $length ) {
			return $text;
		}

		$encoding = mb_detect_encoding( $text );
		$lastWholeWordPosition = $length;

		if ( strpos( $text, ' ' ) !== false ) {
			$lastWholeWordPosition = strrpos( mb_substr( $text, 0, $length, $encoding ), ' ' ); // last whole word
		}

		if ( $lastWholeWordPosition > 0 ) {
			$length = $lastWholeWordPosition;
		}

		return mb_substr( $text, 0, $length, $encoding );
	}

}


<?php

namespace Interpro\ImageAggr\Service;

use Interpro\Core\Contracts\Taxonomy\Taxonomy;
use Interpro\Core\Taxonomy\Enum\TypeRank;
use Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet;
use Interpro\ImageAggr\Model\Crop;
use Interpro\ImageAggr\Model\Image;
use Interpro\ImageAggr\Model\Resize;
use Interpro\Service\Contracts\Cleaner as CleanerInterface;
use Interpro\Service\Enum\Artefact;

class DbCleaner implements CleanerInterface
{
    private $taxonomy;
    private $settingsSet;
    private $consoleOutput;

    public function __construct(Taxonomy $taxonomy, ImageSettingsSet $settingsSet)
    {
        $this->taxonomy = $taxonomy;
        $this->settingsSet = $settingsSet;
        $this->consoleOutput = new \Symfony\Component\Console\Output\ConsoleOutput();
    }

    /**
     * @param callable $action
     *
     * @return bool
     */
    private function strategy(callable $action)
    {
        $report = false;

        $tables = [
            'image' => Image::class,
            'resize' => Resize::class,
            'crop' => Crop::class
            ];

        foreach($tables as $type_name => $modelClass)
        {
            $wehave = $modelClass::all();

            foreach($wehave as $model)
            {
                $entity_name = $model->entity_name;

                if($type_name === 'image')
                {
                    $name = $model->name;
                }
                else
                {
                    $name = $model->image_name;
                }

                if(!$this->taxonomy->exist($entity_name))
                {
                    $action(1, $type_name, $model);
                    $report = true;
                }
                else
                {
                    $ownerType = $this->taxonomy->getType($entity_name);

                    if($ownerType->getRank() === TypeRank::OWN)
                    {
                        $action(2, $type_name, $model);
                        $report = true;
                    }
                    elseif(!$ownerType->ownExist($name))
                    {
                        $action(3, $type_name, $model);
                        $report = true;
                    }
                    elseif($ownerType->getFieldType($name)->getName() !== 'image')
                    {
                        $action(4, $type_name, $model);
                        $report = true;
                    }
                    elseif($type_name !== 'image')
                    {
                        $field = $ownerType->getField($name);

                        $imageSSet = $this->settingsSet->getImage($field);

                        if($type_name === 'resize')
                        {
                            if(!$imageSSet->resizeExist($model->name))
                            {
                                $action(5, $type_name, $model);
                                $report = true;
                            }
                        }
                        elseif($type_name === 'crop')
                        {
                            if(!$imageSSet->cropExist($model->name))
                            {
                                $action(5, $type_name, $model);
                                $report = true;
                            }
                        }
                    }
                }
            }
        }

        return $report;
    }

    /**
     * @return bool
     */
    public function inspect()
    {
        $action = function($flag, $type_name, $model)
        {
            $entity_name = $model->entity_name;
            $entity_id   = $model->entity_id;

            if($type_name === 'image')
            {
                $name = $model->name;
            }
            else
            {
                $name = $model->image_name;
            }

            if($flag === 1)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): обнаружена запись для типа хозяина'.$entity_name.' не найденого в таксономии.';
            }
            elseif($flag === 2)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): обнаружена запись для типа хозяина'.$entity_name.' не соответствующего ранга.';
            }
            elseif($flag === 3)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): обнаружена запись несуществующего поля '.$name.' для хозяина '.$entity_name.'.';
            }
            elseif($flag === 4)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): обнаружена запись несуществующего поля '.$name.' для хозяина '.$entity_name.'.';
            }
            elseif($flag === 5)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): обнаружена запись несуществующей генерации '.$model->name.' поля '.$name.' для хозяина '.$entity_name.'.';
            }
            else
            {
                return;
            }

            $this->consoleOutput->writeln($message);
        };

        $report = $this->strategy($action);

        return $report;
    }

    /**
     * @return void
     */
    public function clean()
    {
        $action = function($flag, $type_name, $model)
        {
            $entity_name = $model->entity_name;
            $entity_id   = $model->entity_id;

            if($type_name === 'image')
            {
                $name = $model->name;
            }
            else
            {
                $name = $model->image_name;
            }

            $model->delete();

            if($flag === 1)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): удалена запись для типа хозяина'.$entity_name.' не найденого в таксономии.';
            }
            elseif($flag === 2)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): удалена запись для типа хозяина'.$entity_name.' не соответствующего ранга.';
            }
            elseif($flag === 3)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): удалена запись несуществующего поля '.$name.' для хозяина '.$entity_name.'.';
            }
            elseif($flag === 4)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): удалена запись несуществующего поля '.$name.' для хозяина '.$entity_name.'.';
            }
            elseif($flag === 5)
            {
                $message = 'ImageAggr '.$type_name.'('.$entity_id.'): удалена запись несуществующей генерации '.$model->name.' поля '.$name.' для хозяина '.$entity_name.'.';
            }
            else
            {
                return;
            }

            $this->consoleOutput->writeln($message);
        };

        $this->strategy($action);
    }

    /**
     * @return string
     */
    public function getArtefact()
    {
        return Artefact::DB_ROW;
    }

    /**
     * @return string
     */
    public function getFamily()
    {
        return 'imageaggr';
    }
}


<?php

/**
 * Service Provider for Laravel & Lumen Frameworks
 *
 * @package EasyCurl
 *
 * @author LightAir
 */

namespace LightAir\EasyCurl;

use Illuminate\Support\ServiceProvider;

class EasyCurlServiceProvider extends ServiceProvider
{

    /**
     * Boot the service provider.
     *
     * @return void
     */
    public function boot()
    {
        $source = realpath(__DIR__) . '/ecurl.php';

        if ($this->app instanceof LaravelApplication) {
            $this->publishes([$source => config_path('ecurl.php')]);
        } elseif ($this->app instanceof LumenApplication) {
            $this->app->configure('ecurl');
        }
        $this->mergeConfigFrom($source, 'ecurl');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('ecurl', function () {

            return (new EasyCurl())
                ->setTimeOut($this->app['config']['ecurl.timeout'])
                ->setProxy($this->app['config']['ecurl.proxy'])
                ->setUserAgent($this->app['config']['ecurl.userAgent']);
        });
    }
}


<?php

namespace ElfSundae\Laravel\Api\Console;

use Illuminate\Console\Command;
use ElfSundae\Laravel\Api\Client;

class GenerateClientCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'api:client {app name}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate key and secret for an api client.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $client = $this->laravel->make(Client::class);

        $data = [
            'name' => $name = $this->argument('app name'),
            'key' => $key = $client->appKeyForName($name),
            'secret' => $client->generateAppSecretForKey($key),
        ];

        $this->table(array_keys($data), [array_values($data)]);
    }
}


<?php

namespace ElfSundae\Laravel\Api;

use Illuminate\Support\Arr;
use Illuminate\Http\JsonResponse;
use Illuminate\Database\Eloquent\Model;

class ApiResponse extends JsonResponse
{
    /**
     * The api result code.
     *
     * @var int
     */
    protected $code;

    /**
     * The keys which value should be clean.
     *
     * @var array|null
     */
    protected $cleanKeys;

    /**
     * Create an ApiResponse instance.
     *
     * @param  mixed  $data
     * @param  int|null  $code
     * @param  array  $headers
     * @param  int  $options
     */
    public function __construct($data = null, $code = null, $headers = [], $options = 0)
    {
        $this->code = is_null($code) ? static::successCode() : (int) $code;

        parent::__construct($data, 200, $headers, $options);
    }

    /**
     * Get the code key.
     *
     * @return string
     */
    public static function codeKey()
    {
        static $codeKey = null;

        if (is_null($codeKey)) {
            $codeKey = config('api.response.key.code', 'code');
        }

        return $codeKey;
    }

    /**
     * Get the message key.
     *
     * @return string
     */
    public static function messageKey()
    {
        static $messageKey = null;

        if (is_null($messageKey)) {
            $messageKey = config('api.response.key.message', 'msg');
        }

        return $messageKey;
    }

    /**
     * Get the success code.
     *
     * @return int
     */
    public static function successCode()
    {
        static $successCode = null;

        if (is_null($successCode)) {
            $successCode = (int) config('api.response.code.success', 1);
        }

        return $successCode;
    }

    /**
     * Sets the data to be sent as JSON.
     *
     * @param  mixed  $data
     * @return $this
     */
    public function setData($data = null)
    {
        if ($data instanceof Model) {
            $data = [snake_case(class_basename($data)) => $this->convertObjectToArray($data)];
        } elseif (is_object($data)) {
            $data = $this->convertObjectToArray($data);
        } elseif (is_null($data)) {
            $data = [];
        } elseif (is_string($data)) {
            $data = [static::messageKey() => $data];
        }

        if (! is_array($data)) {
            $data = [static::messageKey() => json_encode($data)];
        }

        if (! array_key_exists(static::codeKey(), $data)) {
            $data[static::codeKey()] = $this->getCode();
        }

        if (! is_null($this->cleanKeys)) {
            $data = $this->cleanArray($data, $this->cleanKeys);
        }

        return parent::setData($data);
    }

    /**
     * Convert an object to array.
     *
     * @param  mixed  $object
     * @return array
     */
    protected function convertObjectToArray($object)
    {
        if (method_exists($object, 'toArray')) {
            return $object->toArray();
        }

        return json_decode(json_encode($object, true), true);
    }

    /**
     * Clean the given array.
     *
     * @param  array  $array
     * @param  array|null  $keys
     * @return array
     */
    protected function cleanArray($array, $keys = null)
    {
        $keys = $keys ?: array_keys($array);

        foreach ($keys as $key) {
            if (is_array($value = Arr::get($array, $key))) {
                Arr::set($array, $key, array_filter($value));
            }
        }

        return $array;
    }

    /**
     * Merge new data into the current data.
     *
     * @param  array  ...$data
     * @return $this
     */
    public function mergeData(array ...$data)
    {
        return $this->setData(array_replace($this->getData(true), ...$data));
    }

    /**
     * Get the api result code.
     *
     * @return int
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * Set the api result code.
     *
     * @param  int  $code
     * @return $this
     */
    public function setCode($code)
    {
        $this->code = (int) $code;

        return $this->mergeData([static::codeKey() => $this->code]);
    }

    /**
     * Set the api result code.
     *
     * @param  int  $code
     * @return $this
     */
    public function code($code)
    {
        return $this->setCode($code);
    }

    /**
     * Get the api result message.
     *
     * @return string
     */
    public function getMessage()
    {
        return Arr::get($this->getData(true), static::messageKey());
    }

    /**
     * Set the api result message.
     *
     * @param  string  $message
     * @return $this
     */
    public function setMessage($message)
    {
        return $this->mergeData([static::messageKey() => (string) $message]);
    }

    /**
     * Set the api result message.
     *
     * @param  string  $message
     * @return $this
     */
    public function message($message)
    {
        return $this->setMessage($message);
    }

    /**
     * Get the keys which value should be clean.
     *
     * @return array|null
     */
    public function getCleanKeys()
    {
        return $this->cleanKeys;
    }

    /**
     * Set the keys which value should be clean, then clean data.
     * The passed $keys can be "dot" notation.
     *
     * $keys example:
     *
     * null             -> do not clean anything
     * []               -> clean values associated with all root keys
     * 'foo', 'foo.bar' -> clean values associated with 'foo' and 'foo'>'bar'
     * ['foo', 'foo.bar']
     *
     * @param  string|null|string[]  $keys
     * @return $this
     */
    public function clean($keys = [])
    {
        if (is_null($keys)) {
            $this->cleanKeys = null;

            return $this;
        }

        $this->cleanKeys = is_array($keys) ? $keys : func_get_args();

        return $this->setData($this->getData(true));
    }

    /**
     * Set the response status code.
     *
     * @param  int  $code
     * @param  mixed  $text
     * @return $this
     */
    public function statusCode($code, $text = null)
    {
        return $this->setStatusCode($code, $text);
    }
}


<?php

namespace Interpro\ImageAggr\Settings;

use Interpro\Core\Contracts\Taxonomy\Types\BlockType;
use Interpro\ImageAggr\Exception\ImageAggrException;
use Interpro\ImageAggr\Contracts\Settings\Enum\GenVariant;
use Interpro\ImageAggr\Contracts\Settings\Enum\ModVariant;
use Interpro\ImageAggr\Contracts\Settings\Enum\Position;
use Interpro\ImageAggr\Contracts\Settings\GenSettingsSetFactory as GenSettingsSetFactoryInterface;
use Interpro\ImageAggr\Settings\Collection\CropSettingsSet;
use Interpro\ImageAggr\Settings\Collection\ModSet;
use Interpro\ImageAggr\Settings\Collection\ResizeSettingsSet;

class GenSettingsSetFactory implements GenSettingsSetFactoryInterface
{
    private $crop_config;
    private $resize_config;
    private $resizes;
    private $crops;
    private $modImagesType;
    private $positions;

    /**
     * @param \Interpro\Core\Contracts\Taxonomy\Types\BlockType $modImagesType
     * @param array $resize_config
     * @param array $crop_config
     * @return void
     */
    public function __construct(BlockType $modImagesType, array $resize_config, array $crop_config)
    {
        $this->resize_config = $resize_config;
        $this->crop_config   = $crop_config;
        $this->resizes       = [];
        $this->crops         = [];
        $this->modImagesType = $modImagesType;
        $this->positions     = [
            Position::CENTER,
            Position::TOP,
            Position::TOP_LEFT,
            Position::TOP_RIGHT,
            Position::BOTTOM,
            Position::BOTTOM_LEFT,
            Position::BOTTOM_RIGHT,
            Position::LEFT,
            Position::RIGHT
        ];
    }

    private function createMods(array $attrs, $from_mod_section = false)
    {
        $modSettings = [];

        if(array_key_exists('mods', $attrs))
        {
            if($from_mod_section)
            {
                throw new ImageAggrException('Нельзя модифицировать картинки, предназначенные для модификации!');
            }

            $mods = $attrs['mods'];

            if(!is_array($mods))
            {
                throw new ImageAggrException('Модификаторы (mods) должны быть заданы массивом, передано '.gettype($mods).'!');
            }

            foreach($mods as $mod_name => $params)
            {
                if(!is_string($mod_name))
                {
                    throw new ImageAggrException('Имя модификатора должно быть задано строкой!');
                }

                if($mod_name !== ModVariant::MASK and $mod_name !== ModVariant::WMARK)
                {
                    throw new ImageAggrException('Имя модификатора должно быть '.ModVariant::MASK.' или '.ModVariant::WMARK.', передано '.$mod_name.'!');
                }

                if(!is_array($params))
                {
                    throw new ImageAggrException('Параметры модификации должны быть заданы массивом передано '.gettype($params).'!');
                }

                if(array_key_exists('image_key', $params))
                {
                    $image_key = $params['image_key'];
                }
                else
                {
                    throw new ImageAggrException('В параметрах модификации должен присутствовать ключ модификации картинки (image_key)!');
                }

                $position = Position::CENTER;

                $x = 0;
                $y = 0;

                if(array_key_exists('position', $params))
                {
                    if(in_array($params['position'], $this->positions))
                    {
                        $position = $params['position'];
                    }
                    else
                    {
                        throw new ImageAggrException('Позиция в параметрах модификации должна задаваться одним из следующих строковых значений '.implode(', ', $this->positions).', а передано '.$params['position'].'!');
                    }
                }

                if(array_key_exists('x', $params))
                {
                    if(is_int($params['x']) and $params['x']>=0)
                    {
                        $x = $params['x'];
                    }
                    else
                    {
                        throw new ImageAggrException('Координата (x) в параметрах модификации должна задаваться целым положительным числом, передано '.$params['x'].'!');
                    }
                }

                if(array_key_exists('y', $params))
                {
                    if(is_int($params['y']) and $params['y']>=0)
                    {
                        $y = $params['y'];
                    }
                    else
                    {
                        throw new ImageAggrException('Координата (y) в параметрах модификации должна задаваться целым положительным числом, передано '.$params['y'].'!');
                    }
                }

                $gen_path = explode('.', $image_key);

                if(count($gen_path) !== 3)
                {
                    throw new ImageAggrException('Картинка модификатора должна быть задана строкой имя_картинки.генерация.имя_генерации, передано '.$image_key.'!');
                }

                //Проверяем, есть ли такая картинка в сервис блоке
                $field = $this->modImagesType->getField($gen_path[0]);
                $fieldType = $field->getFieldType();

                if($fieldType->getName() !== 'image')
                {
                    throw new ImageAggrException('Картинка модификатора должна ссылаться на тип image, передано ('.$image_key.') '.$fieldType->getName().'!');
                }

                $gen_var = $gen_path[1];

                if($gen_var === GenVariant::RESIZE)
                {
                    $gen = $this->createResizeSetting($gen_path[2], true);
                }
                elseif($gen_var === GenVariant::CROP)
                {
                    $gen = $this->createCropSetting($gen_path[2], true);
                }
                else
                {
                    throw new ImageAggrException('Вариант генерации модификатора должен быть ресайзом (RESIZE) или кропом (CROP), передан ('.$image_key.') '.$gen_var.'!');
                }

                //Создаем модификатор
                $modSettings[$mod_name] = new ModSetting($gen, $field, $mod_name, $position, $x, $y);
            }
        }

        $modSettingsSet = new ModSet($modSettings);

        return $modSettingsSet;
    }

    private function createResizeSetting($resize_name, $from_mod_section = false)
    {
        if(array_key_exists($resize_name, $this->resizes))
        {
            return $this->resizes[$resize_name];
        }

        if(!array_key_exists($resize_name, $this->resize_config))
        {
            throw new ImageAggrException('Настройка ресайза по имени '.$resize_name.' отсутствует!');
        }

        $attrs = $this->resize_config[$resize_name];

        if(array_key_exists('width', $attrs))
        {
            $width = $attrs['width'];
            if(!is_null($width))
            {
                if(!is_int($width))
                {
                    throw new ImageAggrException('Ширина ресайза (width) '.$resize_name.' должна быть задана целым положительным числом или null значением, передано '.gettype($width).'!');
                }
            }
        }
        else
        {
            $width = null;
        }

        if(array_key_exists('height', $attrs))
        {
            $height = $attrs['height'];

            if(!is_null($height))
            {
                if(!is_int($height))
                {
                    throw new ImageAggrException('Высота ресайза (height) '.$resize_name.' должна быть задана целым положительным числом или null значением, передано '.gettype($height).'!');
                }
            }
        }
        else
        {
            $height = null;
        }

        //Если нет размеров ресайза, значит просто применяем моды к оригиналу и сохраняем в ресайз
        //if(is_null($width) and is_null($height))
        //{
        //    throw new ImageAggrException('В настройке ресайза '.$resize_name.' высота (width) и ширина (height) заданы null значением, должно быть задано хотя бы одно значение числом больше нуля(0)!');
        //}

        $modSettingsSet = $this->createMods($attrs, $from_mod_section);

        if(array_key_exists('when_upload', $attrs))
        {
            $when_upload = $attrs['when_upload'];

            if(!is_bool($when_upload))
            {
                throw new ImageAggrException('Признак служебного ресайза (when_upload) '.$resize_name.' должен быть задан булевым значением, передано '.gettype($when_upload).'!');
            }
        }
        else
        {
            $when_upload = false;
        }

        $resizeSetting = new ResizeSetting($resize_name, $width, $height, $modSettingsSet, $when_upload);

        //Закэшируем, чтобы экземпляры не повторялись
        $this->resizes[$resize_name] = $resizeSetting;

        return $resizeSetting;
    }

    private function createCropSetting($crop_name, $from_mod_section = false)
    {
        if(array_key_exists($crop_name, $this->crops))
        {
            return $this->crops[$crop_name];
        }

        if(!array_key_exists($crop_name, $this->crop_config))
        {
            throw new ImageAggrException('Настройка кропа по имени '.$crop_name.' отсутствует!');
        }

        $attrs = $this->crop_config[$crop_name];

        if(array_key_exists('width', $attrs))
        {
            $width = $attrs['width'];

            if(!is_int($width))
            {
                throw new ImageAggrException('Ширина кропа (width) '.$crop_name.' должна быть задана целым положительным числом, передано '.gettype($width).'!');
            }
        }
        else
        {
            throw new ImageAggrException('Ширина кропа (width) '.$crop_name.' отсутствует в настройке!');
        }

        if(array_key_exists('height', $attrs))
        {
            $height = $attrs['height'];

            if(!is_int($height))
            {
                throw new ImageAggrException('Высота кропа (height) '.$crop_name.' должна быть задана целым положительным числом, передано '.gettype($height).'!');
            }
        }
        else
        {
            throw new ImageAggrException('Высота кропа (height) '.$crop_name.' отсутствует в настройке!');
        }

        if(array_key_exists('man', $attrs))
        {
            $man_name = $attrs['man'];

            if(!is_string($man_name))
            {
                throw new ImageAggrException('Имя ресайза виджета для кропа (man) '.$crop_name.' должно быть задано строкой, передано '.gettype($height).'!');
            }

            $man = $this->createResizeSetting($man_name);
        }
        else
        {
            throw new ImageAggrException('Имя ресайза виджета для кропа (man) '.$crop_name.' отсутствует в настройке!');
        }

        if(array_key_exists('target', $attrs))
        {
            $target_name = $attrs['target'];

            if(!is_string($target_name))
            {
                throw new ImageAggrException('Имя ресайза цели для кропа (target) '.$crop_name.' должно быть задано строкой, передано '.gettype($target_name).'!');
            }

            $target = $this->createResizeSetting($target_name);
        }
        else
        {
            throw new ImageAggrException('Имя ресайза цели для кропа (target) '.$crop_name.' отсутствует в настройке!');
        }

        $modSettingsSet = $this->createMods($attrs, $from_mod_section);

        $cropSetting = new CropSetting($crop_name, $width, $height, $man, $target, $modSettingsSet);

        //Закэшируем, чтобы экземпляры не повторялись
        $this->crops[$crop_name] = $cropSetting;

        return $cropSetting;
    }

    /**
     * @param array $resize_names
     *
     * @return \Interpro\ImageAggr\Contracts\Settings\Collection\ResizeSettingsSet
     */
    public function createResizeSettingsSet($resize_names = [])
    {
        $resizeSettings = [];

        foreach($resize_names as $resize_name)
        {
            $resizeSettings[$resize_name] = $this->createResizeSetting($resize_name);
        }

        $resizeSettingsSet = new ResizeSettingsSet($resizeSettings);

        return $resizeSettingsSet;
    }

    /**
     * @param array $crop_names
     *
     * @return \Interpro\ImageAggr\Contracts\Settings\Collection\CropSettingsSet
     */
    public function createCropSettingsSet($crop_names = [])
    {
        $cropSettings = [];

        foreach($crop_names as $crop_name)
        {
            $cropSettings[$crop_name] = $this->createCropSetting($crop_name);
        }

        $cropSettingsSet = new CropSettingsSet($cropSettings);

        return $cropSettingsSet;
    }
}


<?php

namespace Interpro\ImageAggr;

use Illuminate\Bus\Dispatcher;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Interpro\ImageAggr\Settings\GenSettingsSetFactory;
use Interpro\ImageAggr\Settings\ImageSettingsSetFactory;
use Interpro\ImageAggr\Settings\PathResolver;

class ImageAggrUseServiceProvider extends ServiceProvider {

    /**
     * @return void
     */
    public function boot(Dispatcher $dispatcher)
    {
        //Log::info('Загрузка ImageAggrUseServiceProvider');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //Log::info('Регистрация ImageAggrUseServiceProvider');

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Db\ImageAggrDbAgent',
            'Interpro\ImageAggr\Db\ImageAggrDbAgent'
        );

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Settings\PathResolver',
            function($app)
            {
                $test = $app->runningUnitTests();
                return new PathResolver(config('interpro.imageaggr.paths', []), $test);
            }
        );

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Settings\GenSettingsSetFactory',
            function($app)
            {
                $taxonomy = $app->make('Interpro\Core\Contracts\Taxonomy\Taxonomy');
                $modImagesType = $taxonomy->getType('modimages');
                return new GenSettingsSetFactory($modImagesType, config('interpro.resizes', []), config('interpro.crops', []));
            }
        );

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Settings\ImageSettingsSetFactory',
            function($app)
            {
                $taxonomy = $app->make('Interpro\Core\Contracts\Taxonomy\Taxonomy');
                $factory = $app->make('Interpro\ImageAggr\Contracts\Settings\GenSettingsSetFactory');

                return new ImageSettingsSetFactory($taxonomy, config('interpro.images', []), $factory);
            }
        );

        //----------------------------------------------------------------
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\CleanOperation',
            'Interpro\ImageAggr\Operation\CleanOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\CleanPhOperation',
            'Interpro\ImageAggr\Operation\CleanPhOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\CropOperation',
            'Interpro\ImageAggr\Operation\CropOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\DeleteOperation',
            'Interpro\ImageAggr\Operation\DeleteOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\InitOperation',
            'Interpro\ImageAggr\Operation\InitOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\RefreshOperation',
            'Interpro\ImageAggr\Operation\RefreshOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\SaveOperation',
            'Interpro\ImageAggr\Operation\SaveOperation'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\UploadOperation',
            'Interpro\ImageAggr\Operation\UploadOperation'
        );
        //---------------------------------------------------------
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\Owner\OwnerDeleteOperationsCall',
            'Interpro\ImageAggr\Operation\Owner\OwnerDeleteOperationsCall'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\Owner\OwnerInitOperationsCall',
            'Interpro\ImageAggr\Operation\Owner\OwnerInitOperationsCall'
        );
        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Operation\Owner\OwnerSaveOperationsCall',
            'Interpro\ImageAggr\Operation\Owner\OwnerSaveOperationsCall'
        );
        //---------------------------------------------------------

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Settings\Collection\ImageSettingsSet',
            function($app)
            {
                $factory = $app->make('Interpro\ImageAggr\Contracts\Settings\ImageSettingsSetFactory');
                return $factory->create();
            }
        );

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\Placeholder\PlaceholderAgent',
            'Interpro\ImageAggr\Placeholder\PlaceholderAgent'
        );

        $this->app->singleton(
            'Interpro\ImageAggr\Contracts\CommandAgents\OperationsAgent',
            'Interpro\ImageAggr\CommandAgents\OperationsAgent'
        );

        $this->app->make('Interpro\ImageAggr\Http\ImageOperationController');

        include __DIR__ . '/Http/routes.php';
    }

}


<?php

namespace ElfSundae\Laravel\Api\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;

class ProfileJsonResponse
{
    /**
     * Handle an incoming request.
     *
     * @see https://github.com/barryvdh/laravel-debugbar/issues/252#issuecomment-248343762
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if (
            $response instanceof JsonResponse &&
            app()->bound('debugbar') &&
            app('debugbar')->isEnabled() &&
            is_object($response->getData())
        ) {
            $response->setData($response->getData(true) + [
                '_debugbar' => app('debugbar')->getData(),
            ]);
        }

        return $response;
    }
}


<?php

namespace Interpro\ImageAggr\Operation;

use Interpro\Core\Contracts\Ref\ARef;
use Interpro\ImageAggr\Contracts\Operation\CleanOperation as CleanOperationInterface;
use Interpro\ImageAggr\Contracts\Settings\ImageSetting;

class CleanOperation extends Operation implements CleanOperationInterface
{
    /**
     * @param \Interpro\Core\Contracts\Ref\ARef
     * @param \Interpro\ImageAggr\Contracts\Settings\ImageSetting $imageSetting
     *
     * @return void
     */
    public function execute(ARef $aRef, ImageSetting $imageSetting)
    {
        $this->checkOwner($aRef);

        $this->deleteAllFiles($aRef, $imageSetting);

        $this->dbAgent->imageToDb($aRef, $imageSetting, ['link' => '']);

        $this->makeSameImageResizes($aRef, $imageSetting, '');
        $this->makeSameImageCrops($aRef, $imageSetting, '');
    }
}


<?php

namespace Ntavelis\AuthEmail\Commands\Actions;

class CreateFiles extends Files {

    /**
     * Generate our own files.
     */
    public function run()
    {
        //Create controller files
        foreach ($this->getControllers() as $fileName => $filePath) {
            $this->makeDirectory($filePath);
            $this->filesystem->put($filePath, $this->compileStub($fileName));
        }

        //Create blades
        foreach ($this->getBlades() as $fileName => $filePath) {
            $this->makeDirectory($filePath);
            $this->filesystem->put($filePath, $this->compileStub($fileName));
        }

        //Create migration files
        foreach ($this->getMigrations() as $fileName => $filePath) {
            $this->filesystem->put($filePath, $this->compileStub($fileName));
        }

        //Create activation mail, if the --queue flag is passed, then it implements the ShouldQueue interface.
        foreach ($this->getEmails() as $fileName => $filePath) {
            $this->makeDirectory($filePath);
            $stub = $this->filesystem->get(__DIR__ . '/../../stubs/' . $fileName . '.stub');

            $this->filesystem->put($filePath, $this->replaceShouldQueue($stub));
        }

        //Create language files
        foreach ($this->getLanguages() as $fileName => $filePath) {
            $this->filesystem->put($filePath, $this->compileStub($fileName));
        }
    }
}


<?php

namespace Cundd\Noshi\Command;

/**
 * Abstract controller for CLI tools
 *
 * @package Cundd\Noshi\Command
 */
abstract class AbstractCommandController
{
    /**
     * ASCII command escape
     */
    const ESCAPE = "\033";

    /**
     * ASCII style normal
     */
    const NORMAL = "[0m";

    /**
     * ASCII color green
     */
    const GREEN = "[0;32m";

    /**
     * ASCII color red
     */
    const RED = "[0;31m";

    /**
     * Raw input arguments
     *
     * @var array
     */
    protected $rawArguments = [];

    /**
     * Prepared arguments
     *
     * @var array
     */
    protected $arguments = [];

    /**
     * Command
     *
     * The first element of the arguments
     *
     * @var string
     */
    protected $command = '';

    /**
     * Path to the script
     *
     * @var string
     */
    protected $scriptPath = '';

    function __construct($arguments)
    {
        $this->rawArguments = $arguments;
    }

    /**
     * Invokes the correct command
     */
    public function dispatch()
    {
        $arguments = $this->rawArguments;
        $this->scriptPath = array_shift($arguments);
        $this->command = array_shift($arguments);
        $this->arguments = $this->parseArguments($arguments);

        if (!$this->command) {
            $this->outputError('No command given');
            $this->command = 'help';
        }

        $commandName = $this->command . 'Command';
        if (is_callable([$this, $commandName])) {
            $exitCode = call_user_func_array([$this, $commandName], $this->arguments);
        } else {
            $this->outputError('Command ' . $this->command . ' could not be found');
            $exitCode = 1;
        }
        die($exitCode);
    }

    /**
     * @param $arguments
     * @return array
     */
    public function parseArguments($arguments)
    {
        $parsedArguments = [];
        $argumentsCount = count($arguments);
        for ($i = 0; $i < $argumentsCount; $i++) {
            $currentArgument = $arguments[$i];
            switch (true) {
                case substr($currentArgument, 0, 2) === '--':
                    $parsedArguments[substr($currentArgument, 2)] = true;
                    break;

                case substr($currentArgument, 0, 1) === '-':
                    $parsedArguments[substr($currentArgument, 1)] = $arguments[$i + 1];
                    $i++;
                    break;

                default:
                    $parsedArguments[] = $currentArgument;
            }
        }

        return $parsedArguments;
    }

    /**
     * Prints the given data in a table
     *
     * @param array  $data      Table data to display
     * @param string $delimiter Delimiter for table cells
     */
    public function outputTable($data, $delimiter = '|')
    {
        $output = '';
        $firstRow = reset($data);
        $columnWidths = [];

        $columnCount = count($firstRow);
        $headerRow = array_keys($firstRow);

        if (!(is_integer(reset($headerRow)) && is_integer(end($headerRow)))) {
            // Add the header row to the data to detect the longest string
            array_unshift($data, $headerRow);
        } else {
            $headerRow = [];
        }

        // Collect the column widths
        for ($columnIndex = 0; $columnIndex < $columnCount; $columnIndex++) {
            $columnWidths[$columnIndex] = max(
                array_map(
                    function ($row) use ($columnIndex) {
                        $row = array_values($row);

                        return (isset($row[$columnIndex]) ? strlen($row[$columnIndex]) : 0);
                    },
                    $data
                )
            );
        }

        /*
         * Print the header if it is defined
         */
        if ($headerRow) {
            // Remove the header row to the data after detecting the longest string
            array_shift($data);

            // Add the header
            $output .= $delimiter . ' ';
            foreach ($headerRow as $columnIndex => $cell) {
                $output .= ''
                    . str_pad($cell, $columnWidths[$columnIndex])
                    . ' ' . $delimiter . ' ';
            }
            $output .= PHP_EOL;

            // Add the line below the header
            $output .= $delimiter . ' ';
            foreach ($headerRow as $columnIndex => $cell) {
                $output .= ''
                    . str_repeat('-', $columnWidths[$columnIndex])
                    . ' ' . $delimiter . ' ';
            }
            $output .= PHP_EOL;
        }

        /*
         * Print the table
         */
        foreach ($data as $row) {
            $row = array_values($row);

            $output .= $delimiter . ' ';
            foreach ($row as $columnIndex => $cell) {
                if (is_bool($cell)) {
                    $cell = $cell ? 'TRUE' : 'FALSE';
                }
                $output .= ''
                    . str_pad($cell, $columnWidths[$columnIndex])
                    . ' ' . $delimiter . ' ';
            }
            $output .= PHP_EOL;
        }
        $this->output($output);
    }

    /**
     * Prints the given message to the console and adds a newline at the end
     *
     * @param string $message
     */
    public function outputLine($message)
    {
        $this->output($message . PHP_EOL);
    }

    /**
     * Prints the given message to the console
     *
     * @param string $message
     */
    public function output($message)
    {
        fwrite(STDOUT, $message);
    }

    /**
     * Prints the given error to the console
     *
     * @param string|\Exception $error
     */
    public function outputError($error)
    {
        $message = self::ESCAPE . self::RED;
        if (is_scalar($error)) {
            $message .= $error;
        } else {
            if (is_object($error) && $error instanceof \Exception) {
                $message .= '#' . $error->getCode() . ': ' . $error->getMessage();
            }
        }
        $message .= PHP_EOL;
        $message .= self::ESCAPE . self::NORMAL;
        fwrite(STDERR, $message);
    }

    /**
     * Displays this message
     */
    public function helpCommand()
    {
        $availableCommands = $this->getAvailableCommands();
        $longestCommandNameLength = max(
            array_map(
                function ($item) {
                    return strlen($item);
                },
                array_keys($availableCommands)
            )
        );

        $longestCommandNameLength += 4;
        foreach ($availableCommands as $command => $help) {
            $line = ''
                . self::ESCAPE . self::GREEN
                . str_pad($command, $longestCommandNameLength)
                . self::ESCAPE . self::NORMAL
                . $help;
            $this->outputLine($line);
        }
    }

    /**
     * Returns the available commands
     *
     * @return array
     */
    public function getAvailableCommands()
    {
        $commands = [];
        $classReflection = new \ReflectionClass(get_class($this));
        $methods = $classReflection->getMethods(\ReflectionMethod::IS_PUBLIC);
        /** @var \ReflectionMethod $method */
        foreach ($methods as $method) {
            $methodDescription = [];
            $methodName = $method->name;
            $docComment = $method->getDocComment();
            $docCommentLines = explode(PHP_EOL, $docComment);

            if (substr($methodName, -7) !== 'Command') {
                continue;
            }

            foreach ($docCommentLines as $currentLine) {
                $currentLine = trim($currentLine);
                if (substr($currentLine, 0, 2) === '/*') {
                    continue;
                }

                if (substr($currentLine, 0, 1) === '*') {
                    $currentLine = substr($currentLine, 1);
                }

                $currentLine = trim($currentLine);
                if (!$currentLine) {
                    continue;
                }
                if ($currentLine[0] === '@') {
                    continue;
                }
                if ($currentLine === '/') {
                    continue;
                }
                $methodDescription[] = trim($currentLine);
            }
            $commands[substr($methodName, 0, -7)] = implode(' ', $methodDescription);
        }

        return $commands;
    }

}


<?php

namespace Darsyn\ClassFinder;

/**
 * @author Zander Baldwin <hello@zanderbaldwin.com>
 */
class MultiClassFinder extends ClassFinder implements MultiClassFinderInterface
{
    /**
     * @access protected
     * @var array
     */
    protected $locations = array();

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

    /**
     * Set Locations
     *
     * @access public
     * @param array $locations
     * @return self
     */
    public function setLocations(array $locations)
    {
        $this->locations = array();
        foreach ($locations as $namespace => $location) {
            $this->addLocation($namespace, $location);
        }
        return $this;
    }

    /**
     * Add Location
     *
     * @access public
     * @param string $namespace
     * @param string $location
     * @return self
     */
    public function addLocation($namespace, $location)
    {
        $this->locations[$namespace] = $location;
        return $this;
    }

    /**
     * Find Classes
     *
     * @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->locations as $namespace => $location) {
            $this->setRootDirectory($location);
            $this->setRootNamespace($namespace);
            $classes = array_merge($classes, parent::findClasses($subDir, $suffix, $parent, $reflection));
        }
        return $classes;
    }
}


<?php

namespace conquer\i18n;

use yii\di\Instance;
use conquer\i18n\models\I18nMessage;
use yii\i18n\MissingTranslationEvent;
use yii\caching\Cache;
use conquer\i18n\models\I18nTranslator;
use conquer\i18n\models\I18nTranslation;

class MessageSource extends \yii\i18n\MessageSource
{
    private $_messages;

    /**
     * @var Cache|array|string the cache object or the application component ID of the cache object.
     * The messages data will be cached using this cache object. Note, this property has meaning only
     * in case [[cachingDuration]] set to non-zero value.
     */
    public $cache = 'cache';
    /**
     * @var integer the time in seconds that the messages can remain valid in cache.
     * Use 0 to indicate that the cached data will never expire.
     * @see enableCaching
     */
    public $cachingDuration = 0;
    /**
     * @var boolean whether to enable caching translated messages
     */
    public $enableCaching = false;
    /**
     *
     * @var TranslatorInterface
     */
    public $translator;
    /**
     *
     * @var boolean
     */
    public $async = false;

    /**
     * Initializes the DbMessageSource component.
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
     * Configured [[cache]] component would also be initialized.
     * @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
     */
    public function init()
    {
        parent::init();
        $this->translator = Instance::ensure($this->translator, 'conquer\i18n\TranslatorInterface');
        if ($this->enableCaching) {
            $this->cache = Instance::ensure($this->cache, Cache::className());
        }
    }

    /**
     * Loads the message translation for the specified language and category.
     * If translation for specific locale code such as `en-US` isn't found it
     * tries more generic `en`.
     *
     * @param string $category the message category
     * @param string $language the target language
     * @return array the loaded messages. The keys are original messages, and the values
     * are translated messages.
     */
    protected function loadMessages($category, $language)
    {
        if ($this->enableCaching) {
            $key = [
                    __CLASS__,
                    $category,
                    $language,
            ];
            $messages = $this->cache->get($key);
            if ($messages === false) {
                $messages = I18nMessage::loadMessagesFromDb($category, $language);
                $this->cache->set($key, $messages, $this->cachingDuration);
            }

            return $messages;
        } else {
            return I18nMessage::loadMessagesFromDb($category, $language);
        }
    }

    /**
     * Translates the specified message.
     * If the message is not found, a [[EVENT_MISSING_TRANSLATION|missingTranslation]] event will be triggered.
     * If there is an event handler, it may provide a [[MissingTranslationEvent::$translatedMessage|fallback translation]].
     * If no fallback translation is provided this method will return `false`.
     * @param string $category the category that the message belongs to.
     * @param string $message the message to be translated.
     * @param string $language the target language.
     * @return string|boolean the translated message or false if translation wasn't found.
     */
    protected function translateMessage($category, $message, $language)
    {
        $key = $language . '/' . $category;
        if (!isset($this->_messages[$key])) {
            $this->_messages[$key] = $this->loadMessages($category, $language);
        }
        if (isset($this->_messages[$key][$message])) {
            return $this->_messages[$key][$message];
        } else {
            $i18nMessage = I18nMessage::getMessage($category, $message);
            if ($this->async) {
                $i18nMessage->getTranslation($language);
            } else {
                $i18nTranslator = I18nTranslator::getTranslator(get_class($this->translator));
                $i18nTranslation = $i18nMessage->getTranslation($language, $i18nTranslator);
                $i18nTranslation->translator_id = $i18nTranslator->translator_id;
                $sourceLang = explode('-', $this->sourceLanguage)[0];
                $targetLang = explode('-', $language)[0];
                $translation = $this->translator->translate($message, $sourceLang, $targetLang);
                if ($translation) {
                    $i18nTranslation->translation = $translation;
                    $i18nTranslation->status = I18nTranslation::STATUS_DONE;
                    $i18nTranslation->save(false);
                    return $this->_messages[$key][$message] = $translation;
                } else {
                    $i18nTranslation->status = I18nTranslation::STATUS_ERROR;
                    $i18nTranslation->error_message = $this->translator->getError();
                    $i18nTranslation->save(false);
                }
            }
        }
        return $this->_messages[$key][$message] = false;
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Thanasis
 * Date: 07/02/2017
 * Time: 10:44
 */

namespace Ntavelis\AuthEmail\Commands\Actions;

use Illuminate\Container\Container;
use Illuminate\Filesystem\Filesystem;

abstract class FilesInteractions {

    /**
     * The filesystem instance.
     *
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * Holds the Laravel's version
     * @var float
     */
    protected $laravelVersion;

    /**
     * Files constructor.
     * @param Filesystem $filesystem
     */
    public function __construct(Filesystem $filesystem)
    {
        $this->filesystem = $filesystem;
        $this->laravelVersion = (float) Container::getInstance()->version();
    }

    /**
     * Build the directory for the class if necessary.
     *
     * @param  string $path
     * @return string
     */
    protected function makeDirectory($path)
    {
        if (!$this->filesystem->isDirectory(dirname($path))) {
            $this->filesystem->makeDirectory(dirname($path), 0777, true, true);
        }
    }

    /**
     * Compile the migration stub.
     *
     * @param $fileName
     * @return string
     */
    protected function compileStub($fileName)
    {
        $stub = $this->filesystem->get(__DIR__ . '/../../stubs/' . $fileName . '.stub');

        return $stub;
    }

    /**
     * Append to a file a particular stub.
     * @param $file
     * @param $stub
     * @return int
     */
    protected function AppendTo($file, $stub)
    {
        return $this->filesystem->append(base_path() . '/routes/' . $file . '.php', $this->compileStub($stub));
    }

    /**
     * Replace the {{ShouldQueue}} from Activation mail template.
     * @param $stub
     * @return $this
     */
    protected function replaceShouldQueue(&$stub)
    {
        if (ShouldQueue::$bool) {
            return $stub = str_replace('{{ShouldQueue}}', 'implements ShouldQueue', $stub);
        }

        return $stub = str_replace('{{ShouldQueue}}', '', $stub);
    }

    /**
     * Open haystack, find and replace needles, save haystack.
     *
     * @param  string $oldFile The haystack
     * @param  mixed $search String or array to look for (the needles)
     * @param  mixed $replace What to replace the needles for?
     * @param  string $newFile Where to save, defaults to $oldFile
     *
     * @return void
     */
    public function replaceAndSave($oldFile, $search, $replace, $newFile = null)
    {
        if (!isset($newFile) || $newFile == null) {
            $newFile = $oldFile;
        }
        $file = $this->filesystem->get($oldFile);
        $replacing = str_replace($search, $replace, $file);
        $this->filesystem->put($newFile, $replacing);
    }
}


<?php

namespace Cundd\Noshi;

use Cundd\Noshi\Domain\Model\Page;
use Cundd\Noshi\Domain\Repository\PageRepository;
use Cundd\Noshi\Helpers\MarkdownFactory;
use Cundd\Noshi\Ui\View;

class Dispatcher
{
    /**
     * Request URI
     *
     * @var string
     */
    protected $uri = '';

    /**
     * Original request URI
     *
     * @var string
     */
    protected $originalUri = '';

    /**
     * Request method
     *
     * @var string
     */
    protected $method = '';

    /**
     * Return the raw result
     *
     * @var bool
     */
    protected $raw = false;

    /**
     * Page object for the current URI
     *
     * @var Page
     */
    protected $page = null;

    /**
     * Shared Dispatcher instance
     *
     * @var Dispatcher
     */
    static protected $sharedDispatcher = null;

    /**
     * Dispatch the given request URI
     *
     * @param string $uri
     * @param string $method
     * @param array  $arguments
     * @return Response
     */
    public function dispatch($uri, $method = 'GET', $arguments = [])
    {
        $this->originalUri = $uri;
        $this->uri = $this->prepareUri($uri);

        $methods = [
            'GET',
            'HEAD',
            'POST',
            'PUT',
            'DELETE',
            'TRACE',
            'OPTIONS',
            'CONNECT',
            'PATCH',
        ];
        $method = strtoupper($method);
        $this->method = in_array($method, $methods) ? $method : 'GET';

        try {
            // Get the response
            $response = $this->getResponse();

            if (!$this->raw) {
                $response = $this->createTemplateResponse($response);
            }

            // Output the response
            echo $response;

            return $response;
        } catch (\Exception $exception) {
            $fileHandle = fopen('php://stderr', 'w');
            fwrite($fileHandle, (string)$exception);
            if (ConfigurationManager::getConfiguration()->isDevelopmentMode()) {
                echo new Response('An error occurred: ' . $exception, 500);
            } else {
                echo new Response('An error occurred', 500);
            }
        }

        return '';
    }

    /**
     * Fill the template with the contents
     *
     * @param Response $response
     * @return Response
     */
    public function createTemplateResponse($response)
    {
        $page = $this->getPage();

        $view = new View();
        $view->setContext($this);
        $view->setTemplatePath($this->getTemplatePath());
        $configuration = ConfigurationManager::getConfiguration();
        $view->assignMultiple(
            [
                'page'          => $page,
                'meta'          => $page ? $page->getMeta() : [],
                'content'       => $response->getBody(),
                'response'      => $response,
                'resourcePath'  => $configuration->getResourceDirectoryUri(),
                'configuration' => $configuration,
            ]
        );

        return new Response(
            $view->render(),
            $response->getStatusCode(),
            $response->getStatusText()
        );
    }

    /**
     * Returns the template
     *
     * @return string
     */
    public function getTemplatePath()
    {
        $configuration = ConfigurationManager::getConfiguration();

        return $configuration->getThemePath() . $configuration->get('templatePath') . 'Page.html';
    }

    /**
     * Returns the Page object for the current URI
     *
     * @return Page
     */
    public function getPage()
    {
        if (!$this->page) {
            $this->page = $this->getPageForUri($this->uri);
        }

        return $this->page;
    }

    /**
     * Returns the page data
     *
     * @return mixed
     */
    public function getNotFoundPage()
    {
        return $this->getPageForUri('/NotFound/');
    }

    /**
     * Returns the response for the current page URI
     *
     * If the current page URI was not found, the URI "/NotFound/" will be checked
     *
     * @return Response|NULL
     */
    public function getResponse()
    {
        $statusCode = 200;
        $page = $this->getPage();
        if (!$page) {
            $statusCode = 404;
            $page = $this->getNotFoundPage();
        }

        return new Response(
            $page ? $page->getContent() : 'Not found',
            $statusCode
        );
    }

    /**
     * Returns the response for the page URI or NULL if no data was found
     *
     * @param string $uri
     * @return Response|NULL
     */
    public function buildResponseForUri($uri)
    {
        $page = $this->getPageForUri($uri);
        if (!$page) {
            return null;
        }

        return new Response($page->getContent());
    }

    /**
     * Returns the Page for the page URI or NULL if no data was found
     *
     * @param string $uri
     * @return Page
     */
    public function getPageForUri($uri)
    {
        $pageIdentifier = trim(urldecode($uri), '/');

        $pageRepository = new PageRepository();

        return $pageRepository->findByIdentifier($pageIdentifier);
    }

    /**
     * Returns the alias for the given URI, or the original URI if no alias is defined
     *
     * At the current stage this method doesn't do much. It simply returns "/Home/" if the current URI is "/"
     *
     * @param string $uri
     * @return string
     */
    public function getAliasForUri($uri)
    {
        $routingConfiguration = ConfigurationManager::getConfiguration()->get('routing');
        $aliasConfiguration = isset($routingConfiguration['alias']) ? $routingConfiguration['alias'] : [];

        return isset($aliasConfiguration[$uri]) ? $aliasConfiguration[$uri] : $uri;
    }

    /**
     * Parse the given Markdown code
     *
     * @param $markdown
     * @return mixed|string
     * @deprecated since 1.0.0 use \Cundd\Noshi\Helpers\MarkdownFactory::getMarkdownRenderer()->transform($markdown)
     */
    protected function parseMarkdown($markdown)
    {
        return MarkdownFactory::getMarkdownRenderer()->transform($markdown);
    }

    /**
     * Returns the shared dispatcher instance
     *
     * @return Dispatcher
     */
    static public function getSharedDispatcher()
    {
        if (!static::$sharedDispatcher) {
            static::$sharedDispatcher = new static();
        }

        return static::$sharedDispatcher;
    }

    /**
     * @param string $uri
     * @return string
     */
    protected function prepareUri($uri)
    {
        $basePath = ConfigurationManager::getConfiguration()->getRequestBasePath();
        $basePathLength = strlen($basePath);
        if ($basePath && substr($uri, 0, $basePathLength) === $basePath) {
            $uri = '/' . substr($uri, $basePathLength);
        }

        return $this->getAliasForUri($uri);
    }
}


<?php

namespace app\controllers;

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

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

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

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

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

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

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

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

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

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

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

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


<?php

namespace Cundd\Noshi\Helpers\Markdown;

trait AnchorTrait
{
    /**
     * Add IDs to headlines
     *
     * @param string $content
     * @return string
     */
    public function addHeadlineIds($content)
    {
        $regex = '/\<h([0-6]{1})\>(.+)\<\/h[0-6]{1}\>/';

        return preg_replace_callback(
            $regex,
            function ($matches) {
                $headlineLevel = $matches[1];
                $headlineText = $matches[2];

                return sprintf(
                    '<h%d id="%s">%s</h%d>',
                    (int)$headlineLevel,
                    $this->buildElementId($headlineText),
                    $headlineText,
                    (int)$headlineLevel
                );
            },
            (string)$content
        );
    }

    /**
     * @param string $headlineText
     * @return string
     */
    private function buildElementId($headlineText)
    {
        return (string)strtolower(preg_replace('/[^a-zA-Z0-9_\-]/', '-', $headlineText));
    }
}


<?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
 */

use yii\db\Schema;
use yii\db\Migration;

/**
 *
 * @author Andrey Borodulin
 *
 */
class m170610_152817_i18n extends Migration
{
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
        $this->createTable('{{%i18n_message}}', [
                'message_id' => Schema::TYPE_PK,
                'category' => Schema::TYPE_STRING . '(32) NOT NULL',
                'message' => Schema::TYPE_TEXT . ' NOT NULL',
                'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
                'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ]);

        $this->createTable('{{%i18n_translator}}', [
                'translator_id' => Schema::TYPE_PK,
                'class_name' => Schema::TYPE_STRING  . '(80) NOT NULL',
                'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
                'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ]);

        $this->createTable('{{%i18n_translation}}', [
                'message_id' => Schema::TYPE_INTEGER . ' NOT NULL',
                'language' => Schema::TYPE_STRING . '(16) NOT NULL',
                'translator_id' => Schema::TYPE_INTEGER,
                'translation' => Schema::TYPE_TEXT,
                'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 0',
                'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
                'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
                'error_message' => Schema::TYPE_TEXT,
                'PRIMARY KEY (message_id, language)',
        ]);
        $this->addforeignkey('fk_i18n_translation_message', '{{%i18n_translation}}', 'message_id', '{{%i18n_message}}', 'message_id', 'cascade', 'cascade');
        $this->addforeignkey('fk_i18n_translation_translator', '{{%i18n_translation}}', 'translator_id', '{{%i18n_translator}}', 'translator_id', 'cascade', 'cascade');
        $this->createIndex('ix_i18n_translation_status', '{{%i18n_translation}}', 'status');
        $this->createIndex('ix_i18n_translator_class_name', '{{%i18n_translator}}', 'class_name', true);

    }

    public function safeDown()
    {
        $this->dropTable('{{%i18n_translation}}');
        $this->dropTable('{{%i18n_translator}}');
        $this->dropTable('{{%i18n_message}}');
    }
}


<?php

namespace Ntavelis\AuthEmail\Commands\Actions;

class DeleteFiles extends Files {

    /**
     * Delete some of the files created by auth:make.
     */
    public function run()
    {
        //Deletes make:auth controllers
        $this->filesystem->delete($this->getControllers());

        //Deletes blades
        $this->filesystem->delete($this->getBlades());
    }
}


<?php

namespace Cundd\Noshi;

use Cundd\Noshi\Domain\Model\Page;
use Cundd\Noshi\Utilities\Profiler;

class Bootstrap
{

    /**
     * Dispatcher instance
     *
     * @var Dispatcher
     */
    protected $dispatcher;

    function __construct($basePath)
    {
        if (substr($basePath, -1) !== DIRECTORY_SEPARATOR) {
            $basePath .= DIRECTORY_SEPARATOR;
        }
        ConfigurationManager::initializeConfiguration($basePath);
        Profiler::start();
    }

    /**
     * Invokes the dispatcher
     */
    public function run()
    {
        Dispatcher::getSharedDispatcher()->dispatch($this->getUri(), $this->getMethod(), $this->getArguments());
    }

    /**
     * Invokes the CLI dispatcher
     *
     * @param array $arguments
     */
    public function runCli($arguments)
    {
        $commandController = new \Cundd\Noshi\Command\NoshiCommandController($arguments);
        $commandController->dispatch();
    }

    /**
     * @return array
     */
    private function getArguments()
    {
        $argumentsString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
        $arguments = [];
        if ($argumentsString) {
            parse_str($argumentsString, $tempArguments);
            foreach ($tempArguments as $argumentKey => $argumentValue) {
                $argumentKey = filter_var($argumentKey, FILTER_SANITIZE_STRING);
                $argumentValue = filter_var($argumentValue, FILTER_SANITIZE_STRING);
                $arguments[$argumentKey] = $argumentValue;
            }
        }

        return $arguments;
    }

    /**
     * @return string
     */
    private function getUri()
    {
        if (isset($_SERVER['REQUEST_URI'])) {
            $uriParts = explode('?', $_SERVER['REQUEST_URI'], 2);
            $uri = $uriParts[0];
        } elseif (isset($_GET['u'])) {
            $uri = $_GET['u'];
        } else {
            return '';
        }

        $uri = str_replace(' ', Page::URI_WHITESPACE_REPLACE, $uri);
        $uri = filter_var($uri, FILTER_SANITIZE_URL);

        return $uri;
    }

    /**
     * @return string
     */
    private function getMethod()
    {
        $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';

        return $method;
    }
}


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

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

    /**
     * Methods
     * @var array
     */
    private $methods;

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

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

        foreach ($this->methods as $method => $parameter) {
            call_user_func([$concrete, $method], $parameter);
        }

        return $concrete;
    }
}


<?php

namespace Ntavelis\AuthEmail;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Ntavelis\AuthEmail\Commands\AuthEmail;
use Ntavelis\AuthEmail\Repository\Activation;
use Ntavelis\AuthEmail\Repository\ActivationInterface;
use Illuminate\Contracts\Validation\Factory as Validator;
use Ntavelis\AuthEmail\Services\EmailAdapter;
use Ntavelis\AuthEmail\Services\Interfaces\Email;

class AuthEmailServiceProvider extends ServiceProvider {

    /**
     * Perform post-registration booting of services.
     *
     * @param Validator $validator
     * @return void
     */
    public function boot(Validator $validator)
    {
        /**
         * Better safe than sorry, check Laravel's documentation
         * https://laravel.com/docs/5.4/migrations#creating-indexes
         * for details
         */
        Schema::defaultStringLength(191);

        /**
         * Registering commands with artisan
         */
        if ($this->app->runningInConsole()) {
            $this->commands([
                AuthEmail::class,
            ]);
        }

        /**
         * Register custom Validator for alphanumeric with spaces
         */
        $validator->extend('alpha_spaces', function ($attribute, $value) {
            return preg_match('/^[\pL\s]+$/u', $value);
        });
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        /*
         * Bind interfaces to concrete implementations
         */
        $this->app->bind(
            ActivationInterface::class,
            Activation::class
        );
        $this->app->bind(
            Email::class,
            EmailAdapter::class
        );

        /**
         * Register singleton, ShouldQueue class
         * should be resolved out of the
         * container only one time.
         */
        $this->app->singleton('Ntavelis\AuthEmail\Commands\actions\ShouldQueue');
    }
}


<?php

namespace Cundd\Noshi\Helpers;

use Cundd\Noshi\Helpers\Markdown\MichelfRenderer;
use Cundd\Noshi\Helpers\Markdown\ParsedownRenderer;
use Cundd\Noshi\Helpers\Markdown\RenderInterface;

/**
 * Factory class for Markdown parsers
 *
 * @package Cundd\Noshi\Helpers
 */
class MarkdownFactory
{
    /**
     * @var RenderInterface
     */
    static protected $markdownRendererInstance;

    /**
     * Returns a Markdown Parser instance
     *
     * @return RenderInterface
     */
    static public function getMarkdownRenderer()
    {
        if (!self::$markdownRendererInstance) {
            if (class_exists('\\Michelf\\Markdown')) {
                self::$markdownRendererInstance = new MichelfRenderer();
            } else {
                self::$markdownRendererInstance = new ParsedownRenderer();
            }
        }

        return self::$markdownRendererInstance;
    }
}


<?php

namespace Ntavelis\AuthEmail\Commands\Actions;

use Illuminate\Filesystem\Filesystem;

abstract class Files extends FilesInteractions
{
    /**
     * Files constructor.
     * @param Filesystem $filesystem
     * @param ShouldQueue $queue
     */
    public function __construct(Filesystem $filesystem)
    {
        parent::__construct($filesystem);
    }

    /**
     * Get the paths to the make:auth generated controllers of interest.
     * @return array
     */
    protected function getControllers()
    {
        $path = base_path() . '/app/Http/Controllers/Auth/';
        $files = [
            'LoginController' => $path . 'LoginController.php',
            'RegisterController' => $path . 'RegisterController.php',
        ];

        return $files;
    }

    /**
     * Get the path to the blade files.
     *
     * @return array
     */
    protected function getBlades()
    {
        $path = base_path() . '/resources/views/';
        $loginStub = $this->laravelVersion >= 5.6 ? 'login.blade.b4' : 'login.blade';
        $files = [
            $loginStub => $path . 'auth/login.blade.php',
            'auth.email' => $path . 'emails/auth.blade.php',
        ];

        return $files;
    }

    /**
     * Get controllers directory path.
     * @return array
     */
    protected function getLanguages()
    {
        $path = base_path() . '/resources/lang/en/';
        $files = [
            'lang.authEmail' => $path . 'authEmail.php',
        ];

        return $files;
    }

    /**
     * Get the path to the migrations location.
     *
     * @return array
     */
    protected function getMigrations()
    {
        $formatted_date = date('Y_m_d_His');
        $path = base_path() . '/database/migrations/';
        $files = [
            'MigrationActivations' => $path . $formatted_date . '_create_user_activations_table.php',
            'MigrationUsers' => $path . $formatted_date . '_add_boolean_column_to_users_table.php'
        ];

        return $files;
    }

    /**
     * Get the path to the blade login file.
     *
     * @return array
     */
    protected function getEmails()
    {
        $path = base_path() . '/app/Mail/';
        $files = [
            'ActivationEmail' => $path . 'ActivateAccount.php',
        ];

        return $files;
    }

    /**
     * Every subclass must provide a run method.
     * @return mixed
     */
    public abstract function run();
}


<?php

namespace Cundd\Noshi\Domain\Repository;

use Cundd\Noshi\ConfigurationManager;
use Cundd\Noshi\Domain\Exception\InvalidPageIdentifierException;
use Cundd\Noshi\Domain\Model\Page;
use Cundd\Noshi\Utilities\ObjectUtility;

class PageRepository implements PageRepositoryInterface
{
    /**
     * Tree of nested pages
     *
     * @var array
     */
    protected $pageTree = [];

    /**
     * All pages
     *
     * @var array<Pages>
     */
    protected $allPages = [];

    const DEFAULT_SORTING = 9000;

    /**
     * Find the page with tie given identifier
     *
     * @param string $identifier
     * @return Page
     */
    public function findByIdentifier($identifier)
    {
        if (isset($this->allPages[$identifier])) {
            return $this->allPages[$identifier];
        }

        $rawPageData = null;
        $configuration = ConfigurationManager::getConfiguration();
        $dataPath = $configuration->get('basePath') . $configuration->get('dataPath');

        $pageName = $this->getPageNameForPageIdentifier($identifier);
        $pageDataPath = $dataPath . $pageName . '.' . $configuration->get('dataSuffix');
        $directoryDataPath = $dataPath . $pageName;
        $metaDataPath = $dataPath . $pageName . '.json';

        $lastSlashPosition = strrpos($pageName, '/');

        $hiddenPageDataPath = $dataPath . substr($pageName, 0, $lastSlashPosition)
            . '_' . substr($pageName, $lastSlashPosition)
            . '.' . $configuration->get('dataSuffix');

        $whiteSpacePageDataPath = $dataPath . str_replace(Page::URI_WHITESPACE_REPLACE, ' ', $pageName)
            . '.'
            . $configuration->get('dataSuffix');

        // Check if the node exists
        if (file_exists($pageDataPath)) {
            $rawPageData = file_get_contents($pageDataPath);
        } else {
            if (file_exists($whiteSpacePageDataPath)) {
                $pageDataPath = $whiteSpacePageDataPath;
                $rawPageData = file_get_contents($pageDataPath);
            } else {
                if (file_exists($hiddenPageDataPath)) {
                    $pageDataPath = $hiddenPageDataPath;
                    $rawPageData = file_get_contents($pageDataPath);
                } else {
                    if (!(file_exists($directoryDataPath) || file_exists($metaDataPath))) {
                        return null;
                    }
                }
            }
        }

        $page = new Page($identifier, $rawPageData, $this->buildMetaDataForPageIdentifier($identifier, $pageDataPath));
        $this->allPages[$identifier] = $page;

        return $page;
    }

    /**
     * Returns the page file name for the given page identifier
     *
     * @param string $identifier
     * @throws \Cundd\Noshi\Domain\Exception\InvalidPageIdentifierException if the given page identifier is invalid
     * @return string
     */
    public function getPageNameForPageIdentifier($identifier)
    {
        $pageName = urldecode($identifier);

        if (!$pageName || $pageName[0] === '.' || strpos($pageName, '/.') !== false) {
            throw new InvalidPageIdentifierException('Invalid page identifier');
        }

        if ($pageName[0] === '/') {
            $pageName = substr($pageName, 1);
        }
        if (substr($pageName, -1) === '/') {
            $pageName = substr($pageName, 0, -1);
        }

        return $pageName;
    }

    /**
     * Returns the meta data for the given page identifier
     *
     * The meta data is read from the global configuration and the page's config file (i.e. 'PageName.json'), whilst the
     * page config takes precedence.
     *
     * @param string $identifier
     * @param string $pageDataPath Determined path to the page contents
     * @return array
     */
    public function buildMetaDataForPageIdentifier($identifier, $pageDataPath = null)
    {
        $configuration = ConfigurationManager::getConfiguration();
        $dataPath = $configuration->get('basePath') . $configuration->get('dataPath');
        $pageName = $this->getPageNameForPageIdentifier($identifier);
        $metaDataPath = $dataPath . $pageName . '.json';

        // Read the global configuration
        $metaData = ObjectUtility::valueForKeyPathOfObject("pages.$identifier.meta", $configuration, []);

        // Check if the node exists
        if (file_exists($metaDataPath)) {
            $rawMetaData = file_get_contents($metaDataPath);
            $metaData = array_merge($metaData, (array)json_decode($rawMetaData, true));
        }

        if ($pageDataPath && file_exists($pageDataPath)) {
            $metaData['date'] = date('c', filemtime($pageDataPath));
        }

        return $metaData;
    }

    /**
     * Returns all pages
     *
     * @return array<Page>
     */
    public function findAll()
    {
        if (!$this->allPages) {
            $this->getPageTree();
        }

        return $this->allPages;
    }

    /**
     * Returns all available page names
     *
     * @return array<string>
     */
    public function getPageTree()
    {
        if (!$this->pageTree) {
            $configuration = ConfigurationManager::getConfiguration();
            $dataPath = $configuration->get('basePath') . $configuration->get('dataPath');
            $this->pageTree = $this->getPagesForPath($dataPath);
        }

        return $this->pageTree;
    }

    /**
     * Returns all available pages for the given path
     *
     * @param string $path
     * @param string $uriBase
     * @return array
     */
    public function getPagesForPath($path, $uriBase = '')
    {
        $pages = [];
        $pagesSortingMap = [];
        $pagesIdentifierMap = [];
        if (!file_exists($path)) {
            throw new \InvalidArgumentException("Page path '$path' does not exist");
        }
        if (!is_readable($path)) {
            throw new \InvalidArgumentException("Page path '$path' is not readable");
        }
        if ($handle = opendir($path)) {

            $dataSuffix = '.' . ConfigurationManager::getConfiguration()->get('dataSuffix');
            $dataSuffixLength = strlen($dataSuffix);

            while (false !== ($file = readdir($handle))) {
                // Skip the current file if the first character is a dot
                if ($file[0] === '.') {
                    continue;
                }

                // Skip hidden pages
                if ($file[0] === '_') {
                    continue;
                }

                $isFolder = strpos($file, '.') === false;
                $isPage = substr($file, -$dataSuffixLength) === $dataSuffix;
                $isConfig = substr($file, -5) === '.json';

                if (!($isFolder || $isPage || $isConfig)) {
                    continue;
                }

                $relativePageIdentifier = str_replace(
                    ' ',
                    Page::URI_WHITESPACE_REPLACE,
                    substr($file, 0, strrpos($file, '.'))
                );
                $pageIdentifier = ($uriBase ? $uriBase . '/' : '') . ($relativePageIdentifier ? $relativePageIdentifier : $file);

                /** @var Page $page */
                $page = $this->findByIdentifier($pageIdentifier);
                $page->setIsDirectory($isFolder);
                $sorting = $page->getSorting();
                $sortingDescriptor = sprintf('%05d-%s', $sorting, $pageIdentifier);

                /*
                 * Build the page data merged with previous definitions
                 * Page definition is more important than the Directory definition
                 */
                $pageData = array_merge(
                    (isset($pagesIdentifierMap[$pageIdentifier]) ? $pagesIdentifierMap[$pageIdentifier] : []),
                    [
                        'id'                 => $pageIdentifier,
                        'page'               => $page,
                        'sorting'            => $sorting,
                        'sorting_descriptor' => $sortingDescriptor,
                    ]
                );

                /*
                 * If the current page is a folder get the children
                 */
                if ($isFolder) {
                    $pageData['children'] = $this->getPagesForPath(
                        $path . $file . DIRECTORY_SEPARATOR,
                        $pageIdentifier
                    );
                }

                $pagesSortingMap[$sortingDescriptor] = $pageData;
                $pagesIdentifierMap[$pageIdentifier] = $pageData;
            }
            closedir($handle);
        }

        // Add the page to the list pages
        ksort($pagesSortingMap, SORT_NUMERIC);

        $tempPages = [];
        foreach ($pagesSortingMap as $pageWithSorting) {
            $tempPages[$pageWithSorting['id']] = $pageWithSorting['page'];
        }

        $this->allPages = array_merge($this->allPages, $tempPages);

        ksort($pages, SORT_NUMERIC);

        return $pagesSortingMap;
    }
}