protected function createMiddlewareStack(ServiceOptions $serviceOptions)
    {
        //If handler stack is not defined by the user, create a default
        //middleware stack.
        $stack = null;
        if (array_key_exists('stack', $this->options['http'])) {
            $stack = $this->options['http']['stack'];
        } elseif ($serviceOptions->getMiddlewareStack() != null) {
            $stack = $serviceOptions->getMiddlewareStack();
        } else {
            $stack = new MiddlewareStack();
        }

        //Push all the middlewares specified in the $serviceOptions to the
        //handlerstack.
        if ($serviceOptions->getMiddlewares() != array()) {
            foreach ($serviceOptions->getMiddlewares() as $middleware) {
                $stack->push($middleware);
            }
        }

        //Push all the middlewares specified in the $options to the
        //handlerstack.
        if (array_key_exists('middlewares', $this->options)) {
            foreach ($this->options['middlewares'] as $middleware) {
                $stack->push($middleware);
            }
        }

        //Push all the middlewares specified in $this->middlewares to the
        //handlerstack.
        foreach ($this->getMiddlewares() as $middleware) {
            $stack->push($middleware);
        }

        return $stack;
    }