Sort the middlewares by the given priority map.

Each call to this method makes one discrete middleware movement if necessary.

@param  array  $priorityMap
@param  array  $middlewares
@return array
167083
protected function sortMiddleware($priorityMap, $middlewares)
    {
        $lastIndex = 0;

        foreach ($middlewares as $index => $middleware) {
            if (! is_string($middleware)) {
                continue;
            }

            $stripped = head(explode(':', $middleware));

            if (in_array($stripped, $priorityMap)) {
                $priorityIndex = array_search($stripped, $priorityMap);

                // This middleware is in the priority map. If we have encountered another middleware
                // that was also in the priority map and was at a lower priority than the current
                // middleware, we will move this middleware to be above the previous encounter.
                if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) {
                    return $this->sortMiddleware(
                        $priorityMap, array_values($this->moveMiddleware($middlewares, $index, $lastIndex))
                    );
                }

                // This middleware is in the priority map; but, this is the first middleware we have
                // encountered from the map thus far. We'll save its current index plus its index
                // from the priority map so we can compare against them on the next iterations.
                $lastIndex = $index;
                $lastPriorityIndex = $priorityIndex;
            }
        }

        return array_values(array_unique($middlewares, SORT_REGULAR));
    }
316827
public function resolve($middlewares)
    {
        $last = function ($request, $response) {
            // no op
        };
        while ($middleware = array_pop($middlewares)) {
            if (is_object($middleware)) {
                if (method_exists($middleware, '__invoke')) {
                    $middleware = [$middleware, '__invoke'];
                }
            }

            if (!is_callable($middleware)) {
                throw new \InvalidArgumentException('Middle needs to be callable');
            }

            $last = function () use ($middleware, $last) {
                $args = func_get_args();
                $args[] = $last;
                return call_user_func_array($middleware, $args);
            };
        }
        return $last;
    }
560272
private function orderByPriority($eventListeners)
    {
        /**
         * @param int $a
         * @param int $b
         *
         * @return int
         */
        $comparisonFunction = function ($a, $b) {
            if ($a->getPriority() == $b->getPriority()) {
                // This will keep the order of same priority listeners in the order of subscribing
                return 1;
            }

            return ($a->getPriority() > $b->getPriority()) ? -1 : 1;
        };

        return $this->arr($eventListeners)->sortUsingFunction($comparisonFunction)->val();
    }
323631
protected function resolveMiddleware(string $middleware): array
	{
		[$name, $parameters] = $this->parseFunction($middleware);

		if(!isset($this->middleware[$name]))
		{
			throw new RuntimeException(vsprintf('No middleware named [ %s ] has been registered.', [$middleware]));
		}

		return ['name' => $name, 'middleware' => $this->middleware[$name], 'parameters' => $parameters];
	}
278724
protected function parseMiddleware($middleware)
    {
        list($name, $parameters) = array_pad(explode(':', $middleware, 2), 2, array());

        if (is_string($parameters)) {
            $parameters = explode(',', $parameters);
        }

        return array($name, $parameters);
    }
338206
protected function marshalMiddleware($middleware)
    {
        if (!$middleware instanceof Psr7InvokableInterface) {
            $middleware = new Psr7Middleware($middleware);
        }

        return parent::marshalMiddleware($middleware);
    }
1115895
protected function moveMiddleware($middlewares, $from, $to)
    {
        array_splice($middlewares, $to, 0, $middlewares[$from]);

        unset($middlewares[$from + 1]);

        return $middlewares;
    }
1170997
public function insertMiddlewares(array $middlewares, $offset = null)
    {
        null === $offset && $offset = $this->offset;
        $chunkArray = array_chunk($this->middlewares, $offset);
        $after = [];
        $before = $chunkArray[0];
        if (isset($chunkArray[1])) {
            $after = $chunkArray[1];
        }
        $middlewares = array_merge((array)$before, $middlewares, (array)$after);
        $this->middlewares = $middlewares;
        return $this;
    }
486075
public function setHandlerPriority(CommandHandlerInterface $handler, $priority)
    {
        $this->__queue->setPriority($handler, $priority);
        return $this;
    }
179361
protected function getQueueSortingCallback()
    {
        // [$resourceId => $parentId]
        $parentMap = $this->registry->getParentMap();

        // [$resourceId => $priority]
        $priorityMap = $this->registry->getEventPriorityMap();

        /**
         * Returns whether or not $a is a child of $b.
         *
         * @param string $a
         * @param string $b
         *
         * @return bool
         *
         * @todo Move in resource registry
         */
        $isChildOf = function($a, $b) use ($parentMap) {
            while (isset($parentMap[$a])) {
                $parentId = $parentMap[$a];
                if ($parentId === $b) {
                    return true;
                }
                $a = $parentId;
            }
            return false;
        };

        return function ($a, $b) use ($isChildOf, $priorityMap) {
            $aId = $this->getEventPrefix($a);
            $bId = $this->getEventPrefix($b);

            // By prefix (resource id) priority
            $aPriority = isset($priorityMap[$aId]) ? $priorityMap[$aId] : 0;
            $bPriority = isset($priorityMap[$bId]) ? $priorityMap[$bId] : 0;

            if ($aPriority > $bPriority) {
                return -1;
            } elseif ($bPriority > $aPriority) {
                return 1;
            }

            // By resource hierarchy (children first)
            if ($isChildOf($aId, $bId)) {
                // B is a parent of A
                return -1;
            } elseif ($isChildOf($bId, $aId)) {
                // A is a parent of B
                return 1;
            }

            // By suffix priority
            $aPriority = $this->getEventPriority($a);
            $bPriority = $this->getEventPriority($b);

            if ($aPriority > $bPriority) {
                return -1;
            } elseif ($bPriority > $aPriority) {
                return 1;
            }

            return 0;
        };
    }
1326345
public function middleware($middleware, $name = null)
	{
        if($name)
            $this->properties['middleware'][$name] = $middleware;
        else
            $this->properties['middleware'][] = $middleware;

		return $this;
	}
1305839
private function sortLocalesByPriority(array $a, array $b)
    {
        $a = isset($a['priority']) ? $a['priority'] : 0;
        $b = isset($b['priority']) ? $b['priority'] : 0;

        if ($a === $b) {
            return 0;
        }
        return ($a < $b) ? (-1) : 1;
    }
408028
public function validMiddleware(array &$middlewares)
    {
        if (! $middlewares) {
            return;
        }

        foreach ($middlewares as &$middleware) {
            if ($middleware instanceof \Closure) {
                continue;
            }

            if (! $this->hasMiddleware($middleware)) {
                throw new \Exception("Middleware not found. [{$middleware}]");
            }
        }
    }
453111
private function normalizePriorities(Request $request, array $priorities)
    {
        $priorities = $this->sanitize($priorities);

        $mimeTypes = array();
        foreach ($priorities as $priority) {
            if (strpos($priority, '/')) {
                $mimeTypes[] = $priority;

                continue;
            }

            if (method_exists(Request::class, 'getMimeTypes')) {
                $mimeTypes = array_merge($mimeTypes, Request::getMimeTypes($priority));
            } elseif (null !== $request->getMimeType($priority)) {
                $class = new \ReflectionClass(Request::class);
                $properties = $class->getStaticProperties();
                $mimeTypes = array_merge($mimeTypes, $properties['formats'][$priority]);
            }

            if (isset($this->mimeTypes[$priority])) {
                foreach ($this->mimeTypes[$priority] as $mimeType) {
                    $mimeTypes[] = $mimeType;
                }
            }
        }

        return $mimeTypes;
    }
1030732
public function use($middlewares) {
		$middlewares = (array)$middlewares;

		if ($this->namespace) {
			foreach ($middlewares as &$middleware) {
				$middleware = $this->namespace . $middleware;
			}
		}

		$this->middlewares = array_merge($this->middlewares, (array)$middlewares);

		return $this;
	}
239491
public function addMiddleware(MiddlewareInterface $middleware, $priority = 10)
    {
        $this->stack = $this->stack->withMiddleware($middleware, $priority);
        return $this;
    }
1281071
public function addMiddleware($middleware, $priority = PriorityQueue::NORMAL)
    {
        $this->middlewares->insert($middleware, $priority);

        return $this;
    }