<?php

namespace TheCodingMachine\Yaco\Definition;

/**
 * Represents a call to a method.
 */
class MethodCall implements ActionInterface
{
    /**
     * The name of the method.
     *
     * @var string
     */
    private $methodName;

    /**
     * A list of arguments passed to the constructor.
     *
     * @var array Array of scalars or ReferenceInterface, or array mixing scalars, arrays, and ReferenceInterface
     */
    private $arguments = array();

    /**
     * MethodCall constructor.
     *
     * @param string $methodName
     * @param array  $arguments
     */
    public function __construct($methodName, array $arguments = array())
    {
        $this->methodName = $methodName;
        $this->arguments = $arguments;
    }

    /**
     * Adds an argument to the list of arguments to be passed to the method.
     *
     * @param mixed $argument
     *
     * @return self
     */
    public function addArgument($argument)
    {
        $this->arguments[] = $argument;

        return $this;
    }

    /**
     * Generates PHP code for the line.
     *
     * @param string $variableName
     * @param string $containerVariable
     * @param array  $usedVariables
     *
     * @return InlineEntryInterface
     */
    public function toPhpCode($variableName, $containerVariable, array $usedVariables)
    {
        $dumpedArguments = ValueUtils::dumpArguments($this->arguments, $containerVariable, $usedVariables);
        $codeLine = sprintf('%s->%s(%s);', $variableName, $this->methodName, $dumpedArguments->getExpression());

        return new InlineEntry('', $dumpedArguments->getStatements().$codeLine, $dumpedArguments->getUsedVariables());
    }
}


<?php

namespace TheCodingMachine\Yaco;

use Interop\Container\Definition\DefinitionInterface;
use Interop\Container\Definition\DefinitionProviderInterface;
use TheCodingMachine\ServiceProvider\Registry;
use TheCodingMachine\Yaco\Definition\DumpableInterface;
use TheCodingMachine\Yaco\Definition\InlineEntryInterface;
use TheCodingMachine\Yaco\ServiceProvider\ServiceProviderLoader;

/**
 * A class that generates a PHP class (a container) from definitions.
 */
class Compiler
{
    /**
     * @var DefinitionInterface[]
     */
    private $definitions = [];

    /**
     * @var DumpableInterface[]
     */
    private $dumpableDefinitions = [];

    /**
     * The object in charge of converting container-interop definitions to our internal standard.
     *
     * @var DefinitionConverterInterface
     */
    private $converter;

    /**
     * A registry for registering container-interop's service-providers.
     *
     * @var Registry
     */
    private $registry;

    /**
     * @param Registry|null                     $registry  A registry for registering container-interop's service-providers
     * @param DefinitionConverterInterface|null $converter The object in charge of converting container-interop definitions to our internal standard.
     */
    public function __construct(Registry $registry = null, DefinitionConverterInterface $converter = null)
    {
        if ($registry === null) {
            $registry = new Registry();
        }
        $this->registry = $registry;
        if ($converter === null) {
            $converter = new DefinitionConverter();
        }
        $this->converter = $converter;
    }

    /**
     * Adds a definition to the list of definitions managed by this compiler.
     *
     * @param string              $identifier
     * @param DefinitionInterface $definition
     */
    public function addDefinition($identifier, DefinitionInterface $definition)
    {
        $this->definitions[$identifier] = $definition;
        unset($this->dumpableDefinitions[$identifier]);
    }

    /**
     * Registers a new definition provider.
     *
     * @param DefinitionProviderInterface $definitionProvider
     */
    public function register(DefinitionProviderInterface $definitionProvider)
    {
        foreach ($definitionProvider->getDefinitions() as $identifier => $definition) {
            $this->addDefinition($identifier, $definition);
        }
    }

    /**
     * Adds a dumpable definition to the list of definitions managed by this compiler.
     * Note: a "dumpable" definition is a definition represented in Yaco internal format.
     *
     * @param DumpableInterface $dumpableDefinition
     */
    public function addDumpableDefinition(DumpableInterface $dumpableDefinition)
    {
        $id = $dumpableDefinition->getIdentifier();
        if ($id === null) {
            throw new CompilerException('Anonymous instances cannot be directly added to a container.');
        }
        $this->dumpableDefinitions[$id] = $dumpableDefinition;
        unset($this->definitions[$id]);
    }

    /**
     * @param string $identifier
     *
     * @return bool
     */
    public function has($identifier)
    {
        return isset($this->dumpableDefinitions[$identifier]) || isset($this->definitions[$identifier]);
    }

    /**
     * Returns the dumpable definition matching the $identifier.
     *
     * @param string $identifier
     *
     * @return Definition\AliasDefinition|DumpableInterface|Definition\FactoryCallDefinition|Definition\ObjectDefinition|Definition\ParameterDefinition
     *
     * @throws CompilerException
     */
    public function getDumpableDefinition($identifier)
    {
        if (isset($this->dumpableDefinitions[$identifier])) {
            return $this->dumpableDefinitions[$identifier];
        } elseif (isset($this->definitions[$identifier])) {
            return $this->converter->convert($identifier, $this->definitions[$identifier]);
        } else {
            throw new CompilerException(sprintf('Unknown identifier in compiler: "%s"', $identifier));
        }
    }

    /**
     * @param string $className
     *
     * @return string
     */
    public function compile($className)
    {
        // FIXME: 2 successive calls to compile will yield invalid results as the state is modified by "compile".

        // Let's fill the definitions from service providers:
        $serviceProviderLoader = new ServiceProviderLoader($this, $this->converter);
        $serviceProviderLoader->loadFromRegistry($this->registry);

        $classCode = <<<EOF
<?php
%s

use Mouf\Picotainer\Picotainer;
use TheCodingMachine\ServiceProvider\Registry;

class %s extends Picotainer
{
    /**
     * The registry containing service providers.
     * @var Registry
     */
    protected \$registry;

    public function __construct(Registry \$registry = null, ContainerInterface \$delegateLookupContainer = null) {
        parent::__construct([
%s        ], \$delegateLookupContainer);
        \$this->objects = [
%s        ];
        if (\$registry === null) {
            \$registry = new Registry();
        }
        \$this->registry = \$registry;
    }
}

EOF;

        list($shortClassName, $namespaceLine) = $this->splitFQCN($className);

        $closuresCode = '';
        $parametersCode = '';

        $convertedDefinitions = [];
        // Let's merge dumpable definitions with standard definitions.
        foreach ($this->definitions as $identifier => $definition) {
            $convertedDefinitions[$identifier] = $this->converter->convert($identifier, $definition);
        }

        $allDefinitions = $convertedDefinitions + $this->dumpableDefinitions;

        foreach ($allDefinitions as $identifier => $definition) {
            $inlineEntry = $definition->toPhpCode('$container', ['$container']);

            if ($inlineEntry->isLazilyEvaluated()) {
                $closuresCode .= '            '.var_export($identifier, true).' => '.$this->getClosureCode($inlineEntry).",\n";
            } else {
                $parametersCode .= '            '.var_export($identifier, true).' => '.$this->getParametersCode($inlineEntry).",\n";
            }
        }

        return sprintf($classCode, $namespaceLine, $shortClassName, $closuresCode, $parametersCode);
    }

    private function splitFQCN($className)
    {
        $pos = strrpos($className, '\\');
        if ($pos !== false) {
            $shortClassName = substr($className, $pos + 1);
            $namespaceLine = 'namespace '.substr($className, 0, $pos).';';
        } else {
            $shortClassName = $className;
            $namespaceLine = '';
        }

        return [
            $shortClassName,
            $namespaceLine,
        ];
    }

    private function getParametersCode(InlineEntryInterface $inlineEntry)
    {
        if (!empty($inlineEntry->getStatements())) {
            throw new CompilerException('An entry that contains parameters (not lazily loaded) cannot return statements.');
        }

        return $inlineEntry->getExpression();
    }

    private function getClosureCode(InlineEntryInterface $inlineEntry)
    {
        $code = $inlineEntry->getStatements();
        $code .= 'return '.$inlineEntry->getExpression().";\n";

        return sprintf("function(\$container) {\n%s}", $code);
    }
}


<?php
/**
 * @author Jenner <hypxm@qq.com>
 * @blog http://www.huyanping.cn
 * @license https://opensource.org/licenses/MIT MIT
 * @datetime: 2015/11/13 16:37
 */

namespace React\Multi;

use Jenner\SimpleFork\ParallelPool;
use React\EventLoop\LoopInterface;

class Master
{
    /**
     * @var LoopInterface
     */
    protected $loop;

    /**
     * @var int process count
     */
    protected $count;

    /**
     * @var ParallelPool
     */
    protected $pool;

    /**
     * @param LoopInterface $loop
     * @param int $count
     */
    public function __construct(LoopInterface $loop, $count = 10)
    {
        $this->loop = $loop;
        $this->count = $count;
    }

    /**
     * start multi loop
     *
     * @param bool $block
     * @param int $interval
     */
    public function start($block = true, $interval = 100)
    {
        $loop = $this->loop;
        $this->pool = new ParallelPool(function () use ($loop) {
            $loop->run();
        }, $this->count);

        $this->pool->start();
        $this->pool->keep($block, $interval);
    }

    /**
     * keep the sub processes count
     *
     * @param bool $block
     */
    public function keep($block = false)
    {
        $this->pool->keep($block);
    }

    /**
     * start new sub processes and shutdown old processes
     */
    public function reload()
    {
        $this->pool->reload();
    }
}


<?php
/**
 * Created by PhpStorm.
 * User: Jenner
 * Date: 2016/7/1
 * Time: 9:48
 */

require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

class Handler implements \React\Multi\Socket\HandlerInterface {

    /**
     * handle request
     *
     * @param $conn
     * @param \React\EventLoop\LoopInterface $loop
     * @return mixed
     */
    public function handle($conn, \React\EventLoop\LoopInterface $loop)
    {
        sleep(1);
        var_dump(getmypid() . ":" . fread($conn, 1024));
        fwrite($conn, "HTTP/1.1 200 OK
Server: GitHub.com
Date: Fri, 01 Jul 2016 03:38:21 GMT
Content-Type: text/html; charset=utf-8\r\n\r\n");
    }
}

$config = new \React\Multi\Socket\ServerConfig();
$config->setDispatcher(new \React\Multi\Socket\Dispatch\CompetitionDispatch());

$server = new \React\Multi\Socket\Server($config, new Handler());
$server->start(1);


<?php

namespace TheCodingMachine\Yaco\Definition;

/**
 * A reference to a service.
 */
class Reference implements ReferenceInterface
{
    /**
     * @var string
     */
    private $target;

    /**
     * Constructs a Reference object targeting the $target entry.
     *
     * @param string $target
     */
    public function __construct($target)
    {
        $this->target = $target;
    }

    /**
     * Returns the identifier for the object in the container.
     *
     * @return string
     */
    public function getTarget(): string
    {
        return $this->target;
    }

    /**
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
     * the container entry.
     *
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
     * @param array  $usedVariables     An array of variables that are already used and that should not be used when generating this code.
     *
     * @return InlineEntryInterface
     */
    public function toPhpCode(string $containerVariable, array $usedVariables = array()): InlineEntryInterface
    {
        return new InlineEntry(sprintf('%s->get(%s)', $containerVariable, var_export($this->getTarget(), true)), null, $usedVariables);
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Tracker Factory Service Class
 *
 * Provides a service library for building many Tracker objects
 * with the same set of subscribers
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class TrackerFactory
{
    /**
     * @var array|EventSubscriberInterface[]
     */
    private $defaultSubscribers;

    /**
     * Constructor
     *
     * @param EventSubscriberInterface[] $defaultSubscribers
     */
    public function __construct(array $defaultSubscribers = [])
    {
        $this->defaultSubscribers = $defaultSubscribers;
    }

    /**
     * Build a new Tracker instance
     *
     * If $extraSubscribers is not empty, those subscribers will be added
     * to the Tracker in addition to the defaults.
     *
     * @param int                               $numItems          The total number of items (or -1 for unknown)
     * @param array|EventSubscriberInterface[]  $extraSubscribers  Optionally specify extra listeners for this Tracker instance
     * @return Tracker
     */
    public function buildTracker($numItems = Tracker::UNKNOWN, array $extraSubscribers = [])
    {
        $tracker = new Tracker($numItems);

        foreach (array_merge($this->defaultSubscribers, $extraSubscribers) as $listener) {
            $tracker->getDispatcher()->addSubscriber($listener);
        }

        return $tracker;
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Task Tracker
 *
 * Maintains the state of a long-running task and dispatches events
 * to subscribers for reporting on progress
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class Tracker
{
    const UNKNOWN = -1;

    const NOT_STARTED  = 0;
    const RUNNING      = 1;
    const FINISHED     = 2;
    const ABORTED      = 3;

    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;

    /**
     * @var int  The number of total item (-1 for infinite/unknown)
     */
    private $numTotalItems;

    /**
     * @var array  Array holding processed items by Tick type
     */
    private $numProcessedItems;

    /**
     * @var float  The start time (a float value)
     */
    private $startTime;

    /**
     * @var Tick  Holds the last tick
     */
    private $lastTick;

    /**
     * @var int  One of the constants defined above
     */
    private $status;

    /**
     * Build a task tracker using a list of subscribers
     *
     * This is an alternate constructor, to be used when constructing a
     * Tracker object using a collection of subscribers
     *
     * @param array|EventSubscriberInterface[] $subscribers
     * @param int                              $totalItems
     * @return static
     */
    public static function build(array $subscribers = [], $totalItems = self::UNKNOWN)
    {
        // New object
        $that = new static($totalItems);

        // Register subscribers
        foreach ($subscribers as $subscriber) {
            $that->addSubscriber($subscriber);
        }

        // Return it
        return $that;
    }

    /**
     * Constructor
     *
     * @param EventDispatcherInterface  $dispatcher
     * @param int                       $totalItems     Default is unknown (-1)
     */
    public function __construct($totalItems = self::UNKNOWN, EventDispatcherInterface $dispatcher = null)
    {
        $this->status            = self::NOT_STARTED;
        $this->dispatcher        = $dispatcher ?: new EventDispatcher();
        $this->numTotalItems     = $totalItems;
        $this->numProcessedItems = [];
    }

    /**
     * Iterate over items and track them
     *
     * @param \Traversable $items
     * @param callable     $itemCallback  Callback accepts arguments: (Tracker $tracker, $item)
     * @return Report      The final report
     */
    public function run(\Traversable $items, callable $itemCallback)
    {
        $this->start();
        foreach ($items as $item) {
            call_user_func($itemCallback, $this, $item);
        }
        return $this->finish();
    }

    /**
     * @return EventDispatcherInterface
     */
    public function getDispatcher()
    {
        return $this->dispatcher;
    }

    /**
     * Add a subscriber to this Tracker instance
     *
     * @param EventSubscriberInterface $subscriber
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->dispatcher->addSubscriber($subscriber);
    }

    /**
     * Get number of total items to be processed (-1 for unknown)
     *
     * @return int
     */
    public function getNumTotalItems()
    {
        return $this->numTotalItems;
    }

    /**
     * Return the number of items processed, including failed/succeeded
     *
     * @param int $tickType  Tick::SUCCESS, Tick::FAIL, Tick::SKIP, or null for all
     * @return int
     */
    public function getNumProcessedItems($tickType = null)
    {
        if (null !== $tickType) {
            return (array_key_exists($tickType, $this->numProcessedItems))
                ? $this->numProcessedItems[$tickType]
                : 0;
        }
        else {
            return array_sum($this->numProcessedItems);
        }
    }

    /**
     * Get the start time in microseconds (returns NULL if not yet started)
     *
     * @return float|null
     */
    public function getStartTime()
    {
        return $this->startTime;
    }

    /**
     * Get the last report
     *
     * Returns null if not started
     *
     * @return Report|null
     */
    public function getLastTick()
    {
        return $this->lastTick;
    }

    /**
     * Get the status
     *
     * @return int
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Is the tracker running?
     *
     * @return bool
     */
    public function isRunning()
    {
        return ($this->getStatus() == self::RUNNING);
    }

    /**
     * Start processing
     *
     * If this method is not called explicitely, it will automatically
     * be called upon first tick
     *
     * @param string $msg Optional message to include
     * @param array  $extraInfo
     */
    public function start($msg = null, array $extraInfo = [])
    {
        if ($this->status != self::NOT_STARTED) {
            throw new TrackerException("Cannot start tracker that was already started");
        }

        $this->status = self::RUNNING;
        $this->startTime = microtime(true);

        $tick = new Tick($this, Tick::SUCCESS, $msg, $extraInfo, 0);
        $this->dispatcher->dispatch(Events::TRACKER_START, $tick);
        $this->lastTick = $tick;
    }

    /**
     * Indicate progress to the tracker
     *
     * Builds a report and send it to the tick method in the output handlers
     *
     * @param int    $status SUCCESS (default), SKIP, or FAIL
     * @param string $msg    Message to include for this report
     * @param array  $extraInfo
     * @param int    $incrementBy
     * @return Report
     */
    public function tick($status = Tick::SUCCESS, $msg = null, array $extraInfo = [], $incrementBy = 1)
    {
        if ( ! $this->isRunning()) {
            $this->start();
        }

        $tick = new Tick($this, $status, $msg, $extraInfo, $incrementBy);
        // Increment the counter
        if (array_key_exists($tick->getStatus(), $this->numProcessedItems)) {
            $this->numProcessedItems[$tick->getStatus()] += $tick->getIncrementBy();
        }
        else {
            $this->numProcessedItems[$tick->getStatus()] = $tick->getIncrementBy();
        }

        $this->dispatcher->dispatch(Events::TRACKER_TICK, $tick);

        $this->lastTick = $tick;
        return $tick->getReport();
    }

    /**
     * Finish processing
     *
     * Builds a report and sends it to the finish method in the output handlers
     *
     * @param string $msg Optional message to include
     * @param array  $extraInfo
     * @return Report
     */
    public function finish($msg = null, array $extraInfo = [])
    {
        if ( ! $this->isRunning()) {
            throw new TrackerException("Cannot finish Tracker.  Not running.");
        }

        $tick = new Tick($this, Tick::SUCCESS, $msg, $extraInfo, 0);
        $this->status = self::FINISHED;

        $this->dispatcher->dispatch(Events::TRACKER_FINISH, $tick);

        $this->lastTick = $tick;
        return $tick->getReport();
    }

    /**
     * Abort processing
     *
     * Builds a reports and send it to the abort method in the output handlers
     *
     * @param string $msg Optional message to include
     * @param array  $extraInfo
     * @return Report
     */
    public function abort($msg = null, array $extraInfo = [])
    {
        if ( ! $this->isRunning()) {
            throw new TrackerException("Cannot abort Tracker.  Not running.");
        }

        $tick = new Tick($this, Tick::FAIL, $msg, $extraInfo, 0);
        $this->status = self::ABORTED;

        $this->dispatcher->dispatch(Events::TRACKER_ABORT, $tick);

        $this->lastTick = $tick;
        return $tick->getReport();
    }
}


<?php

namespace Codingo\Dropzoner\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Codingo\Dropzoner\Repositories\UploadRepository;

class DropzonerController extends Controller
{
    /**
     * Upload image methods
     *
     * @var UploadRepository
     */
    protected $uploadRepository;

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

    /**
     * Receive post requests from Dropzone
     *
     * @return mixed
     */
    public function postUpload(Request $request)
    {
        $input = $request->all();
        $response = $this->uploadRepository->upload($input);
        return $response;
    }

    public function postDelete(Request $request)
    {
        $response = $this->uploadRepository->delete($request->input('id'));
        return $response;
    }

}


<?php

namespace TheCodingMachine\Yaco\ServiceProvider;

use TheCodingMachine\Yaco\Definition\DumpableInterface;
use TheCodingMachine\Yaco\Definition\InlineEntry;
use TheCodingMachine\Yaco\Definition\InlineEntryInterface;

/**
 * Fetches a service from the service-providers registry.
 */
class CreateServiceFromRegistryDefinition implements DumpableInterface
{
    /**
     * The identifier of the instance in the container.
     *
     * @var string|null
     */
    private $identifier;

    /**
     * The key of the service provider in the registry.
     *
     * @var int
     */
    private $serviceProviderKey;

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

    /**
     * @param string|null                    $identifier
     * @param string                         $serviceName
     * @param int                            $serviceProviderKey
     */
    public function __construct($identifier, string $serviceName, int $serviceProviderKey)
    {
        $this->identifier = $identifier;
        $this->serviceName = $serviceName;
        $this->serviceProviderKey = $serviceProviderKey;
    }

    /**
     * Returns the identifier for this object in the container.
     * If null, classes consuming this definition should assume the definition must be inlined.
     *
     * @return string|null
     */
    public function getIdentifier(): ?string
    {
        return $this->identifier;
    }

    /**
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
     * the container entry.
     *
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
     * @param array  $usedVariables     An array of variables that are already used and that should not be used when generating this code.
     *
     * @return InlineEntryInterface
     */
    public function toPhpCode(string $containerVariable, array $usedVariables = array()): InlineEntryInterface
    {
        $code = sprintf('$this->registry->createService(%s, %s, $this->delegateLookupContainer)', var_export($this->serviceProviderKey, true),
            var_export($this->serviceName, true));

        return new InlineEntry($code, null, $usedVariables);
    }

    public function cloneWithoutIdentifier(): self
    {
        return new self(null, $this->serviceName, $this->serviceProviderKey);
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker\Subscriber;

use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TaskTracker\Events;
use TaskTracker\Tick;

/**
 * PSR3-Compatible Logger Task Tracker Subscriber
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class Psr3Logger implements EventSubscriberInterface
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    // ---------------------------------------------------------------

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

    // ---------------------------------------------------------------

    /**
     * Geth the logger
     *
     * @return LoggerInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    // ---------------------------------------------------------------

    /**
     * Start callback
     *
     * @param Tick $tick
     */
    public function start(Tick $tick)
    {
        $this->logger->info($tick->getMessage() ?: 'Started', $tick->getReport()->toArray());
    }

    // ---------------------------------------------------------------

    /**
     * Tick callback
     *
     * @param Tick $tick
     */
    public function tick(Tick $tick)
    {
        $callback = ($tick->getStatus() == Tick::FAIL)
            ? [$this->logger, 'warning']
            : [$this->logger, 'info'];

        $msg = sprintf(
            "[%s/%s] %s",
            $tick->getReport()->getNumItemsProcessed(),
            $tick->getReport()->getTotalItemCount(),
            $tick->getMessage() ?: 'Tick'
        );

        call_user_func($callback, $msg, $tick->getReport()->toArray());
    }

    // ---------------------------------------------------------------

    /**
     * Finish callback
     *
     * @param Tick $tick
     */
    public function finish(Tick $tick)
    {
        $this->logger->info($tick->getMessage() ?: 'Finished', $tick->getReport()->toArray());
    }

    // ---------------------------------------------------------------

    /**
     * Abort callback
     *
     * @param Tick $tick
     */
    public function abort(Tick $tick)
    {
        $this->logger->warning($tick->getMessage() ?: 'Aborted', $tick->getReport()->toArray());
    }

    // ---------------------------------------------------------------

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            Events::TRACKER_START  => 'start',
            Events::TRACKER_TICK   => 'tick',
            Events::TRACKER_FINISH => 'finish',
            Events::TRACKER_ABORT  => 'abort'
        ];
    }
}


<?php

namespace TheCodingMachine\Yaco\Definition;

/**
 * This class represents an instance declared using a call to a method (a factory) from an existing service.
 * The method can be passed any number of arguments.
 */
class FactoryCallDefinition implements DumpableInterface
{
    /**
     * The identifier of the instance in the container.
     *
     * @var string|null
     */
    private $identifier;

    /**
     * The fully qualified class name of this instance, or a fully qualified class name.
     *
     * @var ReferenceInterface|string
     */
    private $factory;

    /**
     * The name of the method to be called.
     *
     * @var string
     */
    private $methodName;

    /**
     * A list of arguments passed to the constructor.
     *
     * @var array Array of scalars or ReferenceInterface, or array mixing scalars, arrays, and ReferenceInterface
     */
    private $methodArguments = array();

    /**
     * Constructs an factory definition.
     *
     * @param string|null        $identifier      The identifier of the instance in the container. Can be null if the instance is anonymous (declared inline of other instances)
     * @param ReferenceInterface|string $factory         A pointer to the service that the factory method will be called upon, or a fully qualified class name
     * @param string             $methodName      The name of the factory method
     * @param array              $methodArguments The parameters of the factory method
     */
    public function __construct(?string $identifier, $factory, $methodName, array $methodArguments = [])
    {
        $this->identifier = $identifier;
        $this->factory = $factory;
        $this->methodName = $methodName;
        $this->methodArguments = $methodArguments;
    }

    /**
     * Returns the identifier of the instance.
     *
     * @return string
     */
    public function getIdentifier(): ?string
    {
        return $this->identifier;
    }

    /**
     * Returns a pointer to the service that the factory method will be called upon, or a fully qualified class name.
     *
     * @return ReferenceInterface|string
     */
    public function getFactory()
    {
        return $this->factory;
    }

    /**
     * Returns the name of the factory method.
     *
     * @return string
     */
    public function getMethodName()
    {
        return $this->methodName;
    }

    /**
     * Returns the parameters of the factory method.
     *
     * @return array
     */
    public function getMethodArguments()
    {
        return $this->methodArguments;
    }

    /**
     * Adds an argument to the method.
     *
     * @param mixed $argument
     */
    public function addMethodArgument($argument)
    {
        $this->methodArguments[] = $argument;
    }

    /**
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
     * the container entry.
     *
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
     * @param array  $usedVariables     An array of variables that are already used and that should not be used when generating this code.
     *
     * @return InlineEntryInterface
     */
    public function toPhpCode(string $containerVariable, array $usedVariables = array()): InlineEntryInterface
    {
        $dumpedArguments = ValueUtils::dumpArguments($this->methodArguments, $containerVariable, $usedVariables);
        $prependedCode = $dumpedArguments->getStatements();
        if ($this->factory instanceof ReferenceInterface) {
            $code = sprintf("%s->get(%s)->%s(%s)\n", $containerVariable, var_export($this->factory->getTarget(), true), $this->methodName, $dumpedArguments->getExpression());
        } else {
            $code = sprintf("%s::%s(%s)\n", '\\'.ltrim($this->factory, '\\'), $this->methodName, $dumpedArguments->getExpression());
        }

        return new InlineEntry($code, $prependedCode, $usedVariables);
    }

    public function cloneWithoutIdentifier(): self
    {
        return new self(null, $this->factory, $this->methodName, $this->methodArguments);
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker\Subscriber;

use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TaskTracker\Events;
use TaskTracker\Helper\BytesToHumanTrait;
use TaskTracker\Tick;

/**
 * Symfony Console Progress Bar Task Tracker Subscriber
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class SymfonyConsoleProgress implements EventSubscriberInterface
{
    // Use traits for prettier output
    use BytesToHumanTrait;

    // ---------------------------------------------------------------

    /**
     * @var OutputInterface;
     */
    private $output;

    /**
     * @var ProgressBar|null  Set at runtime
     */
    private $progressBar;

    // --------------------------------------------------------------

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            Events::TRACKER_START  => 'start',
            Events::TRACKER_TICK   => 'tick',
            Events::TRACKER_FINISH => 'finish',
            Events::TRACKER_ABORT  => 'abort'
        ];
    }

    // --------------------------------------------------------------

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

    // ---------------------------------------------------------------

    /**
     * Start callback
     *
     * @param Tick $tick
     */
    public function start(Tick $tick)
    {
        if ($tick->getMessage()) {
            $this->output->writeln($tick->getMessage());
        }

        $this->progressBar = new ProgressBar(
            $this->output,
            $tick->getReport()->getTotalItemCount() > -1
                ? $tick->getReport()->getTotalItemCount()
                : 0
        );

        $this->progressBar->start();
    }

    // ---------------------------------------------------------------

    /**
     * Tick callback
     *
     * @param Tick $tick
     */
    public function tick(Tick $tick)
    {
        $rpt = $tick->getReport();

        if ( ! $this->progressBar) {
            $this->start($tick);
        }

        $msgSegs = [$tick->getMessage()];

        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
            $msgSegs[] = sprintf('Processed: <fg=green>%s</fg=green>', number_format($rpt->getNumItemsSuccess(), 0));
            $msgSegs[] = sprintf('Skipped: <fg=yellow>%s</fg=yellow>', number_format($rpt->getNumItemsFail(), 0));
            $msgSegs[] = sprintf('Failed: <fg=red>%s</fg=red>'       , number_format($rpt->getNumItemsSkip(), 0));
        }

        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {

            $msgSegs[] = sprintf("Avg: %s", number_format($rpt->getAvgItemTime(), 2));

            $msgSegs[] = sprintf(
                'Memory: %s/%s',
                $this->bytesToHuman($rpt->getMemUsage(),   2),
                $this->bytesToHuman($rpt->getMemPeakUsage(), 2)
            );
        }

        $this->progressBar->setMessage(implode(' | ', $msgSegs));
        $this->progressBar->setProgress($rpt->getNumItemsProcessed());
        //$this->progressBar->advance($rpt->getTick()->getIncrementBy());
    }

    /**
     * Finish callback
     *
     * @param Tick $tick
     */
    public function finish(Tick $tick)
    {
        $this->progressBar->finish();

        if ($tick->getMessage()) {

            $this->output->writeln(PHP_EOL . $tick->getMessage());
        }

    }

    /**
     * Abort callback
     *
     * @param Tick $tick
     */
    public function abort(Tick $tick)
    {
        $this->progressBar->clear();
        $this->output->writeln($tick->getMessage() ?: 'Aborted');
    }
}


<?php

namespace TheCodingMachine\Yaco\Definition;

use SuperClosure\Analyzer\TokenAnalyzer;

/**
 * This class represents a closure.
 * Important! The code of the closure will be COPIED, not referenced.
 */
class ClosureDefinition implements DumpableInterface
{
    /**
     * The identifier of the instance in the container.
     *
     * @var string|null
     */
    private $identifier;

    /**
     * The closure.
     *
     * @var \Closure
     */
    private $closure;

    /**
     * Constructs an instance definition.
     *
     * @param string|null $identifier The identifier of the entry in the container. Can be null if the entry is anonymous (declared inline in other instances)
     * @param \Closure    $closure    The closure. It should not contain context (i.e. no "use" keyword in the closure definition). It should accept one compulsory parameter: the container.
     */
    public function __construct(?string $identifier, \Closure $closure)
    {
        $this->identifier = $identifier;
        $this->closure = $closure;
    }

    /**
     * Returns the identifier of the instance.
     *
     * @return string
     */
    public function getIdentifier(): ?string
    {
        return $this->identifier;
    }

    /**
     * Returns the closure of the parameter.
     *
     * @return mixed
     */
    public function getClosure()
    {
        return $this->closure;
    }

    /**
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
     * the container entry.
     *
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
     * @param array  $usedVariables     An array of variables that are already used and that should not be used when generating this code.
     *
     * @return InlineEntryInterface
     *
     * @throws DefinitionException
     */
    public function toPhpCode(string $containerVariable, array $usedVariables = array()): InlineEntryInterface
    {
        // TODO: not optimal compared to previous interface!!!
        $analyzer = new TokenAnalyzer();
        $analysis = $analyzer->analyze($this->closure);

        if ($analysis['hasThis']) {
            throw new DefinitionException('Your closure cannot call the $this keyword.');
        }
        if (!empty($analysis['context'])) {
            throw new DefinitionException('Your closure cannot have a context (i.e. cannot have a "use" keyword).');
        }
        $code = $analysis['code'];
        $variableName = VariableUtils::getNextAvailableVariableName("\$closure", $usedVariables);
        $usedVariables[] = $variableName;
        $assignClosure = sprintf('%s = %s;', $variableName, $code);

        return new InlineEntry($variableName.'('.$containerVariable.')', $assignClosure, $usedVariables);
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker\Helper;

/**
 * Time Formatter Trait
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
trait TimeFormatterTrait
{
    /**
     * Format Seconds into readable walltime (HH:ii:ss)
     *
     * @param float $elapsedTime
     * @return string
     */
    public function formatSeconds($elapsedTime)
    {
        $seconds = floor($elapsedTime);
        $output = array();

        //Hours (only if $seconds > 3600)
        if ($seconds > 3600) {
            $hours    = floor($seconds / 3600);
            $seconds  = $seconds - (3600 * $hours);
            $output[] = number_format($hours, 0);
        }

        //Minutes
        if ($seconds >= 60) {
            $minutes  = floor($seconds / 60);
            $seconds  = $seconds - ($minutes * 60);
            $output[] = str_pad((string) $minutes, 2, '0', STR_PAD_LEFT);
        }
        else {
            $output[] = '00';
        }

        //Seconds
        $output[] =($seconds > 0)
            ? str_pad((string) $seconds, 2, '0', STR_PAD_LEFT)
            : '00';

        return implode(':', $output);
    }
}


<?php

namespace TheCodingMachine\Yaco;

use Interop\Container\Definition\DefinitionInterface;
use Interop\Container\Definition\FactoryCallDefinitionInterface;
use Interop\Container\Definition\ObjectDefinitionInterface;
use Interop\Container\Definition\ParameterDefinitionInterface;
use Interop\Container\Definition\ReferenceDefinitionInterface;
use TheCodingMachine\Yaco\Definition\AliasDefinition;
use TheCodingMachine\Yaco\Definition\FactoryCallDefinition;
use TheCodingMachine\Yaco\Definition\ObjectDefinition;
use TheCodingMachine\Yaco\Definition\ParameterDefinition;
use TheCodingMachine\Yaco\Definition\Reference;

/**
 * This class is in charge of converting definitions from the Interop\Container\DefinitionInterface to the
 * internal DumpableInterface format.
 */
class DefinitionConverter implements DefinitionConverterInterface
{
    /**
     * @param string|null               $identifier
     * @param DefinitionInterface|mixed $definition
     *
     * @return AliasDefinition|FactoryCallDefinition|ObjectDefinition|ParameterDefinition|Reference
     */
    public function convert(?string $identifier, $definition)
    {
        if ($definition instanceof ObjectDefinitionInterface) {
            $yacoObjectDefinition = new ObjectDefinition($identifier,
                $definition->getClassName(),
                $this->convertArguments($definition->getConstructorArguments()));

            foreach ($definition->getPropertyAssignments() as $assignment) {
                $yacoObjectDefinition->setProperty($assignment->getPropertyName(), $this->convertValue($assignment->getValue()));
            }

            foreach ($definition->getMethodCalls() as $methodCall) {
                $yacoObjectDefinition->addMethodCall($methodCall->getMethodName(), $this->convertArguments($methodCall->getArguments()));
            }

            return $yacoObjectDefinition;
        } elseif ($definition instanceof FactoryCallDefinitionInterface) {
            return new FactoryCallDefinition($identifier,
                $this->convertValue($definition->getFactory()),
                $definition->getMethodName(),
                $this->convertArguments($definition->getArguments()));
        } elseif ($definition instanceof ParameterDefinitionInterface) {
            return new ParameterDefinition($identifier, $this->convertValue($definition->getValue()));
        } elseif ($definition instanceof ReferenceDefinitionInterface) {
            if ($identifier !== null) {
                return new AliasDefinition($identifier, $definition->getTarget());
            } else {
                return new Reference($definition->getTarget());
            }
        } elseif (is_scalar($definition) || is_array($definition)) {
            return new ParameterDefinition($identifier, $this->convertValue($definition));
        } else {
            throw new \RuntimeException(sprintf('Cannot convert object of type "%s"', get_class($definition)));
        }
    }

    /**
     * @param array $arguments
     *
     * @return array
     */
    private function convertArguments(array $arguments): array
    {
        $yacoArguments = [];
        foreach ($arguments as $argument) {
            $yacoArguments[] = $this->convertValue($argument);
        }

        return $yacoArguments;
    }

    private function convertValue($value)
    {
        if (is_array($value)) {
            return array_map([$this, 'convertValue'], $value);
        } elseif ($value instanceof DefinitionInterface) {
            return $this->convert(null, $value);
        } elseif (is_object($value) || is_resource($value)) {
            throw new \RuntimeException('Unable to convert a definition. Parameters cannot be an object or a resource.');
        } else {
            return $value;
        }
    }
}


<?php

namespace TheCodingMachine\Yaco\Definition;

/**
 * This class represents a constant parameter (a "define" or a const in a class).
 */
class ConstParameterDefinition implements DumpableInterface
{
    /**
     * The identifier of the instance in the container.
     *
     * @var string|null
     */
    private $identifier;

    /**
     * The name of the constant. If it is a class constant, please pass the FQDN. For instance: "My\Class::CONSTANT".
     *
     * @var string
     */
    private $const;

    /**
     * Constructs an instance definition.
     *
     * @param string|null $identifier The identifier of the entry in the container. Can be null if the entry is anonymous (declared inline in other instances)
     * @param string      $const      The name of the constant. If it is a class constant, please pass the FQDN. For instance: "My\Class::CONSTANT"
     */
    public function __construct(?string $identifier, string $const)
    {
        $this->identifier = $identifier;
        $this->const = $const;
    }

    /**
     * Returns the identifier of the instance.
     *
     * @return string
     */
    public function getIdentifier(): ?string
    {
        return $this->identifier;
    }

    /**
     * The name of the constant. If it is a class constant, please pass the FQDN. For instance: "My\Class::CONSTANT".
     *
     * @return mixed
     */
    public function getConst()
    {
        return $this->const;
    }

    /**
     * Returns an InlineEntryInterface object representing the PHP code necessary to generate
     * the container entry.
     *
     * @param string $containerVariable The name of the variable that allows access to the container instance. For instance: "$container", or "$this->container"
     * @param array  $usedVariables     An array of variables that are already used and that should not be used when generating this code.
     *
     * @return InlineEntryInterface
     */
    public function toPhpCode(string $containerVariable, array $usedVariables = array()): InlineEntryInterface
    {
        return new InlineEntry($this->const, null, $usedVariables, false);
    }
}


<?php

/**
 * Tack Tracker - A library for tracking long-running task progress
 *
 * @license http://opensource.org/licenses/MIT
 * @link https://github.com/caseyamcl/tasktracker
 * @version 2.0
 * @package caseyamcl/tasktracker
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * ------------------------------------------------------------------
 */

namespace TaskTracker\Subscriber;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use TaskTracker\Events;
use TaskTracker\Helper\BytesToHumanTrait;
use TaskTracker\Helper\TimeFormatterTrait;
use TaskTracker\Tick;
use TaskTracker\Tracker;

/**
 * Symfony Console Log Task Tracker Subscriber
 *
 * @author Casey McLaughlin <caseyamcl@gmail.com>
 */
class SymfonyConsoleLog implements EventSubscriberInterface
{
    // Use traits to aid in output
    use BytesToHumanTrait;
    use TimeFormatterTrait;

    // --------------------------------------------------------------

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var array
     */
    private $linePrefixMap = [
        Tick::SKIP    => 'SKIP»',
        TICK::SUCCESS => 'SUCC»',
        TICK::FAIL    => 'FAIL»'
    ];

    // --------------------------------------------------------------

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

    // --------------------------------------------------------------

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return [
            Events::TRACKER_START  => 'writeStartLine',
            Events::TRACKER_TICK   => 'writeLogLine',
            Events::TRACKER_FINISH => 'writeFinishLine',
            Events::TRACKER_ABORT  => 'writeAbortLine'
        ];
    }

    // ---------------------------------------------------------------

    /**
     * Set line prefix map
     *
     * @param array $prefixMap  [status => 'prefix']
     */
    public function setLinePrefixMap(array $prefixMap)
    {
        foreach ($prefixMap as $status => $prefix) {
            $this->setLinePrefix($status, $prefix);
        }
    }

    // ---------------------------------------------------------------

    /**
     * Set prefix for a given status
     *
     * @param int    $status  Tick::SUCCESS, Tick::FAIL, or Tick::SUCCESS
     * @param string $prefix
     */
    public function setLinePrefix($status, $prefix)
    {
        $this->linePrefixMap[$status] = $prefix;
    }

    // ---------------------------------------------------------------

    /**
     * Write Log Line
     *
     * @param Tick $tick
     */
    public function writeLogLine(Tick $tick)
    {
        // Line segments
        $lineSegs = array();

        // 1st Segment is a star
        switch ($tick->getStatus()) {
            case Tick::SUCCESS:
                $lineSegs[] = sprintf("<fg=green>%s</fg=green>", $this->linePrefixMap[Tick::SUCCESS]);
                break;
            case Tick::FAIL:
                $lineSegs[] = sprintf("<fg=red>%s</fg=red>", $this->linePrefixMap[Tick::FAIL]);
                break;
            case Tick::SKIP:
            default:
                $lineSegs[] = $this->linePrefixMap[Tick::SKIP];
        }

        // Item Progress
        $lineSegs[] = sprintf(
            "[%s%s]",
            $tick->getReport()->getNumItemsProcessed(),
            $tick->getReport()->getTotalItemCount() != Tracker::UNKNOWN ? "/" . $tick->getReport()->getTotalItemCount() : ''
        );

        // If verbose, add walltime and item counts
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
            $lineSegs[] = $this->formatSeconds($tick->getReport()->getTimeElapsed());

            $lineSegs[] = sprintf(
                '(<fg=green>%s</fg=green>/%s/<fg=red>%s</fg=red>)',
                $tick->getReport()->getNumItemsSuccess(),
                $tick->getReport()->getNumItemsSkip(),
                $tick->getReport()->getNumItemsFail()
            );
        }

        // If very verbose, add memory usage
        if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE) {
            $lineSegs[] = sprintf("{%s/%s}",
                $this->bytesToHuman($tick->getReport()->getMemUsage()),
                $this->bytesToHuman($tick->getReport()->getMemPeakUsage())
            );
        }

        // Add message
        $lineSegs[] = $tick->getMessage() ?: sprintf(
            "Processing item %s",
            number_format($tick->getReport()->getNumItemsProcessed(), 0)
        );

        // Output it!
        $this->output->writeln(implode(' ', $lineSegs));
    }

    // ---------------------------------------------------------------

    /**
     * @param Tick $tick
     */
    public function writeStartLine(Tick $tick)
    {
        $this->output->writeln($tick->getMessage() ?: "Starting . . .");
    }

    /**
     * @param Tick $tick
     */
    public function writeFinishLine(Tick $tick)
    {
        $this->output->writeln($tick->getMessage() ?: ". . . Finished");
    }

    /**
     * @param Tick $tick
     */
    public function writeAbortLine(Tick $tick)
    {
        $this->output->writeln('<error>' . ($tick->getMessage() ?: 'Aborted!') . '</error>');
    }
}


<?php

namespace Codingo\Dropzoner\Repositories;

use Codingo\Dropzoner\Events\ImageWasDeleted;
use Codingo\Dropzoner\Events\ImageWasUploaded;
use Intervention\Image\ImageManager;

class UploadRepository
{
    /**
     * Upload Single Image
     *
     * @param $input
     * @return mixed
     */
    public function upload($input)
    {
        $validator = \Validator::make($input, config('dropzoner.validator'), config('dropzoner.validator-messages'));

        if ($validator->fails()) {

            return response()->json([
                'error' => true,
                'message' => $validator->messages()->first(),
                'code' => 400
            ], 400);
        }

        $photo = $input['file'];

        $original_name = $photo->getClientOriginalName();
        $extension = $photo->getClientOriginalExtension();
        $original_name_without_extension = substr($original_name, 0, strlen($original_name) - strlen($extension) - 1);

        $filename = $this->sanitize($original_name_without_extension);
        $allowed_filename = $this->createUniqueFilename( $filename );

        $filename_with_extension = $allowed_filename .'.' . $extension;

        $manager = new ImageManager();
        $image = $manager->make( $photo )->save(config('dropzoner.upload-path') . $filename_with_extension );

        if( !$image ) {

            return response()->json([
                'error' => true,
                'message' => 'Server error while uploading',
                'code' => 500
            ], 500);

        }

        //Fire ImageWasUploaded Event
        event(new ImageWasUploaded($original_name, $filename_with_extension));

        return response()->json([
            'error' => false,
            'code'  => 200,
            'filename' => $filename_with_extension
        ], 200);
    }

    /**
     * Delete Single Image
     *
     * @param $server_filename
     * @return mixed
     */
    public function delete($server_filename)
    {
        $upload_path = config('dropzoner.upload-path');

        $full_path = $upload_path . $server_filename;

        if (\File::exists($full_path)) {
            \File::delete($full_path);
        }

        event(new ImageWasDeleted($server_filename));

        return response()->json([
            'error' => false,
            'code'  => 200
        ], 200);
    }

    /**
     * Check upload directory and see it there a file with same filename
     * If filename is same, add random 5 char string to the end
     *
     * @param $filename
     * @return string
     */
    private function createUniqueFilename( $filename )
    {
        $full_size_dir = config('dropzoner.upload-path');
        $full_image_path = $full_size_dir . $filename . '.jpg';

        if (\File::exists($full_image_path)) {
            // Generate token for image
            $image_token = substr(sha1(mt_rand()), 0, 5);
            return $filename . '-' . $image_token;
        }

        return $filename;
    }

    /**
     * Create safe file names for server side
     *
     * @param $string
     * @param bool $force_lowercase
     * @return mixed|string
     */
    private function sanitize($string, $force_lowercase = true)
    {
        $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
            "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
            "â€”", "â€“", ",", "<", ".", ">", "/", "?");
        $clean = trim(str_replace($strip, "", strip_tags($string)));
        $clean = preg_replace('/\s+/', "-", $clean);

        return ($force_lowercase) ?
            (function_exists('mb_strtolower')) ?
                mb_strtolower($clean, 'UTF-8') :
                strtolower($clean) :
            $clean;
    }
}


<?php

namespace TheCodingMachine\Yaco\Definition;

class VariableUtils
{
    /**
     * Returns the next available variable name to use.
     *
     * @param string $variable      The variable name we wish to use
     * @param array  $usedVariables The list of variable names already used.
     *
     * @return string
     */
    public static function getNextAvailableVariableName(string $variable, array $usedVariables): string
    {
        $variable = self::toVariableName($variable);
        while (true) {
            // check that the name is not reserved
            if (!in_array($variable, $usedVariables, true)) {
                break;
            }

            $numbers = '';
            while (true) {
                $lastCharacter = substr($variable, strlen($variable) - 1);
                if ($lastCharacter >= '0' && $lastCharacter <= '9') {
                    $numbers = $lastCharacter.$numbers;
                    $variable = substr($variable, 0, strlen($variable) - 1);
                } else {
                    break;
                }
            }

            if ($numbers === '') {
                $numbers = 0;
            } else {
                $numbers = (int) $numbers;
            }
            ++$numbers;

            $variable = $variable.$numbers;
        }

        return $variable;
    }

    /**
     * Transform $name into a valid variable name by removing not authorized characters or adding new ones.
     *
     * - foo => $foo
     * - $foo => $foo
     * - fo$o => $foo
     *
     * @param string $name
     *
     * @return string
     */
    private static function toVariableName(string $name): string
    {
        $variableName = preg_replace('/[^A-Za-z0-9]/', '', $name);
        if ($variableName{0} >= '0' && $variableName{0} <= '9') {
            $variableName = 'a'.$variableName;
        }

        return '$'.$variableName;
    }
}


<?php

namespace Nur\Kernel;

use RuntimeException;

abstract class Facade
{
    /**
     * Application List in Service Provider
     *
     * @var array
     */
    protected static $app;

    /**
     * Resolved instances of objects in Facade
     *
     * @var array
     */
    protected static $resolvedInstance;

    /**
     * Created instances of objects in Facade
     *
     * @var array
     */
    protected static $createdInstances = [];

    /**
     * Set Facade Application (Container)
     *
     * @param string $app
     * @return void
     */
    public static function setApplication($app)
    {
        static::$app = $app;
    }

    /**
     * Get the application instance behind the facade.
     *
     * @return \Nur\Kernel\Application
     */
    public static function getFacadeApplication()
    {
        return static::$app;
    }

    /**
     * Clear Resolved Instance
     *
     * @param string $facadeName
     * @return void
     */
    public static function clearResolvedInstance($facadeName)
    {
        unset(static::$resolvedInstance[$facadeName]);
    }

    /**
     * Clear All Resolved Instances
     *
     * @return void
     */
    public static function clearResolvedInstances()
    {
        static::$resolvedInstance = [];
    }

    /**
     * Run a Closure when the facade has been resolved.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function resolved(Closure $callback)
    {
        static::$app->afterResolving(static::getFacadeAccessor(), function ($service) use ($callback) {
            $callback($service);
        });
    }

    /**
     * Hotswap the underlying instance behind the facade.
     *
     * @param  mixed  $instance
     * @return void
     */
    public static function swap($instance)
    {
        static::$resolvedInstance[static::getFacadeAccessor()] = $instance;
        if (isset(static::$app)) {
            static::$app->instance(static::getFacadeAccessor(), $instance);
        }
    }

    /**
     * Get the root object behind the facade.
     *
     * @return mixed
     */
    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }

    /**
     * Get the registered name of the component.
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    protected static function getFacadeAccessor()
    {
        throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
    }

    /**
     * Resolved Instance
     *
     * @param string $facadeName
     * @return string
     */
    protected static function resolveInstance($facadeName)
    {
        if (is_object($facadeName)) {
            return $facadeName;
        }

        if (isset(static::$resolvedInstance[$facadeName])) {
            return static::$resolvedInstance[$facadeName];
        }

        return static::$resolvedInstance[$facadeName] = static::$app->get($facadeName);
    }

    /**
     * Call Methods in Application Object
     *
     * @param string $method
     * @param array  $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        $accessor = strtolower(static::getFacadeAccessor());
        $provider = static::resolveInstance(strtolower($accessor));

        if (!array_key_exists($accessor, static::$createdInstances)) {
            static::$createdInstances[$accessor] = $provider;
        }

        return call_user_func_array([static::$createdInstances[$accessor], $method], $parameters);
    }

    /**
     * Call Methods in Application Object
     *
     * @param string $method
     * @param array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return self::__callStatic($method, $parameters);
    }
}


<?php

namespace Nur\Kernel;

use Closure;
use RuntimeException;
use Nur\Container\Container;
use Nur\Kernel\ServiceProvider;
use Nur\Exception\ExceptionHandler;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Collection;
use Illuminate\Filesystem\Filesystem;
use Whoops\Handler\PrettyPageHandler as WhoopsPrettyPageHandler;
use Whoops\Run as WhoopsRun;

class Application extends Container
{
    /**
     * Nur Framework Version
     *
     * @var string
     */
    const VERSION = '1.0.0';

    /**
     * The base path for the Nur Framework installation.
     *
     * @var string
     */
    protected $basePath;

    /**
     * Indicates if the application has been bootstrapped before.
     *
     * @var bool
     */
    protected $hasBeenBootstrapped = false;

    /**
     * Indicates if the application has "booted".
     *
     * @var bool
     */
    protected $booted = false;

    /**
     * The array of booting callbacks.
     *
     * @var array
     */
    protected $bootingCallbacks = [];

    /**
     * The array of booted callbacks.
     *
     * @var array
     */
    protected $bootedCallbacks = [];

    /**
     * The array of terminating callbacks.
     *
     * @var array
     */
    protected $terminatingCallbacks = [];

    /**
     * All of the registered service providers.
     *
     * @var array
     */
    protected $serviceProviders = [];

    /**
     * The names of the loaded service providers.
     *
     * @var array
     */
    protected $loadedProviders = [];

    /**
     * The deferred services and their providers.
     *
     * @var array
     */
    protected $deferredServices = [];

    /**
     * The custom database path defined by the developer.
     *
     * @var string
     */
    protected $databasePath;

    /**
     * The custom storage path defined by the developer.
     *
     * @var string
     */
    protected $storagePath;

    /**
     * The application namespace.
     *
     * @var string
     */
    protected $namespace;

    /**
     * Framework core providers
     *
     * @var array
     */
    private $registerCoreProviders = [];

    /**
     * Framework core aliases
     *
     * @var array
     */
    private $registerCoreAliases = [];

    /**
     * Framework config
     *
     * @var array|null
     */
    private $config = null;

    /**
     * Framework root folder
     *
     * @var string|null
     */
    private $root = null;

    /**
     * Framework document root folder
     *
     * @var string|null
     */
    private $docRoot = null;

    /**
     * Create a new Illuminate application instance.
     *
     * @param  string|null  $basePath
     * @return void
     */
    public function __construct()
    {
        $this->root = realpath(getcwd());
        $this->docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
        $this->baseFolder = trim(
            str_replace(
                '\\', '/', str_replace($this->docRoot, '', $this->root) . '/'
            ),
            '/'
        );

        $this->setBasePath($this->root);

        $this->init();

        $this->loadConfigFiles();

        $this->registerBaseBindings();
        $this->registerBaseServiceProviders();
        $this->registerCoreContainerAliases();
        $this->registerApplicationProviders();
        $this->registerApplicationAliases();
    }

    /**
     * Application Initializer
     *
     * @return void
     */
    protected function init()
    {
        $this->registerCoreProviders = [
            \Nur\Providers\Event::class,
            \Nur\Providers\Route::class,
            \Nur\Providers\Load::class,
            \Nur\Providers\Uri::class,
            \Nur\Providers\Request::class,
            \Nur\Providers\Response::class,
            \Nur\Providers\Encryption::class,
        ];

        $this->registerCoreAliases = [
            'Route' => \Nur\Facades\Route::class,
        ];
    }

    /**
     * Load application configuration files
     *
     * @return void
     * @throws
     */
    protected function loadConfigFiles()
    {
        try {
            if (file_exists($this->cachePath('config.php'))) {
                $this->config = require $this->cachePath('config.php');
            } else {
                $dotenv = new \Dotenv\Dotenv($this->root);
                $dotenv->load();
                foreach (glob($this->root . '/config/*.php') as $file) {
                    $keyName = strtolower(str_replace(
                        [$this->root . '/config/', '.php'], '', $file
                    ));
                    $this->config[$keyName] = require $file;
                }
            }
        } catch (Exception $e) {
            die(printf(
                "Configuration information could not be retrieved properly.\nError Message: %s",
                $e->getMessage()
            ));
        }
    }

    /**
     * Kernel start
     *
     * @param string $env
     *
     * @return void
     */
    public function start($env)
    {
        switch ($env) {
            case 'dev':
                ini_set('display_errors', 1);
                error_reporting(1);
                $this->initWhoops();
                break;
            case 'test':
            case 'prod':
                ini_set('display_errors', 0);
                error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
                break;
            default:
                header('HTTP/1.1 503 Service Unavailable.', true, 503);
                die('The application environment is not set correctly.');
        }

        if (file_exists(storage_path('app.down'))) {
            throw new ExceptionHandler('The system is under maintenance.', 'We will be back very soon.');
        }

        if (! $this->hasBeenBootstrapped()) {
            $this->bootstrap();
        }

        require $this->path('routes.php');
        $this->app['route']->run();
    }

    /**
     * Get the version number of the application.
     *
     * @return string
     */
    public function version()
    {
        return static::VERSION;
    }

    /**
     * Get the configs of the application.
     *
     * @return string
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * Application root path
     *
     * @return string
     */
    public function root()
    {
        return $this->root;
    }

    /**
     * Application document root path
     *
     * @return string
     */
    public function docRoot()
    {
        return $this->docRoot;
    }

    /**
     * Application base folder
     *
     * @return string
     */
    public function baseFolder()
    {
        return $this->baseFolder;
    }

    /**
     * Register the basic bindings into the container.
     *
     * @return void
     */
    protected function registerBaseBindings()
    {
        static::setInstance($this);

        $this->instance('app', $this);

        $this->instance(Container::class, $this);

        $this->singleton('config', function() {
            return new \Nur\Config\Config($this->config);
        });

        $this->singleton('files', function () {
            return new Filesystem;
        });

        $this->instance(PackageManifest::class, new PackageManifest(
            new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
        ));
    }

    /**
     * Register all of the base service providers.
     *
     * @return void
     */
    protected function registerBaseServiceProviders()
    {
        foreach ($this->registerCoreProviders as $provider) {
            $this->register(new $provider($this));
        }
    }

    /**
     * Register providers of Application
     *
     * @return void
     */
    protected function registerApplicationProviders()
    {
        foreach ($this->config['services']['providers'] as $provider) {
            $this->register(new $provider($this));
        }
    }

    /**
     * Register aliases of Application
     *
     * @return void
     */
    protected function registerApplicationAliases()
    {
        foreach ($this->config['services']['aliases'] as $key => $alias) {
            $this->alias($key, $alias);
            if (! class_exists($key)) {
                class_alias($alias, $key);
            }
        }
    }

    /**
     * Run the given array of bootstrap classes.
     *
     * @return void
     */
    public function bootstrap()
    {
        $this->hasBeenBootstrapped = true;

        $this['events']->dispatch('bootstrapping', [$this]);
        $this->boot();
        $this['events']->dispatch('bootstrapped', [$this]);
    }

    /**
     * Register a callback to run before a bootstrapper.
     *
     * @param  string  $bootstrapper
     * @param  \Closure  $callback
     * @return void
     */
    public function beforeBootstrapping($bootstrapper, Closure $callback)
    {
        $this['events']->listen('bootstrapping: '.$bootstrapper, $callback);
    }

   /**
     * Register a callback to run after a bootstrapper.
     *
     * @param  string  $bootstrapper
     * @param  \Closure  $callback
     * @return void
     */
    public function afterBootstrapping($bootstrapper, Closure $callback)
    {
        $this['events']->listen('bootstrapped: '.$bootstrapper, $callback);
    }

    /**
     * Determine if the application has been bootstrapped before.
     *
     * @return bool
     */
    public function hasBeenBootstrapped()
    {
        return $this->hasBeenBootstrapped;
    }

    /**
     * Set the base path for the application.
     *
     * @param  string  $basePath
     * @return $this
     */
    public function setBasePath($basePath)
    {
        $this->basePath = rtrim($basePath, '\/');

        $this->bindPathsInContainer();

        return $this;
    }

    /**
     * Bind all of the application paths in the container.
     *
     * @return void
     */
    protected function bindPathsInContainer()
    {
        $this->instance('path', $this->path());
        $this->instance('path.base', $this->basePath());
        $this->instance('path.lang', $this->langPath());
        $this->instance('path.config', $this->configPath());
        $this->instance('path.storage', $this->storagePath());
        $this->instance('path.database', $this->databasePath());
        $this->instance('path.cache', $this->cachePath());
        $this->instance('path.public', $this->publicPath());
    }

    /**
     * Get the path to the application "app" directory.
     *
     * @param  string  $path Optionally, a path to append to the app path
     * @return string
     */
    public function path($path = '')
    {
        return $this->root().DIRECTORY_SEPARATOR.'app'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

    /**
     * Get the base path of the Nur Framework installation.
     *
     * @param  string  $path Optionally, a path to append to the base path
     * @return string
     */
    public function basePath($path = '')
    {
        return $this->root().($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

    /**
     * Get the path to the application configuration files.
     *
     * @param  string  $path Optionally, a path to append to the config path
     * @return string
     */
    public function configPath($path = '')
    {
        return $this->root().DIRECTORY_SEPARATOR.'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

    /**
     * Get the path to the database directory.
     *
     * @param  string $path Optionally, a path to append to the database path
     *
     * @return string
     */
    public function databasePath($path = '')
    {
        return $this->root().DIRECTORY_SEPARATOR.'database'.($path ? DIRECTORY_SEPARATOR . $path : $path);
    }

    /**
     * Get the path to the language files.
     *
     * @return string
     */
    public function langPath()
    {
        return $this->path().DIRECTORY_SEPARATOR.'lang';
    }

    /**
     * Get the path to the storage directory.
     *
     * @param  string $path Optionally, a path to append to the storage path
     *
     * @return string
     */
    public function storagePath($path = '')
    {
        return $this->root().DIRECTORY_SEPARATOR.'storage'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

    /**
     * Get the path to the cache directory.
     *
     * @param  string $path Optionally, a path to append to the cache path
     *
     * @return string
     */
    public function cachePath($path = '')
    {
        return $this->storagePath('cache') . ($path ? DIRECTORY_SEPARATOR . $path : $path);
    }

    /**
     * Get the path to the application public files.
     *
     * @param  string  $path Optionally, a path to append to the public path
     * @return string
     */
    public function publicPath($path = '')
    {
        return $this->root().DIRECTORY_SEPARATOR.'public'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

    /**
     * Determine if the application is running in the console.
     *
     * @return bool
     */
    public function runningInConsole()
    {
        if (isset($_ENV['APP_RUNNING_IN_CONSOLE'])) {
            return $_ENV['APP_RUNNING_IN_CONSOLE'] === 'true';
        }

        return php_sapi_name() === 'cli' || php_sapi_name() === 'phpdbg';
    }

    /**
     * Register all of the configured providers.
     *
     * @return void
     */
    public function registerConfiguredProviders()
    {
        $providers = Collection::make($this->config['app.providers'])
                        ->partition(function ($provider) {
                            return Str::startsWith($provider, 'Nur\\');
                        });
        $providers->splice(1, 0, [$this->make(PackageManifest::class)->providers()]);
        (new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath()))
                    ->load($providers->collapse()->toArray());
    }

    /**
     * Register a service provider with the application.
     *
     * @param  \Nur\Kernel\ServiceProvider|string  $provider
     * @param  bool   $force
     * @return \Nur\Kernel\ServiceProvider
     */
    public function register($provider, $force = false)
    {
        if (($registered = $this->getProvider($provider)) && ! $force) {
            return $registered;
        }

        // If the given "provider" is a string, we will resolve it, passing in the
        // application instance automatically for the developer. This is simply
        // a more convenient way of specifying your service provider classes.
        if (is_string($provider)) {
            $provider = $this->resolveProvider($provider);
        }

        if (method_exists($provider, 'register')) {
            $provider->register();
        }

        // If there are bindings / singletons set as properties on the provider we
        // will spin through them and register them with the application, which
        // serves as a convenience layer while registering a lot of bindings.
        if (property_exists($provider, 'bindings')) {
            foreach ($provider->bindings as $key => $value) {
                $this->bind($key, $value);
            }
        }

        if (property_exists($provider, 'singletons')) {
            foreach ($provider->singletons as $key => $value) {
                $this->singleton($key, $value);
            }
        }

        $this->markAsRegistered($provider);

        // If the application has already booted, we will call this boot method on
        // the provider class so it has an opportunity to do its boot logic and
        // will be ready for any usage by this developer's application logic.
        if ($this->booted) {
            $this->bootProvider($provider);
        }

        return $provider;
    }

    /**
     * Get the registered service provider instance if it exists.
     *
     * @param  \Nur\Kernel\ServiceProvider|string  $provider
     * @return \Nur\Kernel\ServiceProvider|null
     */
    public function getProvider($provider)
    {
        return array_values($this->getProviders($provider))[0] ?? null;
    }

    /**
     * Get the registered service provider instances if any exist.
     *
     * @param  \Nur\Kernel\ServiceProvider|string  $provider
     * @return array
     */
    public function getProviders($provider)
    {
        $name = is_string($provider) ? $provider : get_class($provider);

        return Arr::where($this->serviceProviders, function ($value) use ($name) {
            return $value instanceof $name;
        });
    }

    /**
     * Resolve a service provider instance from the class name.
     *
     * @param  string  $provider
     * @return \Nur\Kernel\ServiceProvider
     */
    public function resolveProvider($provider)
    {
        return new $provider($this);
    }

    /**
     * Mark the given provider as registered.
     *
     * @param  \Nur\Kernel\ServiceProvider  $provider
     * @return void
     */
    protected function markAsRegistered(ServiceProvider $provider)
    {
        $this->serviceProviders[] = $provider;

        $this->loadedProviders[get_class($provider)] = true;
    }

    /**
     * Load and boot all of the remaining deferred providers.
     *
     * @return void
     */
    public function loadDeferredProviders()
    {
        // We will simply spin through each of the deferred providers and register each
        // one and boot them if the application has booted. This should make each of
        // the remaining services available to this application for immediate use.
        foreach ($this->deferredServices as $service => $provider) {
            $this->loadDeferredProvider($service);
        }

        $this->deferredServices = [];
    }

    /**
     * Load the provider for a deferred service.
     *
     * @param  string  $service
     * @return void
     */
    public function loadDeferredProvider($service)
    {
        if (! isset($this->deferredServices[$service])) {
            return;
        }

        $provider = $this->deferredServices[$service];

        // If the service provider has not already been loaded and registered we can
        // register it with the application and remove the service from this list
        // of deferred services, since it will already be loaded on subsequent.
        if (! isset($this->loadedProviders[$provider])) {
            $this->registerDeferredProvider($provider, $service);
        }
    }

    /**
     * Register a deferred provider and service.
     *
     * @param  string  $provider
     * @param  string|null  $service
     * @return void
     */
    public function registerDeferredProvider($provider, $service = null)
    {
        // Once the provider that provides the deferred service has been registered we
        // will remove it from our local list of the deferred services with related
        // providers so that this container does not try to resolve it out again.
        if ($service) {
            unset($this->deferredServices[$service]);
        }

        $this->register($instance = new $provider($this));

        if (! $this->booted) {
            $this->booting(function () use ($instance) {
                $this->bootProvider($instance);
            });
        }
    }

    /**
     * Resolve the given type from the container.
     *
     * (Overriding Container::make)
     *
     * @param  string  $abstract
     * @param  array  $parameters
     * @return mixed
     */
    public function make($abstract, array $parameters = [])
    {
        $abstract = $this->getAlias($abstract);

        if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
            $this->loadDeferredProvider($abstract);
        }

        return parent::make($abstract, $parameters);
    }

    /**
     * Determine if the given abstract type has been bound.
     *
     * (Overriding Container::bound)
     *
     * @param  string  $abstract
     * @return bool
     */
    public function bound($abstract)
    {
        return isset($this->deferredServices[$abstract]) || parent::bound($abstract);
    }

    /**
     * Determine if the application has booted.
     *
     * @return bool
     */
    public function isBooted()
    {
        return $this->booted;
    }

    /**
     * Boot the application's service providers.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->booted) {
            return;
        }

        // Once the application has booted we will also fire some "booted" callbacks
        // for any listeners that need to do work after this initial booting gets
        // finished. This is useful when ordering the boot-up processes we run.
        $this->fireAppCallbacks($this->bootingCallbacks);

        array_walk($this->serviceProviders, function ($p) {
            $this->bootProvider($p);
        });

        $this->booted = true;

        $this->fireAppCallbacks($this->bootedCallbacks);
    }

    /**
     * Boot the given service provider.
     *
     * @param  \Nur\Kernel\ServiceProvider  $provider
     * @return mixed
     */
    protected function bootProvider(ServiceProvider $provider)
    {
        if (method_exists($provider, 'boot')) {
            return $this->call([$provider, 'boot']);
        }
    }

    /**
     * Register a new boot listener.
     *
     * @param  mixed  $callback
     * @return void
     */
    public function booting($callback)
    {
        $this->bootingCallbacks[] = $callback;
    }

    /**
     * Register a new "booted" listener.
     *
     * @param  mixed  $callback
     * @return void
     */
    public function booted($callback)
    {
        $this->bootedCallbacks[] = $callback;

        if ($this->isBooted()) {
            $this->fireAppCallbacks([$callback]);
        }
    }

    /**
     * Call the booting callbacks for the application.
     *
     * @param  array  $callbacks
     * @return void
     */
    protected function fireAppCallbacks(array $callbacks)
    {
        foreach ($callbacks as $callback) {
            call_user_func($callback, $this);
        }
    }

    /**
     * Get the path to the cached services.php file.
     *
     * @return string
     */
    public function getCachedServicesPath()
    {
        return $this->cachePath().'/services.php';
    }

    /**
     * Get the path to the cached packages.php file.
     *
     * @return string
     */
    public function getCachedPackagesPath()
    {
        return $this->cachePath().'/packages.php';
    }

    /**
     * Determine if the application configuration is cached.
     *
     * @return bool
     */
    public function configurationIsCached()
    {
        return file_exists($this->getCachedConfigPath());
    }

    /**
     * Get the path to the configuration cache file.
     *
     * @return string
     */
    public function getCachedConfigPath()
    {
        return $_ENV['APP_CONFIG_CACHE'] ?? $this->cachePath().'/config.php';
    }

    /**
     * Determine if the application routes are cached.
     *
     * @return bool
     */
    public function routesAreCached()
    {
        return $this['files']->exists($this->getCachedRoutesPath());
    }

    /**
     * Get the path to the routes cache file.
     *
     * @return string
     */
    public function getCachedRoutesPath()
    {
        return $this->cachePath().'/routes.php';
    }

    /**
     * Determine if the application is currently down for maintenance.
     *
     * @return bool
     */
    public function isDownForMaintenance()
    {
        return file_exists($this->storagePath().'/app.down');
    }

    /**
     * Register a terminating callback with the application.
     *
     * @param  \Closure  $callback
     * @return $this
     */
    public function terminating(Closure $callback)
    {
        $this->terminatingCallbacks[] = $callback;

        return $this;
    }

    /**
     * Terminate the application.
     *
     * @return void
     */
    public function terminate()
    {
        foreach ($this->terminatingCallbacks as $terminating) {
            $this->call($terminating);
        }
    }

    /**
     * Get the service providers that have been loaded.
     *
     * @return array
     */
    public function getLoadedProviders()
    {
        return $this->loadedProviders;
    }

    /**
     * Get the application's deferred services.
     *
     * @return array
     */
    public function getDeferredServices()
    {
        return $this->deferredServices;
    }

    /**
     * Set the application's deferred services.
     *
     * @param  array  $services
     * @return void
     */
    public function setDeferredServices(array $services)
    {
        $this->deferredServices = $services;
    }

    /**
     * Add an array of services to the application's deferred services.
     *
     * @param  array  $services
     * @return void
     */
    public function addDeferredServices(array $services)
    {
        $this->deferredServices = array_merge($this->deferredServices, $services);
    }

    /**
     * Determine if the given service is a deferred service.
     *
     * @param  string  $service
     * @return bool
     */
    public function isDeferredService($service)
    {
        return isset($this->deferredServices[$service]);
    }

    /**
     * Configure the real-time facade namespace.
     *
     * @param  string  $namespace
     * @return void
     */
    public function provideFacades($namespace)
    {
        AliasLoader::setFacadeNamespace($namespace);
    }

    /**
     * Register the core class aliases in the container.
     *
     * @return void
     */
    public function registerCoreContainerAliases()
    {
        // Prepare Facades
        Facade::clearResolvedInstances();
        Facade::setApplication($this);

        foreach ($this->registerCoreAliases as $key => $alias) {
            $this->alias($key, $alias);
            if (! class_exists($key)) {
                class_alias($alias, $key);
            }
        }
    }

    /**
     * Flush the container of all bindings and resolved instances.
     *
     * @return void
     */
    public function flush()
    {
        parent::flush();

        $this->buildStack = [];
        $this->loadedProviders = [];
        $this->bootedCallbacks = [];
        $this->bootingCallbacks = [];
        $this->deferredServices = [];
        $this->reboundCallbacks = [];
        $this->serviceProviders = [];
        $this->resolvingCallbacks = [];
        $this->afterResolvingCallbacks = [];
        $this->globalResolvingCallbacks = [];
    }

    /**
     * Get the application namespace.
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    public function getNamespace()
    {
        if (! is_null($this->namespace)) {
            return $this->namespace;
        }

        $composer = json_decode(file_get_contents(base_path('composer.json')), true);

        foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) {
            foreach ((array) $path as $pathChoice) {
                if (realpath(app_path()) == realpath(base_path().'/'.$pathChoice)) {
                    return $this->namespace = $namespace;
                }
            }
        }

        throw new RuntimeException('Unable to detect application namespace.');
    }

    /**
     * Whoops Initializer
     *
     * @return void
     */
    protected function initWhoops()
    {
        $whoops = new WhoopsRun;
        $whoops->pushHandler(new WhoopsPrettyPageHandler);
        $whoops->register();
    }
}


<?php

namespace Nur\Uri;

class UriGenerator
{
    protected $base = null;
    protected $url = null;
    protected $https = false;
    protected $cachedHttps = false;

    /**
     * Create URI class values.
     *
     * @return string | null
     */
    function __construct()
    {
        $this->base = BASE_FOLDER;

        $this->url = http()->server('HTTP_HOST') . '/' . $this->base . '/';
        if (!in_array(http()->server('HTTPS'), [null, 'off', 'false']) ||
            http()->server('SERVER_PORT') == 443 || config('app.https') === true) {
            $this->cachedHttps = true;
        }

        return;
    }

    /**
     * Get base url for app.
     *
     * @param string $data
     * @param bool   $secure
     *
     * @return string
     */
    public function base($data = null, $secure = false)
    {
        $data = (! is_null($data)) ? $this->url . $data : $this->url . '/';
        return $this->getUrl($data, $secure);
    }

    /**
     * Get admin url for app.
     *
     * @param string $data
     * @param bool   $secure
     *
     * @return string
     */
    public function admin($data = null, $secure = false)
    {
        $data = (! is_null($data))
            ? $this->url . '/' . ADMIN_FOLDER . '/' . $data
            : $this->url . '/' . ADMIN_FOLDER . '/';
        return $this->getUrl($data, $secure);
    }

    /**
     * Get route uri value with params.
     *
     * @param string $name
     * @param array  $params
     * @param bool   $secure
     *
     * @return string
     */
    public function route($name, array $params = null, $secure = false)
    {
        $routes = file_exists(cache_path('routes.php'))
            ? require cache_path('routes.php')
            : app('route')->getRoutes();

        $found = false;
        foreach ($routes as $key => $value) {
            if ($value['alias'] == $name) {
                $found = true;
                break;
            }
        }

        if ($found) {
            if (strstr($routes[$key]['route'], '{')) {
                $segment = explode('/', $routes[$key]['route']);
                $i = 0;
                foreach ($segment as $key => $value) {
                    if (strstr($value, '{')) {
                        $segment[$key] = $params[$i];
                        $i++;
                    }
                }
                $newUrl = implode('/', $segment);
            } else {
                $newUrl = $routes[$key]['route'];
            }

            $data = str_replace($this->base, '', $this->url) . '/' . $newUrl;
            return $this->getUrl($data, $secure);
        }

        return $this->getUrl($this->url, $secure);
    }

    /**
     * Get assets directory for app.
     *
     * @param string $data
     * @param bool   $secure
     *
     * @return string
     */
    public function assets($data = null, $secure = false)
    {
        $data = (! is_null($data))
            ? $this->url . '/' . ASSETS_FOLDER . '/' . $data
            : $this->url . '/' . ASSETS_FOLDER . '/';
        return $this->getUrl($data, $secure);
    }

    /**
     * Redirect to another URL.
     *
     * @param string $data
     * @param int    $statusCode
     * @param bool   $secure
     *
     * @return null
     */
    public function redirect($data = null, int $statusCode = 301, $secure = false)
    {
        if (substr($data, 0, 4) === 'http' || substr($data, 0, 5) === 'https') {
            header('Location: ' . $data, true, $statusCode);
        } else {
            $data = (! is_null($data)) ? $this->url . '/' . $data : $this->url;
            header('Location: ' . $this->getUrl($data, $secure), true, $statusCode);
        }

        die();
    }

    /**
     * Get active URI.
     *
     * @return string | null
     */
    public function current()
    {
        return $this->scheme() . http()->server('HTTP_HOST') . http()->server('REQUEST_URI');
    }

    /**
     * Get segments of URI.
     *
     * @param int $num
     *
     * @return string | null
     */
    public function segment($num = null)
    {
        if (is_null(http()->server('REQUEST_URI')) || is_null(http()->server('SCRIPT_NAME'))) {
            return null;
        }

        if (! is_null($num)) {
            $uri = $this->replace(str_replace($this->base, '', http()->server('REQUEST_URI')));
            $uriA = explode('/', $uri);
            return (isset($uriA[$num]) ? reset(explode('?', $uriA[$num])) : null);
        }

        return null;
    }

    /**
     * Get url.
     *
     * @param string $data
     * @param bool   $secure
     *
     * @return string
     */
    protected function getUrl($data, $secure)
    {
        $this->https = $secure;
        return $this->scheme() . $this->replace($data);
    }

    /**
     * Get url scheme.
     *
     * @return string
     */
    protected function scheme()
    {
        if ($this->cachedHttps === true) {
            $this->https = true;
        }

        return "http" . ($this->https === true ? 's' : '') . "://";
    }

    /**
     * Replace.
     *
     * @param string $data
     *
     * @return string | null
     */
    private function replace($data)
    {
        return str_replace(['///', '//'], '/', $data);
    }
}


<?php

namespace Nur\Components\Cache;

class Cache
{
    /**
     * Cache file target
     *
     * @var string
     */
    protected $file;

    /**
     * Cache save path
     *
     * @var string
     */
    protected $path = '/storage/cache/html';

    /**
     * Cache file prefix
     *
     * @var string
     */
    protected $prefix = '%nurfw%';

    /**
     * Cache file extension
     *
     * @var string
     */
    protected $extension = '.cache';

    /**
     * Save cache file
     *
     * @param string $content
     * @param int    $time
     *
     * @return string|bool
     */
    public function save($content = null, $time = 30)
    {
        $fileName = md5($this->prefix . http()->server('REQUEST_URI')) . $this->extension;
        $this->file = cache_path('html' . DIRECTORY_SEPARATOR . $fileName);

        $this->start($time);
        return $this->finish($content);
    }

    /**
     * Cache start
     *
     * @param int $time
     *
     * @return mixed
     */
    protected function start($time = 1)
    {
        if (file_exists($this->file)) {
            if (time() - $time < filemtime($this->file)) {
                die(readfile($this->file));
            }
            return $this->delete();
        }

        touch($this->file);
    }

    /**
     * Finish cache and save file
     *
     * @param string $output
     *
     * @return mixed
     */
    protected function finish($output = null)
    {
        if (! is_null($output)) {
            $file = fopen($this->file, 'w+');
            fwrite($file, $output);
            fclose($file);
            return $output;
        }

        return false;
    }

    /**
     * Delete cache file
     *
     * @return bool
     */
    protected function delete()
    {
        return unlink($this->file);
    }
}


<?php

namespace Nur\Providers;

use Nur\Kernel\ServiceProvider;
use Illuminate\Pagination\Paginator;

class Database extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     * @throws
     */
    public function register()
    {
        $this->app->singleton('builder', \Nur\Database\Builder::class);

        // Paginator::viewFactoryResolver(function () {
        //     return $this->app['view'];
        // });
        Paginator::currentPathResolver(function () {
            return $this->app['request']->url();
        });
        Paginator::currentPageResolver(function ($pageName = 'page') {
            $page = $this->app['request']->input($pageName);
            if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) {
                return (int) $page;
            }
            return 1;
        });
    }
}