ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
Slim\App Class Reference
+ Inheritance diagram for Slim\App:
+ Collaboration diagram for Slim\App:

Public Member Functions

 __construct ($container=[])
 Create new application. More...
 
 getContainer ()
 Enable access to the DI container by consumers of $app. More...
 
 add ($callable)
 Add middleware. More...
 
 __call ($method, $args)
 Calling a non-existant method on App checks to see if there's an item in the container that is callable and if so, calls it. More...
 
 get ($pattern, $callable)
 Add GET route. More...
 
 post ($pattern, $callable)
 Add POST route. More...
 
 put ($pattern, $callable)
 Add PUT route. More...
 
 patch ($pattern, $callable)
 Add PATCH route. More...
 
 delete ($pattern, $callable)
 Add DELETE route. More...
 
 options ($pattern, $callable)
 Add OPTIONS route. More...
 
 any ($pattern, $callable)
 Add route for any HTTP method. More...
 
 map (array $methods, $pattern, $callable)
 Add route with multiple methods. More...
 
 redirect ($from, $to, $status=302)
 Add a route that sends an HTTP redirect. More...
 
 run ($silent=false)
 Run application. More...
 
 process (ServerRequestInterface $request, ResponseInterface $response)
 Process a request. More...
 
 respond (ResponseInterface $response)
 Send the response to the client. More...
 
 subRequest ( $method, $path, $query='', array $headers=[], array $cookies=[], $bodyContent='', ResponseInterface $response=null)
 Perform a sub-request from within an application route. More...
 

Data Fields

const VERSION = '3.11.0'
 

Protected Member Functions

 processInvalidMethod (ServerRequestInterface $request, ResponseInterface $response)
 Pull route info for a request with a bad method to decide whether to return a not-found error (default) or a bad-method error, then run the handler for that error, returning the resulting response. More...
 
 dispatchRouterAndPrepareRoute (ServerRequestInterface $request, RouterInterface $router)
 Dispatch the router to find the route. More...
 
 finalize (ResponseInterface $response)
 Finalize response. More...
 
 isEmptyResponse (ResponseInterface $response)
 Helper method, which returns true if the provided response must not output a body and false if the response could have a body. More...
 
 handleException (Exception $e, ServerRequestInterface $request, ResponseInterface $response)
 Call relevant handler from the Container if needed. More...
 
 handlePhpError (Throwable $e, ServerRequestInterface $request, ResponseInterface $response)
 Call relevant handler from the Container if needed. More...
 

Private Attributes

 $container
 

Detailed Description

Definition at line 46 of file App.php.

Constructor & Destructor Documentation

◆ __construct()

Slim\App::__construct (   $container = [])

Create new application.

Parameters
ContainerInterface | array$containerEither a ContainerInterface or an associative array of app settings
Exceptions
InvalidArgumentExceptionwhen no container is provided that implements ContainerInterface

Definition at line 74 of file App.php.

References $container.

75  {
76  if (is_array($container)) {
77  $container = new Container($container);
78  }
79  if (!$container instanceof ContainerInterface) {
80  throw new InvalidArgumentException('Expected a ContainerInterface');
81  }
82  $this->container = $container;
83  }
$container
Definition: App.php:62

Member Function Documentation

◆ __call()

Slim\App::__call (   $method,
  $args 
)

Calling a non-existant method on App checks to see if there's an item in the container that is callable and if so, calls it.

Parameters
string$method
array$args
Returns
mixed

Definition at line 117 of file App.php.

118  {
119  if ($this->container->has($method)) {
120  $obj = $this->container->get($method);
121  if (is_callable($obj)) {
122  return call_user_func_array($obj, $args);
123  }
124  }
125 
126  throw new \BadMethodCallException("Method $method is not a valid method");
127  }

◆ add()

Slim\App::add (   $callable)

Add middleware.

This method prepends new middleware to the app's middleware stack.

Parameters
callable | string$callableThe callback routine
Returns
static

Definition at line 104 of file App.php.

References Slim\addMiddleware().

105  {
106  return $this->addMiddleware(new DeferredCallable($callable, $this->container));
107  }
addMiddleware(callable $callable)
Add middleware.
+ Here is the call graph for this function:

◆ any()

Slim\App::any (   $pattern,
  $callable 
)

Add route for any HTTP method.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 219 of file App.php.

220  {
221  return $this->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, $callable);
222  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ delete()

Slim\App::delete (   $pattern,
  $callable 
)

Add DELETE route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 193 of file App.php.

194  {
195  return $this->map(['DELETE'], $pattern, $callable);
196  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ dispatchRouterAndPrepareRoute()

Slim\App::dispatchRouterAndPrepareRoute ( ServerRequestInterface  $request,
RouterInterface  $router 
)
protected

Dispatch the router to find the route.

Prepare the route for use.

Parameters
ServerRequestInterface$request
RouterInterface$router
Returns
ServerRequestInterface

Definition at line 583 of file App.php.

References Slim\Interfaces\RouterInterface\dispatch(), Psr\Http\Message\RequestInterface\getMethod(), Psr\Http\Message\RequestInterface\getUri(), Slim\Interfaces\RouterInterface\lookupRoute(), string, and Psr\Http\Message\ServerRequestInterface\withAttribute().

584  {
585  $routeInfo = $router->dispatch($request);
586 
587  if ($routeInfo[0] === Dispatcher::FOUND) {
588  $routeArguments = [];
589  foreach ($routeInfo[2] as $k => $v) {
590  $routeArguments[$k] = urldecode($v);
591  }
592 
593  $route = $router->lookupRoute($routeInfo[1]);
594  $route->prepare($request, $routeArguments);
595 
596  // add route to the request's attributes in case a middleware or handler needs access to the route
597  $request = $request->withAttribute('route', $route);
598  }
599 
600  $routeInfo['request'] = [$request->getMethod(), (string) $request->getUri()];
601 
602  return $request->withAttribute('routeInfo', $routeInfo);
603  }
Add rich text string
+ Here is the call graph for this function:

◆ finalize()

Slim\App::finalize ( ResponseInterface  $response)
protected

Finalize response.

Parameters
ResponseInterface$response
Returns
ResponseInterface

Definition at line 611 of file App.php.

References $response, $size, Psr\Http\Message\MessageInterface\getBody(), Psr\Http\Message\MessageInterface\hasHeader(), Psr\Http\Message\MessageInterface\withHeader(), and Psr\Http\Message\MessageInterface\withoutHeader().

612  {
613  // stop PHP sending a Content-Type automatically
614  ini_set('default_mimetype', '');
615 
616  if ($this->isEmptyResponse($response)) {
617  return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
618  }
619 
620  // Add Content-Length header if `addContentLengthHeader` setting is set
621  if (isset($this->container->get('settings')['addContentLengthHeader']) &&
622  $this->container->get('settings')['addContentLengthHeader'] == true) {
623  if (ob_get_length() > 0) {
624  throw new \RuntimeException("Unexpected data in output buffer. " .
625  "Maybe you have characters before an opening <?php tag?");
626  }
627  $size = $response->getBody()->getSize();
628  if ($size !== null && !$response->hasHeader('Content-Length')) {
629  $response = $response->withHeader('Content-Length', (string) $size);
630  }
631  }
632 
633  return $response;
634  }
$size
Definition: RandomTest.php:84
isEmptyResponse(ResponseInterface $response)
Helper method, which returns true if the provided response must not output a body and false if the re...
Definition: App.php:645
$response
+ Here is the call graph for this function:

◆ get()

Slim\App::get (   $pattern,
  $callable 
)

Add GET route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 141 of file App.php.

142  {
143  return $this->map(['GET'], $pattern, $callable);
144  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ getContainer()

Slim\App::getContainer ( )

Enable access to the DI container by consumers of $app.

Returns
ContainerInterface

Definition at line 90 of file App.php.

References $container.

91  {
92  return $this->container;
93  }
$container
Definition: App.php:62

◆ handleException()

Slim\App::handleException ( Exception  $e,
ServerRequestInterface  $request,
ResponseInterface  $response 
)
protected

Call relevant handler from the Container if needed.

If it doesn't exist, then just re-throw.

Parameters
Exception$e
ServerRequestInterface$request
ResponseInterface$response
Returns
ResponseInterface
Exceptions
Exceptionif a handler is needed and not found

Definition at line 665 of file App.php.

References $handler, $params, and $response.

666  {
667  if ($e instanceof MethodNotAllowedException) {
668  $handler = 'notAllowedHandler';
669  $params = [$e->getRequest(), $e->getResponse(), $e->getAllowedMethods()];
670  } elseif ($e instanceof NotFoundException) {
671  $handler = 'notFoundHandler';
672  $params = [$e->getRequest(), $e->getResponse(), $e];
673  } elseif ($e instanceof SlimException) {
674  // This is a Stop exception and contains the response
675  return $e->getResponse();
676  } else {
677  // Other exception, use $request and $response params
678  $handler = 'errorHandler';
679  $params = [$request, $response, $e];
680  }
681 
682  if ($this->container->has($handler)) {
683  $callable = $this->container->get($handler);
684  // Call the registered handler
685  return call_user_func_array($callable, $params);
686  }
687 
688  // No handlers found, so just throw the exception
689  throw $e;
690  }
$params
Definition: disable.php:11
$response
$handler

◆ handlePhpError()

Slim\App::handlePhpError ( Throwable  $e,
ServerRequestInterface  $request,
ResponseInterface  $response 
)
protected

Call relevant handler from the Container if needed.

If it doesn't exist, then just re-throw.

Parameters
Throwable$e
ServerRequestInterface$request
ResponseInterface$response
Returns
ResponseInterface
Exceptions
Throwable

Definition at line 702 of file App.php.

References $handler, $params, and $response.

703  {
704  $handler = 'phpErrorHandler';
705  $params = [$request, $response, $e];
706 
707  if ($this->container->has($handler)) {
708  $callable = $this->container->get($handler);
709  // Call the registered handler
710  return call_user_func_array($callable, $params);
711  }
712 
713  // No handlers found, so just throw the exception
714  throw $e;
715  }
$params
Definition: disable.php:11
$response
$handler

◆ isEmptyResponse()

Slim\App::isEmptyResponse ( ResponseInterface  $response)
protected

Helper method, which returns true if the provided response must not output a body and false if the response could have a body.

See also
https://tools.ietf.org/html/rfc7231
Parameters
ResponseInterface$response
Returns
bool

Definition at line 645 of file App.php.

References Psr\Http\Message\ResponseInterface\getStatusCode().

646  {
647  if (method_exists($response, 'isEmpty')) {
648  return $response->isEmpty();
649  }
650 
651  return in_array($response->getStatusCode(), [204, 205, 304]);
652  }
$response
+ Here is the call graph for this function:

◆ map()

Slim\App::map ( array  $methods,
  $pattern,
  $callable 
)

Add route with multiple methods.

Parameters
string[]$methods Numeric array of HTTP method names
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns
RouteInterface

Definition at line 233 of file App.php.

234  {
235  if ($callable instanceof Closure) {
236  $callable = $callable->bindTo($this->container);
237  }
238 
239  $route = $this->container->get('router')->map($methods, $pattern, $callable);
240  if (is_callable([$route, 'setContainer'])) {
241  $route->setContainer($this->container);
242  }
243 
244  if (is_callable([$route, 'setOutputBuffering'])) {
245  $route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
246  }
247 
248  return $route;
249  }

◆ options()

Slim\App::options (   $pattern,
  $callable 
)

Add OPTIONS route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 206 of file App.php.

207  {
208  return $this->map(['OPTIONS'], $pattern, $callable);
209  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ patch()

Slim\App::patch (   $pattern,
  $callable 
)

Add PATCH route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 180 of file App.php.

181  {
182  return $this->map(['PATCH'], $pattern, $callable);
183  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ post()

Slim\App::post (   $pattern,
  $callable 
)

Add POST route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 154 of file App.php.

Referenced by ilRestServer\init().

155  {
156  return $this->map(['POST'], $pattern, $callable);
157  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233
+ Here is the caller graph for this function:

◆ process()

Slim\App::process ( ServerRequestInterface  $request,
ResponseInterface  $response 
)

Process a request.

This method traverses the application middleware stack and then returns the resultant Response object.

Parameters
ServerRequestInterface$request
ResponseInterface$response
Returns
ResponseInterface
Exceptions
Exception
MethodNotAllowedException
NotFoundException

Definition at line 390 of file App.php.

References $response, and Psr\Http\Message\RequestInterface\getUri().

391  {
392  // Ensure basePath is set
393  $router = $this->container->get('router');
394  if (is_callable([$request->getUri(), 'getBasePath']) && is_callable([$router, 'setBasePath'])) {
395  $router->setBasePath($request->getUri()->getBasePath());
396  }
397 
398  // Dispatch the Router first if the setting for this is on
399  if ($this->container->get('settings')['determineRouteBeforeAppMiddleware'] === true) {
400  // Dispatch router (note: you won't be able to alter routes after this)
401  $request = $this->dispatchRouterAndPrepareRoute($request, $router);
402  }
403 
404  // Traverse middleware stack
405  try {
406  $response = $this->callMiddlewareStack($request, $response);
407  } catch (Exception $e) {
408  $response = $this->handleException($e, $request, $response);
409  } catch (Throwable $e) {
410  $response = $this->handlePhpError($e, $request, $response);
411  }
412 
413  return $response;
414  }
handleException(Exception $e, ServerRequestInterface $request, ResponseInterface $response)
Call relevant handler from the Container if needed.
Definition: App.php:665
dispatchRouterAndPrepareRoute(ServerRequestInterface $request, RouterInterface $router)
Dispatch the router to find the route.
Definition: App.php:583
$response
handlePhpError(Throwable $e, ServerRequestInterface $request, ResponseInterface $response)
Call relevant handler from the Container if needed.
Definition: App.php:702
+ Here is the call graph for this function:

◆ processInvalidMethod()

Slim\App::processInvalidMethod ( ServerRequestInterface  $request,
ResponseInterface  $response 
)
protected

Pull route info for a request with a bad method to decide whether to return a not-found error (default) or a bad-method error, then run the handler for that error, returning the resulting response.

Used for cases where an incoming request has an unrecognized method, rather than throwing an exception and not catching it all the way up.

Parameters
ServerRequestInterface$request
ResponseInterface$response
Returns
ResponseInterface

Definition at line 355 of file App.php.

References Psr\Http\Message\ServerRequestInterface\getAttribute(), and Psr\Http\Message\RequestInterface\getUri().

356  {
357  $router = $this->container->get('router');
358  if (is_callable([$request->getUri(), 'getBasePath']) && is_callable([$router, 'setBasePath'])) {
359  $router->setBasePath($request->getUri()->getBasePath());
360  }
361 
362  $request = $this->dispatchRouterAndPrepareRoute($request, $router);
363  $routeInfo = $request->getAttribute('routeInfo', [RouterInterface::DISPATCH_STATUS => Dispatcher::NOT_FOUND]);
364 
366  return $this->handleException(
367  new MethodNotAllowedException($request, $response, $routeInfo[RouterInterface::ALLOWED_METHODS]),
368  $request,
369  $response
370  );
371  }
372 
373  return $this->handleException(new NotFoundException($request, $response), $request, $response);
374  }
handleException(Exception $e, ServerRequestInterface $request, ResponseInterface $response)
Call relevant handler from the Container if needed.
Definition: App.php:665
dispatchRouterAndPrepareRoute(ServerRequestInterface $request, RouterInterface $router)
Dispatch the router to find the route.
Definition: App.php:583
$response
+ Here is the call graph for this function:

◆ put()

Slim\App::put (   $pattern,
  $callable 
)

Add PUT route.

Parameters
string$patternThe route URI pattern
callable | string$callableThe route callback routine
Returns

Definition at line 167 of file App.php.

168  {
169  return $this->map(['PUT'], $pattern, $callable);
170  }
map(array $methods, $pattern, $callable)
Add route with multiple methods.
Definition: App.php:233

◆ redirect()

Slim\App::redirect (   $from,
  $to,
  $status = 302 
)

Add a route that sends an HTTP redirect.

Parameters
string$from
string | UriInterface$to
int$status
Returns
RouteInterface

Definition at line 260 of file App.php.

References $from, $handler, and $response.

261  {
262  $handler = function ($request, ResponseInterface $response) use ($to, $status) {
263  return $response->withHeader('Location', (string)$to)->withStatus($status);
264  };
265 
266  return $this->get($from, $handler);
267  }
$from
$response
$handler

◆ respond()

Slim\App::respond ( ResponseInterface  $response)

Send the response to the client.

Parameters
ResponseInterface$response

Definition at line 421 of file App.php.

References $contentLength, $data, $name, $response, Psr\Http\Message\ServerRequestInterface\getAttribute(), Psr\Http\Message\MessageInterface\getBody(), Psr\Http\Message\MessageInterface\getHeaderLine(), Psr\Http\Message\MessageInterface\getHeaders(), Psr\Http\Message\RequestInterface\getMethod(), Psr\Http\Message\MessageInterface\getProtocolVersion(), Psr\Http\Message\ResponseInterface\getReasonPhrase(), Psr\Http\Message\ResponseInterface\getStatusCode(), Psr\Http\Message\RequestInterface\getUri(), header, and string.

422  {
423  // Send response
424  if (!headers_sent()) {
425  // Headers
426  foreach ($response->getHeaders() as $name => $values) {
427  $first = stripos($name, 'Set-Cookie') === 0 ? false : true;
428  foreach ($values as $value) {
429  header(sprintf('%s: %s', $name, $value), $first);
430  $first = false;
431  }
432  }
433 
434  // Set the status _after_ the headers, because of PHP's "helpful" behavior with location headers.
435  // See https://github.com/slimphp/Slim/issues/1730
436 
437  // Status
438  header(sprintf(
439  'HTTP/%s %s %s',
440  $response->getProtocolVersion(),
441  $response->getStatusCode(),
442  $response->getReasonPhrase()
443  ), true, $response->getStatusCode());
444  }
445 
446  // Body
447  if (!$this->isEmptyResponse($response)) {
448  $body = $response->getBody();
449  if ($body->isSeekable()) {
450  $body->rewind();
451  }
452  $settings = $this->container->get('settings');
453  $chunkSize = $settings['responseChunkSize'];
454 
455  $contentLength = $response->getHeaderLine('Content-Length');
456  if (!$contentLength) {
457  $contentLength = $body->getSize();
458  }
459 
460 
461  if (isset($contentLength)) {
462  $amountToRead = $contentLength;
463  while ($amountToRead > 0 && !$body->eof()) {
464  $data = $body->read(min($chunkSize, $amountToRead));
465  echo $data;
466 
467  $amountToRead -= strlen($data);
468 
469  if (connection_status() != CONNECTION_NORMAL) {
470  break;
471  }
472  }
473  } else {
474  while (!$body->eof()) {
475  echo $body->read($chunkSize);
476  if (connection_status() != CONNECTION_NORMAL) {
477  break;
478  }
479  }
480  }
481  }
482  }
if($format !==null) $name
Definition: metadata.php:146
if(preg_match('#\.( $contentLength[^/\.]+)$#D', $path, $type)) if($contentType===null)
Definition: module.php:163
Add a drawing to the header
Definition: 04printing.php:69
isEmptyResponse(ResponseInterface $response)
Helper method, which returns true if the provided response must not output a body and false if the re...
Definition: App.php:645
$response
+ Here is the call graph for this function:

◆ run()

Slim\App::run (   $silent = false)

Run application.

This method traverses the application middleware stack and then sends the resultant Response object to the HTTP client.

Parameters
bool | false$silent
Returns
ResponseInterface
Exceptions
Exception
MethodNotAllowedException
NotFoundException

Definition at line 308 of file App.php.

References $output, $response, and Slim\Exception\InvalidMethodException\getRequest().

309  {
310  $response = $this->container->get('response');
311 
312  try {
313  ob_start();
314  $response = $this->process($this->container->get('request'), $response);
315  } catch (InvalidMethodException $e) {
316  $response = $this->processInvalidMethod($e->getRequest(), $response);
317  } finally {
318  $output = ob_get_clean();
319  }
320 
321  if (!empty($output) && $response->getBody()->isWritable()) {
322  $outputBuffering = $this->container->get('settings')['outputBuffering'];
323  if ($outputBuffering === 'prepend') {
324  // prepend output buffer content
325  $body = new Http\Body(fopen('php://temp', 'r+'));
326  $body->write($output . $response->getBody());
327  $response = $response->withBody($body);
328  } elseif ($outputBuffering === 'append') {
329  // append output buffer content
330  $response->getBody()->write($output);
331  }
332  }
333 
334  $response = $this->finalize($response);
335 
336  if (!$silent) {
337  $this->respond($response);
338  }
339 
340  return $response;
341  }
process(ServerRequestInterface $request, ResponseInterface $response)
Process a request.
Definition: App.php:390
if(!is_dir( $entity_dir)) exit("Fatal Error ([A-Za-z0-9]+)\+" &#(? foreach( $entity_files as $file) $output
finalize(ResponseInterface $response)
Finalize response.
Definition: App.php:611
respond(ResponseInterface $response)
Send the response to the client.
Definition: App.php:421
processInvalidMethod(ServerRequestInterface $request, ResponseInterface $response)
Pull route info for a request with a bad method to decide whether to return a not-found error (defaul...
Definition: App.php:355
$response
+ Here is the call graph for this function:

◆ subRequest()

Slim\App::subRequest (   $method,
  $path,
  $query = '',
array  $headers = [],
array  $cookies = [],
  $bodyContent = '',
ResponseInterface  $response = null 
)

Perform a sub-request from within an application route.

This method allows you to prepare and initiate a sub-request, run within the context of the current request. This WILL NOT issue a remote HTTP request. Instead, it will route the provided URL, method, headers, cookies, body, and server variables against the set of registered application routes. The result response object is returned.

Parameters
string$methodThe request method (e.g., GET, POST, PUT, etc.)
string$pathThe request URI path
string$queryThe request URI query string
array$headersThe request headers (key-value array)
array$cookiesThe request cookies (key-value array)
string$bodyContentThe request body
ResponseInterface$responseThe response object (optional)
Returns
ResponseInterface

Definition at line 551 of file App.php.

References $env, $path, and $query.

559  {
560  $env = $this->container->get('environment');
561  $uri = Uri::createFromEnvironment($env)->withPath($path)->withQuery($query);
562  $headers = new Headers($headers);
563  $serverParams = $env->all();
564  $body = new Body(fopen('php://temp', 'r+'));
565  $body->write($bodyContent);
566  $body->rewind();
567  $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
568 
569  if (!$response) {
570  $response = $this->container->get('response');
571  }
572 
573  return $this($request, $response);
574  }
static createFromEnvironment(Environment $env)
Create new Uri from environment.
Definition: Uri.php:166
$env
$query
$response

Field Documentation

◆ $container

Slim\App::$container
private

Definition at line 62 of file App.php.

Referenced by ilRestServer\__construct().

◆ VERSION

const Slim\App::VERSION = '3.11.0'

Definition at line 55 of file App.php.


The documentation for this class was generated from the following file: