private function make_xml() { Response::macro('xml', function (array $vars, $status = 200, array $headers = [], $xml = null) { $xml_out = self::create_xml($xml, $vars); if (empty($headers)) { $headers = self::handle(); } return Response::make($xml_out->asXML(), $status, $headers); }); }
/** * Register the service provider. * * @return void */ public function register() { // Register response macro \Response::macro('api', function () { $manager = new Manager(); // If you have to customize the manager instance, like setting a custom serializer, // I strongly suggest you to create your own service provider and add you manager configuration action here // Here some example if you want to set a custom serializer : // $manager->setSerializer(\League\Fractal\Serializer\JsonApiSerializer); // Are we going to try and include embedded data? $manager->parseIncludes(explode(',', Input::get('include'))); // Return the Response object return new Response($manager); }); }
public function xml() { Response::macro('xml', function (array $vars, $status = 200, array $header = [], $xml = null) { if (is_null($xml)) { $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response/>'); } foreach ($vars as $key => $value) { if (is_array($value)) { Response::xml($value, $status, $header, $xml->addChild($key)); } else { $xml->addChild($key, $value); } } if (empty($header)) { $header['Content-Type'] = 'application/xml'; } return Response::make($xml->asXML(), $status, $header); }); }
| Provides the ability to supply both AJAX and regular redirects at | the same time. Will always generate relative Location headers, | and will default to "home" ("/") if no route was found. | IDs/params to pass to the URL can be passed in. | */ Response::macro('route', function ($url, $ids = array(), $params = null) { try { $url = URL::route($url, $ids, $absolute = false); } catch (Exception $e) { $url = URL::route("home", $absolute = false); } if ($params and is_array($params)) { $query = []; foreach ($params as $key => $value) { $query[] = $key . "=" . $value; } $url = $url . "?" . implode("&", $query); } if (Request::ajax() or Input::has("ajax")) { return Response::json(["url" => $url]); } else { return Redirect::to($url); } }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- | | The "down" Artisan command gives you the ability to put an application
*/ App::down(function () { return Response::make("Be right back!", 503); }); /* |-------------------------------------------------------------------------- | Require The Filters File |-------------------------------------------------------------------------- | | Next we will load the filters file for the application. This gives us | a nice separate location to store our route and application filter | definitions instead of putting them all in the main routes file. | */ require app_path() . '/filters.php'; /* * Custom response macros * */ Response::macro('jsonError', function ($message = "Error occured", $code = 500) { return Response::json(["status" => "error", "message" => $message], $code); }); Response::macro('jsonOk', function () { return Response::json(["status" => "ok"]); }); Response::macro('jsonModel', function ($model, $status = 200) { return Response::make($model->toJson(), $status, ['Content-Type' => 'application/json']); }); Response::macro('authHeader', function () { return Response::make("401 Unauthorized", 401)->header('WWW-Authenticate', 'Basic realm="API Authorization"'); });
Route::match(array('GET', 'POST'), 'admin/config/list', array('as' => 'adminConfigList', 'uses' => 'AdminConfigController@listConfig')); Route::match(array('GET', 'POST'), 'admin/config/email', array('as' => 'adminConfigEmail', 'uses' => 'AdminConfigController@emailConfig')); //Preview OG image Route::match(array('GET', 'POST'), 'admin/config/preview-og-image', array('as' => 'adminPreviewOgImage', 'uses' => 'AdminConfigController@previewOgImage')); //Change Password Route::match(array('GET', 'POST'), 'admin/change-password', array('as' => 'adminChangePassword', 'uses' => 'AdminController@changePassword')); //Users Route::controller('admin/users', 'AdminUsersController'); Route::match(array('GET', 'POST'), 'admin/users/', array('as' => 'adminUsersHome', 'uses' => 'AdminUsersController@index')); //Categories Route::match(array('GET', 'POST'), 'admin/categories', array('as' => 'adminCategories', 'uses' => 'AdminCategoriesController@view')); Route::match(array('GET', 'POST', 'PATCH', 'DELETE'), 'admin/categories/addEdit', array('as' => 'adminCategoriesAddEdit', 'uses' => 'AdminCategoriesController@addEdit')); //Update Route::get('admin/update', array('as' => 'update', 'uses' => 'UpdateController@index')); //Sitemap Route::controller('sitemap', 'AdminSitemapController'); }); //Media manager Route::group(array(), function () { \Route::get('media', 'W3G\\MediaManager\\MediaManagerController@showStandalone'); \Route::any('media/connector', array('as' => 'mediaConnector', 'uses' => 'W3G\\MediaManager\\MediaManagerController@connector')); }); //404 macro Response::macro('notFound', function ($value = null) { ListController::_loadLists(); return Response::view('errors.404', array('errorMsg' => strtoupper($value)), 404); }); App::missing(function ($exception) { ListController::_loadLists(); return Response::view('errors.404', array('errorMsg' => strtoupper($exception->getMessage())), 404); });
| The "down" Artisan command gives you the ability to put an application | into maintenance mode. Here, you will define what is displayed back | to the user if maintenance mode is in effect for the application. | */ App::down(function () { return Response::make("Be right back!", 503); }); /* |-------------------------------------------------------------------------- | Require The Filters File |-------------------------------------------------------------------------- | | Next we will load the filters file for the application. This gives us | a nice separate location to store our route and application filter | definitions instead of putting them all in the main routes file. | */ App::missing(function ($e) { $url = Request::fullUrl(); $userAgent = Request::header('user-agent'); Log::warning("404 for URL: {$url} requested by user agent: {$userAgent}"); return Response::view('errors.not-found', array(), 404); }); require app_path() . '/filters.php'; /* * 自訂alert response */ Response::macro('alert', function ($message, $status = 400) { App::abort(500, $message); });
/** * Register response macro * * @deprecated We still register macro for backward compatibility, but DO NOT USE THIS MACRO ANYMORE ! * @param $response */ private function registerMacro($response) { \Response::macro('api', function () use($response) { return $response; }); }
<?php Response::macro('xml', function (array $vars, $status = 200, array $header = [], $rootElement = 'response', $xml = null, $overrideRoot = null) { if (is_object($vars) && $vars instanceof \Illuminate\Contracts\Support\Arrayable) { $vars = $vars->toArray(); } $isRoot = is_null($xml); if ($isRoot) { $root = !empty($overrideRoot) ? $overrideRoot : $rootElement; $xml = new SimpleXMLElement('<' . $root . '/>'); } foreach ($vars as $key => $value) { if (is_array($value)) { if (is_numeric($key)) { Response::xml($value, $status, $header, $rootElement, $xml->addChild(str_singular($isRoot ? $rootElement : $xml->getName()))); } else { Response::xml($value, $status, $header, $rootElement, $xml->addChild($key)); } } else { $xml->addChild($key, htmlspecialchars($value)); } } if (empty($header)) { $header['Content-Type'] = 'application/xml'; } return Response::make($xml->asXML(), $status, $header); });
<?php HTML::macro('activeLinkRoute', function ($keysWithDefaults, $route, $title = null, $parameters = [], $attributes = [], $activeClass = 'is-active') { // This only works if we pass a single param. $key = key($parameters); if (Input::get($key) === $parameters[$key] || !Input::has($key) && $parameters[$key] === $keysWithDefaults[$key]) { $cssClass = isset($attributes['class']) ? $attributes['class'] : ''; $cssClass .= " {$activeClass}"; $attributes['class'] = $cssClass; } // There has to be a better way... $outputParameters = []; foreach ($keysWithDefaults as $key => $default) { if (array_key_exists($key, $parameters)) { $outputParameters[$key] = $parameters[$key]; } elseif (Input::has($key)) { $outputParameters[$key] = Input::get($key); } else { $outputParameters[$key] = $keysWithDefaults[$key]; } } return HTML::linkRoute($route, $title, $outputParameters, $attributes); }); Response::macro('jsonApi', function ($value) { $response = Response::json($value); $response->headers->set('Content-Type', 'application/vnd.api+json'); return $response; });
| Provides the ability to supply both AJAX and regular redirects at | the same time. Will always generate relative Location headers, | and will default to "home" ("/") if no route was found. | IDs/params to pass to the URL can be passed in. | */ Response::macro('route', function ($url, $ids = [], $params = null) { try { $url = URL::route($url, $ids, $absolute = false); } catch (Exception $e) { $url = URL::route('home', $absolute = false); } if ($params and is_array($params)) { $query = []; foreach ($params as $key => $value) { $query[] = $key . '=' . $value; } $url = $url . '?' . implode('&', $query); } if (Request::ajax() or Input::has('ajax')) { return Response::json(['url' => $url]); } else { return Redirect::to($url); } }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- | | The "down" Artisan command gives you the ability to put an application
* Mapa com os erros suportados. */ $statusMessagesMap = [200 => ['status' => 'success', 'message' => 'Ok'], 201 => ['status' => 'success', 'message' => 'New resource has been created.'], 204 => ['status' => 'success', 'message' => 'The resource was successfully deleted.'], 400 => ['status' => 'error', 'message' => 'Bad Request: The request was invalid or cannot be served.'], 401 => ['status' => 'error', 'message' => 'Unauthorized: The request requires an user authentication.'], 403 => ['status' => 'error', 'message' => 'Forbidden: access is not allowed.'], 404 => ['status' => 'error', 'message' => 'Not found: There is no resource behind the URI.'], 422 => ['status' => 'error', 'message' => 'Unprocessable Entity: Could not process due to validation errors.']]; $defaultOptions = ['data' => [], 'httpCode' => 200, 'message' => '', 'errors' => []]; Response::macro('apiResponse', function ($options) use($statusMessagesMap, $defaultOptions) { $options = array_merge($defaultOptions, $options); $status = $statusMessagesMap[$options['httpCode']]['status']; $message = $options['message'] ? $options['message'] : $statusMessagesMap[$options['httpCode']]['message']; $response = ['status' => $status, 'data' => $options['data'], 'message' => $message]; /** * Se foi recebido como parâmetro 'erros', adicionamos a chave erros a resposta. * Isto é útil no caso de múltiplos erros para uma ação, ex.: erros de validação. */ if ($options['errors']) { $response['errors'] = $options['errors']; } /** * Caso o parâmetro data seja resultado de uma paginação, aqui nós padronizamos o resultado. */ if (is_object($options['data']) && is_subclass_of($options['data'], 'Illuminate\\Contracts\\Pagination\\Paginator')) { $results = $options['data']->toArray()['data']; $response = ['status' => $status, 'data' => $results, 'paging' => ['total' => $options['data']->total(), 'perPage' => $options['data']->perPage(), 'currentPage' => $options['data']->currentPage(), 'lastPage' => $options['data']->lastPage(), 'from' => $options['data']->firstItem(), 'to' => $options['data']->lastItem(), 'previous' => $options['data']->previousPageUrl(), 'next' => $options['data']->nextPageUrl()], 'message' => $message]; } /** * Se for uma resposta de erro, não é necessário retornamos a chave 'data' */ if ($status == 'error' || empty($options['data'])) { unset($response['data']); } return Response::json($response, $options['httpCode']); });
*/ Route::get('/', function () { return view('welcome'); }); Response::macro('xml', function ($vars, $status = 200, array $header = array(), $rootElement = 'response', $xml = null) { if (is_object($vars) && $vars instanceof Illuminate\Support\Contracts\ArrayableInterface) { $vars = $vars->toArray(); } if (is_null($xml)) { $xml = new SimpleXMLElement('<' . $rootElement . '/>'); } foreach ($vars as $key => $value) { if (is_array($value)) { if (is_numeric($key)) { Response::xml($value, $status, $header, $rootElement, $xml->addChild(str_singular($xml->getName()))); } else { Response::xml($value, $status, $header, $rootElement, $xml->addChild($key)); } } else { $xml->addChild($key, $value); } } if (empty($header)) { $header['Content-Type'] = 'application/xml'; } return Response::make($xml->asXML(), $status, $header); }); // How to use // routes.php Route::get('api.{ext}', function () { $data = ['status' => 'OK'];
/** * Registers a macro * * @param $name * @param callable $macro */ public function macro($name, callable $macro) { return \Response::macro($name, $macro); }
<?php Response::macro('plain', function ($value, $status = 200, array $headers = []) { return Response::make($value, $status, array_merge(['Content-Type' => 'text/plain'], $headers)); });
}); App::missing(function ($exception) { QuizController::_loadQuizes(); return Response::view('errors.404', array('errorMsg' => strtoupper($exception->getMessage())), 404); }); Response::macro('error', function ($message, $title = null, $errorCode = 500) { if (Request::ajax()) { return Response::make($message, $errorCode); } else { return Response::view('errors.error', array('title' => $title, 'message' => $message), $errorCode); } }); Response::macro('configurationError', function ($message, $title = null, $errorCode = 500) { if (Request::ajax()) { $response = $title . '<br>' . $message; } else { $response = View::make('errors.plainError')->with(array('title' => $title, 'message' => $message)); } die($response); }); /* |-------------------------------------------------------------------------- | Maintenance Mode Handler |-------------------------------------------------------------------------- | | The "down" Artisan command gives you the ability to put an application | into maintenance mode. Here, you will define what is displayed back | to the user if maintenance mode is in effect for the application. | */ App::down(function () { if (!empty($_COOKIE['dev'])) {
<?php /* |-------------------------------------------------------------------------- | Application Response Macros |-------------------------------------------------------------------------- */ use Spescina\PlatformCore\Components\Action\Action as ActionConst; use Spescina\PlatformCore\Facades\Platform; Response::macro('showForm', function ($objId = null, $withInput = false) { $response = Redirect::route('module', array(Platform::getModule(), ActionConst::ACTION_SHOWFORM, $objId)); if ($withInput) { $response->withInput(); } return $response; }); Response::macro('listing', function () { return Redirect::route('module', array(Platform::getModule(), ActionConst::ACTION_LISTING)); });
| | In addition to using Composer, you may use the Laravel class loader to | load your controllers and models. This is useful for keeping all of | your classes in the "global" namespace without Composer updating. | */ Response::macro('jsend', function ($status, $data = null, $message = null, $code = null) { switch ($status) { case 'success': case 'fail': $response = ['success' => $status, 'data' => $data]; //good for form submit //$response = ['success' => $status, $data]; break; default: $response = ['status' => 'error', 'message' => $message]; if ($data) { $response['data'] = $data; } if ($code) { $response['code'] = $code; } } return Response::make($response); }); ClassLoader::addDirectories(array(app_path() . '/commands', app_path() . '/controllers', app_path() . '/models', app_path() . '/database/seeds')); /* |-------------------------------------------------------------------------- | Application Error Logger |-------------------------------------------------------------------------- |