{@inheritdoc}

@api

@throws Exception\MethodNotImplemented if any enabled state implement the required method
@throws \Throwable

@see http://php.net/manual/en/class.arrayaccess.php
434792
public function offsetUnset($offset): void
    {
        $args = [$offset];
        $methodName = __FUNCTION__;

        $this->findAndCall($methodName, $args);
    }
812315
final public function execute() {
		if (!is_array($this->controller->accessRules()))
			throw new \Exception('Authentication failed: Method "accessRules" in "' .
				$this->controller->getClass() . '" must return an array');
		foreach ($this->controller->accessRules() as $rule) {
			if (!is_array($rule))
				throw new \Exception('Authentication error: Each element of the array returned by accessRules() must be an array');

			if (!isset($rule[0]))
				throw new \Exception('Authentication error: Each element of the array returned by accessRules() must indicate permission as its first element');

			$permission = $rule[0];
			$rules = (isset($rule[1])) ? $rule[1] : array();

			if (!is_string($permission) || (is_string($permission) && !in_array($permission, array('allow', 'deny'))))
				throw new \Exception('Authentication error: First element of each rules array can only be either "allow" or "deny"');
			if (isset($rules) && !is_array($rules))
				throw new \Exception('Authentication error: The second element of each rules array must return an array');

			if (strtolower($permission) === 'allow') {
				if ($this->checkPermission($rules) === TRUE)
					return true;
			}
			elseif (strtolower($permission) === 'deny') {
				if ($this->checkPermission($rules) === TRUE)
					return false;
			}
		}

		return true;
	}
558325
public function execute($method=null) {
    $isDebugEnabled = $this->logger->isDebugEnabled();
    if ($isDebugEnabled) {
      $this->logger->debug('Executing: '.get_class($this).($method ? '::'.$method: ''));
      $this->logger->debug('Request: '.$this->request);
    }

    // validate controller data
    $validationFailed = false;
    if (!$this->validate()) {
      $validationFailed = true;
    }

    // execute controller logic
    if (!$validationFailed) {
      try {
        $this->doExecute($method);
        $this->endTransaction(true);
      }
      catch (\Exception $ex) {
        if ($ex instanceof ApplicationException) {
          $error = $ex->getError();
          $this->response->addError($error);
          $this->response->setStatus($error->getStatusCode());
        }
        else {
          $this->getLogger()->error($ex);
          $error = ApplicationError::fromException($ex);
          $this->response->addError($error);
          $this->response->setStatus($error->getStatusCode());
        }
        $this->endTransaction(false);
      }
    }

    // return the last error
    $errors = array_merge($this->request->getErrors(), $this->response->getErrors());
    if (sizeof($errors) > 0) {
      $error = array_pop($errors);
      $this->response->setValue('errorCode', $error->getCode());
      $this->response->setValue('errorMessage', $error->getMessage());
      $this->response->setValue('errorData', $error->getData());
      $this->response->setStatus($error->getStatusCode());
    }

    // log errors
    for ($i=0,$count=sizeof($errors); $i<$count; $i++) {
      $error = $errors[$i];
      $message = $error->__toString();
      switch ($error->getLevel()) {
        case ApplicationError::LEVEL_WARNING:
          $this->logger->warn($message);
          break;
        default:
          $this->logger->error($message);
      }
    }

    if ($isDebugEnabled) {
      $this->logger->debug('Response: '.$this->response);
    }
  }
587075
private function handleUndefinedParameters()
    {
        $leftover = count($this->rawParams);

        if (0 < $leftover) {
            if (1 == $leftover) {
                $msg = 'The parameter \'%s\' is not valid';
            } else {
                $msg = 'The parameters \'%s\' are not valid';
            }

            throw new \Exception(sprintf($msg, implode('\', \'', array_keys($this->rawParams))));
        }
    }
1062300
public function handleException(Throwable $e): void
    {
        $exceptionHandlerPath = null;

        if (($module = Application::getCurrentModule()) !== null) {
            $exceptionHandlerPath = Application::getModulePath($module) . 'controllers/ExceptionHandler.php';
            if (!is_file($exceptionHandlerPath)) {
                $exceptionHandlerPath = Application::getApplicationPath('controllers/ExceptionHandler.php');
            }
        } else {
            $exceptionHandlerPath = Application::getApplicationPath('controllers/ExceptionHandler.php');
        }

        if (is_file($exceptionHandlerPath)) {
            require_once $exceptionHandlerPath;
            $exceptionHandler = new \ExceptionHandler($e);

            if ($exceptionHandler instanceof ResponseExceptionHandler) {
                $exceptionHandler->exec();
            } else {
                $routeException = new ServerException('Your ExceptionHandler is not instance of ResponseExceptionHandler, can not continue');
                Log::emergency($routeException);
                Application::terminateWithError('Your ExceptionHandler is not instance of ResponseExceptionHandler, can not continue');
            }
        } else {
            $exceptionHandler = new ResponseExceptionHandler($e);
            $exceptionHandler->exec();
        }
    }
958107
protected function handleThrowable(
        Throwable $throwable,
        ?PsrContainerInterface $container
    ): ThrowableResponseInterface {
        if ($container !== null && $container->has(ThrowableHandlerInterface::class) === true) {
            /** @var ThrowableHandlerInterface $handler */
            /** @noinspection PhpUnhandledExceptionInspection */
            $handler  = $container->get(ThrowableHandlerInterface::class);
            $response = $handler->createResponse($throwable, $container);
        } else {
            $response = $this->createDefaultThrowableResponse($throwable);
        }

        return $response;
    }
1158338
public function notFoundHttpException(NotFoundHttpException $exception)
    {
        $statuCode = $exception->getStatusCode();
        $error = [[
            'status' => $statuCode,
            'code'   => $this->getCode('not_found_http'),
            'source' => ['pointer' => $exception->getFile().':'.$exception->getLine()],
            'title'  => $this->getDescription($exception),
            'detail' => $this->getNotFoundMessage($exception),
        ]];

        $this->jsonApiResponse->setStatus($statuCode);
        $this->jsonApiResponse->setErrors($error);
    }
259315
function with(array $options, $throwException = false)
    {
        foreach ($options as $key => $val) {
            $key = strtolower($key);
            $this->$key = $val;
        }
    }
276005
public function options()
    {
        if (!($this->response instanceof ResponseInterface)) {
            throw new MethodNotAllowed();
        }

        // Get all implemented methods for this resources
        $methods = get_class_methods(get_class($this));

        // Get supported verbs
        $validMethods = $this->container['validHttpVerbs'];

        // Loop though class functions/methods
        foreach ($methods as $key => &$method) {
            $method = strtoupper($method);
            // If class function/method isn't a verb, then unset it
            if (!in_array($method, $validMethods)) {
                unset($methods[$key]);
            }
        }

        // Set accept header
        $this->response = $this->response->withAddedHeader('Allow', implode(', ', $methods));

        // Prepare output
        $output = [];
        $output['Content-Type'] = $this->container['contentTypes'];
        $output['Accept'] = $this->container['acceptTypes'];

        foreach ($methods as $verb) {
            $doc = $this->parseMethodDoc($verb);

            // Check if there is any output to show
            if (!empty($doc)) {
                $output['methods'][$verb] = $doc;
            }
        }

        // return output
        return $output;
    }
984899
public function check(array $input)
    {
        $missing = [];
        $invalid = [];

        $check = function ($constraint, $key, $value, $input) use (
            &$missing,
            &$invalid
        ) {
            if ($constraint instanceof AbstractConstraint) {
                if (!$constraint->check($value, $input)) {
                    $invalid[$key][] = $constraint;
                }
            } elseif ($constraint instanceof CheckableInterface) {
                $result = $constraint->check($value);

                $missing = Std::concat(
                    $missing,
                    array_map(
                        function ($subKey) use ($key) {
                            return vsprintf('%s.%s', [$key, $subKey]);
                        },
                        $result->getMissing()
                    )
                );

                foreach ($result->getFailed() as $failedField => $constraints) {
                    $fullPath = vsprintf('%s.%s', [$key, $failedField]);

                    if (array_key_exists($fullPath, $invalid)) {
                        $invalid[$fullPath] = array_merge(
                            $invalid[$fullPath],
                            $constraints
                        );
                    } else {
                        $invalid[$fullPath] = $constraints;
                    }
                }
            } else {
                throw new CoreException(
                    vsprintf(
                        'Unexpected constraint type: %s.',
                        [
                            TypeHound::fetch($constraint),
                        ]
                    )
                );
            }
        };

        $inputMap = ArrayMap::of($input);

        $this->annotations->each(
            function ($value, $key) use (
                $check,
                $input,
                $inputMap,
                &$missing
            ) {
                // If a field is required but not present, we should report it.
                if (Maybe::fromMaybe(
                        false,
                        $value->lookup(static::ANNOTATION_REQUIRED)
                    )
                    && $inputMap->member($key) === false
                ) {
                    $missing[] = $key;

                    // There's no point on checking constraints on the field
                    // since it is missing.
                    return;
                } elseif ($inputMap->member($key) === false) {
                    // There's no point on checking constraints on the field
                    // since it is missing.
                    return;
                }

                $fieldValue = Maybe::fromJust($inputMap->lookup($key));

                $this
                    ->getInternalFieldConstraints($key)
                    ->each(
                        function ($constraint) use (
                            $check,
                            $key,
                            $fieldValue,
                            $input
                        ) {
                            $check($constraint, $key, $fieldValue, $input);
                        }
                    );
            }
        );

        if (count($missing) === 0 && count($invalid) === 0) {
            return new SpecResult($missing, $invalid, SpecResult::STATUS_PASS);
        }

        return new SpecResult($missing, $invalid, SpecResult::STATUS_FAIL);
    }
764606
public function setPHPThrowable($throwable)
    {
        if (!$throwable instanceof Throwable && !$throwable instanceof Exception) {
            throw new InvalidArgumentException('The throwable must implement Throwable or extend Exception.');
        }

        $this->setName(get_class($throwable))
             ->setMessage($throwable->getMessage())
             ->setStacktrace(Stacktrace::fromBacktrace($this->config, $throwable->getTrace(), $throwable->getFile(), $throwable->getLine()));

        if (method_exists($throwable, 'getPrevious')) {
            $this->setPrevious($throwable->getPrevious());
        }

        return $this;
    }
611178
public function exceptionHandler($throwable)
    {
        $report = Report::fromPHPThrowable(
            $this->client->getConfig(),
            $throwable
        );

        $report->setSeverity('error');
        $report->setUnhandled(true);
        $report->setSeverityReason([
            'type' => 'unhandledException',
        ]);

        $this->client->notify($report);

        if ($this->previousExceptionHandler) {
            call_user_func(
                $this->previousExceptionHandler,
                $throwable
            );
        }
    }
465557
private function handleHTTP()
    {
    	try
    	{
			$method = new ReflectionMethod($this->classname, $_REQUEST["svc"]);
    	}
    	catch (Exception $ex)
    	{
    		echo '{ error: "Method does not exists" }';
    		exit;
    	}
		if (!$method->isPublic())
		{
    		echo '{ error: "Method is not public" }';
			exit;
		}

		$params = $method->getParameters();
		$paramValues = array();
		$missingParams = array();
		foreach ($params as $param)
		{
			$paramName = $param->getName();
			$paramValue = ( isset($_REQUEST[$paramName]) ? $_REQUEST[$paramName] : null);
			if (is_null($paramValue) && $param->isDefaultValueAvailable())
			{
				$paramValue = $param->getDefaultValue();
			}
			if (is_null($paramValue))
			{
				$missingParams[] = $paramName;
			}
			else
			{
				$paramValues[$paramName] = $paramValue;
			}
		}
		if (count($missingParams) > 0)
		{
			echo '{ error: "Missing params", parameters: [ "' . implode('","', $missingParams) . '"] }';
		}
		else
		{
			try
			{
				$result = $method->invokeArgs($this, $paramValues);
				if (is_array($result))
				{
					echo json_encode($result);
				}
				elseif (is_object($result))
				{
					echo '{ error: "Return type is not supported" } ';
				}
				else
				{
					echo $result;
				}
			}
			catch (Exception $ex)
			{
				echo '{ error: "' . $ex->getMessage() . '" }';
			}
		}
    }
1158021
protected function validate()
    {
        if ($this->method === HttpMethods::POST && empty($this->data)) {
            throw new Exceptions\WebException(
                "Using method POST without data."
            );
        }
    }
1317985
public function execute() {
        $ch = \curl_init();

        $this->setAuth($ch);
        try {
            switch (strtoupper($this->method)) {
                case 'GET':
                    $this->executeGet($ch);
                    break;
                case 'POST':
                    $this->executePost($ch);
                    break;
                case 'PUT':
                    $this->executePut($ch);
                    break;
                case 'PATCH':
                    $this->executePatch($ch);
                    break;
                case 'DELETE':
                    $this->executeDelete($ch);
                    break;
                // This custom case is used to execute a Multipart PUT request
                case 'PUT_MP':
                    $this->method = 'PUT';
                    $this->executePutMultipart($ch);
                    break;
                case 'POST_MP':
                    $this->method = 'POST';
                    $this->executePostMultipart($ch);
                    break;
                default:
                    throw new \InvalidArgumentException('Current method (' . $this->method . ') is an invalid REST method.');
            }
        } catch (\InvalidArgumentException $e) {
            \curl_close($ch);
            throw $e;
        } catch (\Exception $e) {
            \curl_close($ch);
            throw $e;
        }
    }
931581
public function handler(Throwable $exception): void
	{
		try
		{
			// Empty output buffers

			$this->clearOutputBuffers();

			// Loop through the exception handlers

			foreach($this->handlers as $handler)
			{
				if($exception instanceof $handler['exceptionType'])
				{
					if($this->handleException($handler['handler'], $exception) !== null)
					{
						break;
					}
				}
			}

			// Log exception

			if($this->shouldExceptionBeLogged($exception))
			{
				$this->getLogger()->error($exception->getMessage(), ['exception' => $exception]);
			}
		}
		catch(Throwable $e)
		{
			// Empty output buffers

			$this->clearOutputBuffers();

			// One of the exception handlers failed so we'll just show the user a generic error screen

			echo $e->getMessage() . ' on line [ ' . $e->getLine() . ' ] in [ ' . $e->getFile() . ' ]' . PHP_EOL;
		}

		exit(1);
	}
1112217
private function setUnsupportedMethodsCollections()
    {
        /**
         * PHP doesn't pass in data from PUT/PATCH/DELETE requests through globals.
         * In the case that we faked the method via a "_method" input, we need to use
         * the original method's collection.  Otherwise, we have to manually read from
         * the input stream to grab their data.  If the content is not from a form, we
         * don't bother and just let users look the data up in the raw body.
         */
        if (
            (mb_strpos($this->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') === 0
                || mb_strpos($this->headers->get('CONTENT_TYPE'), 'multipart/form-data') === 0) &&
            in_array($this->method, [RequestMethods::PUT, RequestMethods::PATCH, RequestMethods::DELETE])
        ) {
            if ($this->originalMethodCollection === null) {
                parse_str($this->getRawBody(), $collection);
            } else {
                $collection = $this->originalMethodCollection->getAll();
            }

            switch ($this->method) {
                case RequestMethods::PUT:
                    $this->put->exchangeArray($collection);
                    break;
                case RequestMethods::PATCH:
                    $this->patch->exchangeArray($collection);
                    break;
                case RequestMethods::DELETE:
                    $this->delete->exchangeArray($collection);
                    break;
            }
        }
    }