protected function process($data) { if ('json' == $this->type) { return $this->responseFactory->json($data, $this->code); } throw new \Exception('no processer for api maker'); }
/** * Generic response. * * @api * @param array|null $payload * @return \Illuminate\Contracts\Http\Response */ public function respond($payload) { if ($meta = $this->getMeta()) { $payload = array_merge($payload, ['meta' => $meta]); } return !($callback = $this->request->input('callback')) ? $this->response->json($payload, $this->getStatusCode(), $this->getHeaders()) : $this->response->jsonp($callback, $payload, $this->getStatusCode(), $this->getHeaders()); }
/** * Serialize the data and wrap it in a JSON response object. * * @param int|null $statusCode * @param array $headers * @return \Illuminate\Http\JsonResponse */ public function respond(int $statusCode = null, array $headers = []) : JsonResponse { if (!is_null($statusCode)) { $this->setStatus($statusCode); } $data = $this->includeStatusCode($this->toArray()); return $this->responseFactory->json($data, $this->statusCode, $headers); }
/** * Generic response. * * @api * @param array|null $payload * @return \Illuminate\Contracts\Http\Response */ public function respond($payload = []) { if ($meta = $this->getMeta()) { $payload = array_merge($payload, ['meta' => $meta]); } $statusCode = config('api.suppress_response_code') === true ? StatusCode::OK : $this->getStatusCode(); return !($callback = $this->request->input('callback')) ? $this->response->json($payload, $statusCode, $this->getHeaders(), JSON_PRETTY_PRINT) : $this->response->jsonp($callback, $payload, $statusCode, $this->getHeaders()); }
/** * Bootstrap the application services. * * @param ResponseFactory $factory */ public function boot(ResponseFactory $factory) { $factory->macro('error', function ($code, $msg) use($factory) { return $factory->json(array('success' => false, 'code' => $code, 'msg' => $msg)); }); $factory->macro('success', function ($data = null) use($factory) { if ($data === null) { return $factory->json(array('success' => true)); } return $factory->json(array('success' => true, 'data' => $data)); }); }
/** * Create a response instance from the given parameters. * * @param mixed $data * @param int $status * @param BaseTransformer $transformer * @return mixed */ public function create($data = [], $status = null, $transformer = null) { $this->setContent($data); if (!isset($data)) { $this->setContent('')->setStatusCode(HttpResponse::HTTP_NO_CONTENT); } elseif ($data instanceof LengthAwarePaginator) { $this->setContent($this->handlePagination($data, $transformer)); } elseif ($data instanceof Collection) { $this->setContent($this->handleCollection($data, $transformer)); } elseif ($data instanceof Model) { $this->setContent($this->handleItem($data, $transformer)); } elseif ($data instanceof ResourceException || get_parent_class($data) == ResourceException::class) { $this->setContent($this->handleError($data, $transformer, ResourceException::class))->setStatusCode($data->getStatusCode()); } elseif ($data instanceof HttpException || get_parent_class($data) == HttpException::class) { $this->setContent($this->handleError($data, $transformer, HttpException::class))->setStatusCode($data->getStatusCode()); } elseif ($data instanceof ValidationException || get_parent_class($data) == ValidationException::class) { // Create new ResourceException with the given errors if it is a ValidationException $resourceException = new ResourceException($data->getMessage(), $data->validator->errors()); $this->setContent($this->handleError($resourceException, $transformer))->setStatusCode($resourceException->getStatusCode()); } elseif ($data instanceof Exception || get_parent_class($data) == Exception::class) { $this->setContent($this->handleError($data, $transformer, Exception::class))->setStatusCode(HttpResponse::HTTP_INTERNAL_SERVER_ERROR); } elseif ($data instanceof FatalErrorException) { $this->setContent($this->handleError($data, $transformer, Exception::class))->setStatusCode(HttpResponse::HTTP_INTERNAL_SERVER_ERROR); } // Override status code if (isset($status)) { $this->setStatusCode($status); } return $this->response->json($this->getContent(), $this->getStatusCode()); }
/** * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ protected function unauthenticated($request, AuthenticationException $exception) { if ($request->expectsJson()) { return $this->response->json(['error' => 'Unauthenticated.'], 401); } return $this->redirector->guest('login'); }
/** * Handle an incoming request. * * @return null * @throws Exception * @throws HttpResponseException */ public function validate() { if (!$this->isThisValid()) { $errorList = null; switch ($this->errorFormat) { case self::ERROR_FORMAT_RULES: $errorList = $this->getFailedRules(); break; case self::ERROR_FORMAT_MESSAGES: $errorList = $this->getMessageBag()->all(); break; default: throw new Exception("Unknown error format: {$this->errorFormat}"); } $result = $this->makeResponse($errorList); throw new HttpResponseException($this->responseFactory->json($result, $this->errorResponseStatus)); } return null; }
public function act(Request $request, ResponseFactory $response, $number = 5) { $status = 200; try { $cages = $this->cageRepo->getRandomCageImages($number); $data = ['cages' => $cages]; } catch (\InvalidArgumentException $e) { $status = 400; $data = ['error' => $e->getMessage()]; } return $response->json($data, $status); }
/** * rpc response. * * @param \Recca0120\Terminal\Kernel $kernel * @param \Illuminate\Http\Request $request * @param \Illuminate\Contracts\Response\Factory $responseFactory * * @return mixed */ public function endpoint(Kernel $kernel, Request $request, ResponseFactory $responseFactory) { if ($request->hasSession() === true) { $session = $request->session(); if ($session->isStarted() === true) { $session->save(); } } $command = $request->get('command'); $status = $kernel->call($command); return $responseFactory->json(['jsonrpc' => $request->get('jsonrpc'), 'id' => $request->get('id'), 'result' => $kernel->output(), 'error' => $status]); }
/** * Create Screenshot. * * @return Illuminate\Http\Response */ public function createScreenshot(Request $request) { $url = $request->get('url', 'http://screeenly.com'); $user = $this->user->getUserByKey($request->get('key')); // Validate Input $validator = $this->app->make('Screeenly\\Screenshot\\ScreenshotValidator'); $validator->validate($request->all()); // Check if Host is available $checkHost = $this->app->make('Screeenly\\Services\\CheckHostService'); $checkHost->ping($url); // Actually Capture the Screenshot $screenshot = $this->app->make('Screeenly\\Screenshot\\Screenshot'); $filename = $screenshot->generateFilename(); $screenshot->setStoragePath($filename); $screenshot->setHeight($request->get('height')); $screenshot->setWidth($request->get('width', 1024)); $screenshot->capture($url); $log = $this->log->store($screenshot, $user); $this->setRateLimitHeader($request); $result = ['path' => $screenshot->assetPath, 'base64' => 'data:image/jpg;base64,' . $screenshot->bas64, 'base64_raw' => $screenshot->bas64]; return $this->response->json($result, 201, $this->header); }
/** * Handle the file upload. * * @param DiskRepositoryInterface $disks * @param ResponseFactory $response * @param MountManager $manager * @param Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function handle(DiskRepositoryInterface $disks, ResponseFactory $response, MountManager $manager, Request $request) { $path = trim($request->get('path'), '.'); $file = $request->file('upload'); $disk = $request->get('disk'); if (is_numeric($disk)) { $disk = $disks->find($disk); } elseif (is_string($disk)) { $disk = $disks->findBySlug($disk); } $file = $manager->putStream($disk->path(ltrim(trim($path, '/') . '/' . $file->getClientOriginalName(), '/')), fopen($file->getRealPath(), 'r+')); /* @var FileInterface $file */ return $response->json($file->getAttributes()); }
/** * 以客户端需求自动转换响应格式 * * @param array $data * @param string $message * @param int $code * @param null|string $format * * @return Response */ public function make($data = array(), $message = '', $code = 0, $format = null) { !empty($data) && $this->setData($data); !empty($message) && $this->setMessage($message); $code && $this->setCode($code); !empty($format) && $this->setFormat($format); switch ($this->getFormat() ?: $this->request->format()) { case 'xml': return $this->response->make($this->toXML())->header('Content-Type', 'application/xml'); break; case 'html': return $this->response->make($this->getMessage()); break; case 'jsonp': $this->response->setCallback($this->getCallback()); case 'json': default: return $this->response->json($this->toArray()); break; } }
public function getUpdateItem() { $inputs = $this->request->only('action', 'info'); $rules = ['action' => ['required', 'in:update,delete'], 'info' => ['array']]; $validator = $this->validator->make($inputs, $rules); $response = []; if ($validator->fails()) { $response['success'] = 0; return $this->response->json($response); } extract($inputs); if ($inputs['action'] == "delete") { $this->db->table('menus_item')->delete($inputs['info']['id']); } elseif ($inputs['action'] == "update") { $id = $inputs['info']['id']; unset($inputs['info']['id']); $this->db->table('menus_item')->where('id', $id)->update($inputs['info']); } $response['success'] = 1; return $this->response->json($response); }
/** * Render response with format. * * @param string $format * @return mixed */ public function render($format = null, $callback = null) { $format = $format ?: $this->format; $returned = $this->returned; // Change error code number. if ($this->code and isset($returned['response']['code'])) { $returned['response']['code'] = $this->code; } switch ($format) { case 'xml': if (isset($returned['response']['data'])) { $returned['response']['entries'] = $returned['response']['data']; unset($returned['response']['data']); } $data = array('type' => 'application/xml', 'content' => $this->converter->factory($returned['response'])->toXML()); break; case 'php': $data = array('type' => 'text/plain', 'content' => $this->converter->factory($returned['response'])->toPHP()); break; case 'serialized': $data = array('type' => 'text/plain', 'content' => $this->converter->factory($returned['response'])->toSerialized()); break; // In case JSON we don't need to convert anything. // In case JSON we don't need to convert anything. case 'json': default: $response = $this->response->json($returned['response'], $returned['header']); // Support JSONP Response. if ($callback) { $response = $response->setCallback($callback); } return $response; break; } // Making response. $response = $this->response->make($data['content'], $returned['header']); //$response = response() $response->header('Content-Type', $data['type']); return $response; }
/** * @param array $data * @param int $status * @param array $headers * @param int $options * * @return \Illuminate\Http\JsonResponse */ public function json(array $data = [], int $status = 200, array $headers = [], int $options = 0) { return $this->responseFactory->json($data, $status, $headers, $options); }
/** * Bootstrap the application services. * * @return void */ public function boot(ResponseFactory $factory) { $factory->macro('api', function ($httpStatus, $outcome, $error, $body) use($factory) { return $factory->json(['header' => ['success' => $outcome, 'msg' => $error], 'body' => [$body]], $httpStatus); }); }
/** * @param WebsiteRepositoryContract $website * @param ResponseFactory $response * * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function ajax(WebsiteRepositoryContract $website, ResponseFactory $response) { return $response->json($website->ajaxQuery('identifier')); }
/** * Perform post-registration booting of services. * * @param ResponseFactory $response * @return void */ public function boot(ResponseFactory $response) { $response->macro('crossDomainJson', function ($value) use($response) { return $response->json($value)->header('Access-Control-Allow-Origin', '*'); }); }
/** * Fire event and return the response * * @param string $event * @param string $error * @param integer $status * @param array $payload * @return mixed */ protected function respond($event, $error, $status, $payload = []) { $response = $this->events->fire($event, $payload, true); return $response ?: $this->response->json(['error' => $error], $status); }
/** * Loads tenants for select2 fields and such. * * @param TenantRepositoryContract $tenant * @param ResponseFactory $response * * @return \Illuminate\Http\JsonResponse */ public function ajax(TenantRepositoryContract $tenant, ResponseFactory $response) { return $response->json($tenant->ajaxQuery('name')); }
/** * @param Request $request * @param Response $response * @return Object * */ public function userProgress(Request $request, Response $response) { if ($request->ajax()) { $id = $request->get('id'); $query = Progress::select(['name', 'alias'])->where('id', '=', $id)->get(); $param = 'progress'; return $response->json([$query, $param]); } }
public function act(ResponseFactory $response) { $cageCount = $this->cageRepo->getCageImageCount(); $data = ['cage_count' => $cageCount]; return $response->json($data); }
/** * @param ResponseFactory $response * * @return \Illuminate\Http\JsonResponse */ public function act(ResponseFactory $response) { $randomCage = $this->cageRepo->getRandomCageImage(); $data = ['cage' => $randomCage]; return $response->json($data); }
/** * @param \Larapie\Contracts\TransformableContract|\Illuminate\Support\Collection|array|null $content * @param int $status * * @return \Illuminate\Http\JsonResponse */ public function respond($content, $status = 200) { $transformed = $this->transform($content); return $this->responseFactory->json($transformed, $status); }
/** * Send API message. * * @param array $message * @param int $status * * @return Symfony\Component\HttpFoundation\JsonResponse; */ public function message(array $message, $status = 200) { return $this->response->json($message, $status); }
protected function jsonResponse($data = [], $status = 200) { return $this->responseFactory->json($data, $status); }
/** * @param ResponseFactory $response * * @return \Illuminate\Http\JsonResponse */ public function act(ResponseFactory $response) { $cageIpsum = $this->cageRepo->getCageIpsum(); $data = ['cage_ipsum' => $cageIpsum]; return $response->json($data); }