Skip to content

Commit

Permalink
Response: Add native support for send safe response.
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek authored Apr 20, 2020
1 parent 7086574 commit bf95fa9
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/ApiManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use Nette\Caching\Cache;
use Nette\Caching\IStorage;
use Nette\DI\Container;
use Nette\Http\Request;
use Nette\Http\Response;
use Nette\Utils\Strings;
use Tracy\Debugger;

Expand All @@ -26,6 +28,12 @@ final class ApiManager
/** @var Container */
private $container;

/** @var Request */
private $request;

/** @var Response */
private $response;

/** @var Cache */
private $cache;

Expand All @@ -35,11 +43,15 @@ final class ApiManager

/**
* @param Container $container
* @param Request $request
* @param Response $response
* @param IStorage $storage
*/
public function __construct(Container $container, IStorage $storage)
public function __construct(Container $container, Request $request, Response $response, IStorage $storage)
{
$this->container = $container;
$this->request = $request;
$this->response = $response;
$this->cache = new Cache($storage, 'structured-api');
}

Expand Down Expand Up @@ -89,8 +101,13 @@ public function run(string $path, ?array $params = [], ?string $method = null, b
if ($throw === true) {
throw new ThrowResponse($response);
}
header('Content-Type: ' . $response->getContentType());
echo (string) $response;
if ($this->response->isSent() === false) {
$this->response->setContentType($response->getContentType(), 'UTF-8');
(new \Nette\Application\Responses\JsonResponse($response->toArray(), $response->getContentType()))
->send($this->request, $this->response);
} else {
throw new \RuntimeException('API: Response already was sent.');
}
die;
}

Expand Down

0 comments on commit bf95fa9

Please sign in to comment.