public function setAllowedCrossDomainUrls(Request $request, array $urls) { $origin = null; if (count($urls) > 1) { // we can only set one allowed origin URL // if many are given, we need to find the current one $requestOrigin = $request->header('Origin'); if ($requestOrigin) { // the docs say this will not have any path info, but we don't trust those bastards if (substr($requestOrigin, -1) != '/') { $requestOrigin .= '/'; } foreach ($urls as $allowedOrigin) { $allowedOriginWithSlash = $allowedOrigin; if (substr($allowedOriginWithSlash, -1) != '/') { $allowedOriginWithSlash .= '/'; } if (strpos($requestOrigin, $allowedOriginWithSlash) === 0) { $origin = $allowedOrigin; break; } } } } if (!$origin) { // only one URL given, or none matches the request // fallback to first allowed origin $origin = reset($urls); } $this->addHeader('Access-Control-Allow-Credentials: true'); $this->addHeader('Access-Control-Allow-Origin: ' . $origin); return $this; }
<?php use Bravicility\Failure\FailureHandler; use Bravicility\Http\Request; use Bravicility\Http\Response\Response; use Bravicility\Http\Response\TextResponse; use Bravicility\Router\RouteNotFoundException; require_once __DIR__ . '/../vendor/autoload.php'; $container = new Container(); $logger = $container->getErrorLogger(); FailureHandler::setup(function ($error) use($logger) { (new TextResponse(500, 'Произошла ошибка сервера'))->send(); $logger->error($error['message'], $error); exit; }); try { $request = Request::createFromGlobals(); $route = $container->getRouter()->route($request->getMethod(), $request->getUrlPath()); $request->setOptions($route->vars); /** @var Response $response */ $response = (new $route->class($container))->{$route->method}($request); } catch (RouteNotFoundException $e) { $response = new Response(404); } catch (BadRequestException $e) { $response = new Response(400, $e->getMessage()); } $response->addHeader('Access-Control-Allow-Origin: *'); $response->send();
private function makeResponse(Request $request, array $values, $status = 200) { $format = $request->option('format', 'json'); switch ($format) { case 'json': $response = new JsonResponse($status, $values); break; case 'jsonp': $callback = $request->get('callback'); if (!$callback) { return new Response(400, 'Отсутствует обязательный параметр: callback.'); } $response = new JsonpResponse($values, $callback); break; default: throw new RouteNotFoundException(); } return $response; }