本文整理汇总了PHP中Silex\Application::before方法的典型用法代码示例。如果您正苦于以下问题:PHP Application::before方法的具体用法?PHP Application::before怎么用?PHP Application::before使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Silex\Application
的用法示例。
在下文中一共展示了Application::before方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: register
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
// handling CORS preflight request
$app->before(function (Request $request) {
if ($request->getMethod() === 'OPTIONS') {
$response = new Response();
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setStatusCode(200);
return $response;
}
}, $app::EARLY_EVENT);
$app->before(function (Request $request) {
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : []);
}
});
// CORS domain
$app->after(function (Request $request, Response $response) {
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
});
// Returns the status code in the response body
$app->after(function (Request $request, Response $response) {
$status = $response->getStatusCode();
// Errors
if ($status >= 400 && $response instanceof JsonResponse) {
$data = json_decode($response->getContent(), true);
if (!is_array($data)) {
$data = [];
}
$response->setData(array_merge($data, ['status' => $status]));
}
return $response;
});
// Converts HTTP exception to response
$app->error(function (\Exception $e) {
$response = null;
switch (true) {
case $e instanceof NotFoundHttpException:
case $e instanceof BadRequestHttpException:
$response = new JsonResponse(['message' => $e->getMessage()], $e->getStatusCode(), $e->getHeaders());
break;
default:
}
return $response;
});
}
示例2: boot
public function boot(Application $app)
{
// Because they're at the root admin prefix we mount them directly instead to $app['np.admin.controllers']
$app->mount($app['np.admin.controllers.prefix'], new AuthRouting());
$app->mount($app['np.admin.controllers.prefix'], new AdminRouting());
$app->before(function () use($app) {
$app['np.admin.theme'] = $app->share(function ($app) {
if (isset($app['np.theme.manager'])) {
$app['np.theme.manager']->get($app['np.admin.theme']);
}
});
});
// $app->on(ThemeEvents::THEME_MANAGER_INITIALIZED, function(Event $event) use ($app) {
// $app['np.admin.theme'] = $app->share(function($app) {
// if (isset($app['np.theme.manager'])
// && $theme = $app['np.theme.manager']->getTheme($app['np.admin.theme'])) {
// $javascripts = array();
// // add all extension js modules
// $resources = $app['np.extension_manager']->collectMethodCalls('getResourceManifest');
// foreach ($resources as $resource) {
// if (0 === strpos($resource, '/js')) {
// $javascripts[] = $resource;
// }
// }
// $theme->addJavaScripts($javascripts);
// $app['np.theme.manager']->setTheme($theme);
// return $theme;
// }
// });
// });
}
示例3: register
public function register(Application $app)
{
$logger = $app[$this->name] = new Logger($this, $app);
$app->before(function () use($logger) {
$logger->bindSession();
});
}
示例4: register
public function register(Application $app)
{
$app['monolog'] = $app->share(function () use($app) {
$log = new Logger(isset($app['monolog.name']) ? $app['monolog.name'] : 'myapp');
$app['monolog.configure']($log);
return $log;
});
$app['monolog.configure'] = $app->protect(function ($log) use($app) {
$log->pushHandler($app['monolog.handler']);
});
$app['monolog.handler'] = function () use($app) {
return new StreamHandler($app['monolog.logfile'], $app['monolog.level']);
};
if (!isset($app['monolog.level'])) {
$app['monolog.level'] = function () {
return Logger::DEBUG;
};
}
if (isset($app['monolog.class_path'])) {
$app['autoloader']->registerNamespace('Monolog', $app['monolog.class_path']);
}
$app->before(function (Request $request) use($app) {
$app['monolog']->addInfo('> ' . $request->getMethod() . ' ' . $request->getRequestUri());
});
$app->error(function (\Exception $e) use($app) {
$app['monolog']->addError($e->getMessage());
});
$app->after(function (Request $request, Response $response) use($app) {
$app['monolog']->addInfo('< ' . $response->getStatusCode());
});
}
示例5: _iniMiddlewares
/**
* Init middlewares
*
* @param Application $app
*/
private function _iniMiddlewares(Application $app)
{
// The middleware is run before the routing and the security.
$app->before(function (Request $request, Application $app) {
// The request body should only be parsed as JSON
// if the Content-Type header begins with application/json
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
$content = $request->getContent();
$data = json_decode($content, true);
$request->request->replace(is_array($data) ? $data : array());
}
}, Application::EARLY_EVENT);
// The middleware is run after the routing and the security.
$app->before(function (Request $request, Application $app) {
// Get route
$attrs = $request->attributes->all();
if (isset($attrs['_route'])) {
$route = $attrs['_route'];
$app['route'] = $route;
}
// Get route params
if (isset($attrs['_route_params']) && count($attrs['_route_params'])) {
$route_params = $attrs['_route_params'];
$app['route_params'] = $route_params;
}
});
// Set event after the Response
$app->finish(function (Request $request, Response $response) use($app) {
// Stop event 'eApp'
$event = $app['watch']->stop('eApp');
if ($app['debug']) {
$data = array();
//----------------
// Get sum profile params
$duration = $event->getDuration();
$memory = $event->getMemory();
$data['Sum'] = array('t' => $duration, 'm' => $memory);
// Get periods
$periods = $event->getPeriods();
// Get profile params for periods
if (isset($periods[0])) {
$bootstrapDuration = $periods[0]->getDuration();
$data['Bootstrap'] = array('t' => $bootstrapDuration);
}
if (isset($periods[1])) {
$routingDuration = $periods[1]->getDuration();
$data['Routing'] = array('t' => $routingDuration);
}
if (isset($periods[2])) {
$controllerDuration = $periods[2]->getDuration();
$data['Controller'] = array('t' => $controllerDuration);
}
if (isset($periods[3])) {
$renderDuration = $periods[3]->getDuration();
$data['Render'] = array('t' => $renderDuration);
}
$app['monolog']->addDebug('<== Profile:eApp ==>', $data);
}
});
}
示例6: register
/**
* {@inheritdoc}
*/
public function register(Application $app)
{
$app['informator'] = $app->share(function ($app) {
return new $app['informator_class']($app['url_generator']);
});
$app->before([$app['informator'], 'beforeRequest']);
}
示例7: boot
/**
* @param Application $app
*/
public function boot(Application $app)
{
$options = $this->options;
$cors = new CorsService($options);
// handle OPTIONS preflight request if necessary
$app->before(function (Request $request) use($app, $cors, $options) {
if (!$cors->isCorsRequest($request)) {
return;
}
if ($cors->isPreflightRequest($request)) {
$response = $cors->handlePreflightRequest($request);
$denied_codes = array(Response::HTTP_METHOD_NOT_ALLOWED, Response::HTTP_FORBIDDEN);
$is_denied = in_array($response->getStatusCode(), $denied_codes);
if ($is_denied && !empty($options['denied_reponse_class'])) {
$response = new $options['denied_reponse_class']($response->getContent(), $response->getStatusCode(), $response->headers->all());
}
return $response;
}
if (!$cors->isActualRequestAllowed($request)) {
if (!empty($options['denied_reponse_class'])) {
$response = new $options['denied_reponse_class']('Not allowed', 403);
} else {
$response = new Response('Not allowed.', 403);
}
return $response;
}
}, Application::EARLY_EVENT);
// when the response is sent back, add CORS headers if necessary
$app->after(function (Request $request, Response $response) use($cors) {
if (!$cors->isCorsRequest($request)) {
return;
}
$cors->addActualRequestHeaders($response, $request);
});
}
示例8: boot
public function boot(\Silex\Application $app)
{
$app->before(function (\Symfony\Component\HttpFoundation\Request $request) use($app) {
$routeName = $request->attributes->get('_route');
$route = $request->getRequestUri();
$log = $_SERVER['REMOTE_ADDR'] . ' - ';
if ($app['session']->has('user') && defined('USERNAME_METHOD_LOGGED')) {
$user = $app['session']->get('user');
$method = USERNAME_METHOD_LOGGED;
if (is_callable(array($user, $method))) {
$name = $user->{$method}();
if (!empty($name)) {
$log .= $name;
}
}
}
if (!empty($routeName)) {
$log .= ' está acessando a rota "' . $routeName . '" (' . $route . ')';
} else {
if (!file_exists(__WEBROOT__ . $route)) {
$log .= ' tentou acessar um arquivo ou rota inexistente (' . $route . ')!';
} else {
$log .= ' está acessando um arquivo (' . $route . ')!';
}
}
$app['monolog']->addInfo($log);
});
$app->error(function (\Exception $e, $code) use($app) {
$msg = $code != 500 ? $e->getMessage() : $e->getFile() . ' na linha ' . $e->getLine() . ': ' . $e->getMessage();
$app['monolog']->addError('cod: ' . $code . ' => ' . $msg);
});
}
示例9: boot
public function boot(Application $app)
{
$app->before(function () use($app) {
$app['np.extensions']['debug'] = $app['debug'];
$app['np.extensions']['admin'] = $app['np.admin'];
$app['np.extensions']->boot();
// add template paths for all extensions and blocks
$app['twig.loader.filesystem'] = $app->share($app->extend('twig.loader.filesystem', function ($loader, $app) {
foreach ($app['np.extensions']->getAll() as $namespace => $extension) {
$loader->addPath($extension->getPath(), $namespace);
}
foreach ($app['np.extensions']['block_types'] as $blockType) {
$loader->addPath($blockType->getPath(), 'block_' . $app['np.slug_helper']->slugify($blockType->name));
}
return $loader;
}));
// load collected twig functions
$app['twig'] = $app->share($app->extend('twig', function ($twig, $app) {
foreach ($app['np.extensions']['twig_extensions'] as $extension) {
$twig->addExtension($extension);
}
return $twig;
}));
});
$app->after(function (Request $request, Response $response) use($app) {
if ($response instanceof BinaryFileResponse || !$app['np.extensions']->booted) {
return;
}
$app['np.extensions']->prepareSnippets();
$response->setContent($app['np.extensions']['snippet_queue']->processAll($app, $response->getContent()));
});
}
示例10: boot
public function boot(Application $app)
{
$app->before(function (Request $request) use($app) {
$app['monolog']->addInfo('> ' . $request->getMethod() . ' ' . $request->getRequestUri());
});
/*
* Priority -4 is used to come after those from SecurityServiceProvider (0)
* but before the error handlers added with Silex\Application::error (defaults to -8)
*/
$app->error(function (\Exception $e) use($app) {
$message = sprintf('%s: %s (uncaught exception) at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
if ($e instanceof HttpExceptionInterface && $e->getStatusCode() < 500) {
$app['monolog']->addError($message, array('exception' => $e));
} else {
$app['monolog']->addCritical($message, array('exception' => $e));
}
}, -4);
$app->after(function (Request $request, Response $response) use($app) {
if ($response instanceof RedirectResponse) {
$app['monolog']->addInfo('< ' . $response->getStatusCode() . ' ' . $response->getTargetUrl());
} else {
$app['monolog']->addInfo('< ' . $response->getStatusCode());
}
});
}
示例11: boot
public function boot(Application $app)
{
// set up the middleware with short-circuit
$app->before(function (Request $request) use($app) {
return $this->enforceValidSessionId($app, $request);
});
}
示例12: register
public function register(Application $app)
{
$app['url_generator'] = $app->share(function () use($app) {
$urlGenerator = new UrlGenerator($app['routes'], $app['request_context']);
if (isset($app['facebook.canvas']) && $app['facebook.canvas'] && isset($app['facebook.namespace'])) {
$urlGenerator->setNamespace($app['facebook.namespace']);
}
return $urlGenerator;
});
if (!isset($app['facebook.class_path'])) {
$app['facebook.class_path'] = __DIR__ . '/../../../vendor/facebook-php-sdk/src';
}
require_once $app['facebook.class_path'] . '/facebook.php';
$app['facebook'] = $app->share(function () use($app) {
if (!isset($app['session'])) {
$app->register(new SessionServiceProvider());
}
$parameters = array('app_id', 'secret', 'namespace', 'canvas', 'proxy', 'timeout', 'connect_timeout', 'permissions', 'protect');
$config = array();
foreach ($parameters as $parameter) {
if (isset($app['facebook.' . $parameter])) {
$config[$parameter] = $app['facebook.' . $parameter];
}
}
return new Facebook($config, $app['session'], isset($app['monolog']) ? $app['monolog'] : null);
});
$app->before(function ($request) use($app) {
$app['facebook']->setRequest($request);
});
}
示例13: register
/**
* Register before callbacks
*
* $app["user.authenticated"] => user must be authenticated to run the action
* $app["user.in.group"]($groups) => user must have all defined groups to run the action
*/
public function register(Application $app)
{
$app->before([$this, "addUserToRequest"], Application::EARLY_EVENT);
$app["auth"] = $this;
$app["auth.authenticated"] = [$this, "authenticated"];
$app["auth.secure"] = [$this, "userHasGroup"];
}
示例14: register
public function register(Application $app)
{
$app->before(function () use($app) {
$app['session']->start();
if ($app['request']->get('_route') == 'logout') {
return;
}
if (!$app['session']->has('username')) {
$openid = new \LightOpenID($_SERVER['SERVER_NAME']);
if (!$openid->mode) {
$openid->identity = 'https://www.google.com/accounts/o8/id';
$openid->required = array('email' => 'contact/email', 'firstname' => 'namePerson/first', 'lastname' => 'namePerson/last');
return $app->redirect($openid->authUrl());
} else {
if ($openid->validate()) {
$attributes = $openid->getAttributes();
$app['session']->set('username', $attributes['contact/email']);
$app['session']->set('fullname', $attributes['namePerson/first'] . ' ' . $attributes['namePerson/last']);
}
}
}
$app['twig']->addGlobal('username', $app['session']->get('username'));
$app['twig']->addGlobal('fullname', $app['session']->get('fullname'));
if (isset($app['auth']) && !$app['auth']($app['session']->get('username'))) {
$app['session']->remove('username');
$app['session']->remove('fullname');
return new Response($app['twig']->render('forbidden.html.twig'), 403);
}
});
}
示例15: register
public function register(Application $app)
{
$app->before(function (Request $request, Application $app) {
if (explode('?', $request->getRequestUri())[0] === '/' || explode('?', $request->getRequestUri())[0] === '/not-found') {
return;
}
$password = $request->request->get('founder');
$cookie = $request->cookies->get('founder');
$needsCookie = false;
if (is_null($cookie)) {
$needsCookie = true;
}
if (is_null($password)) {
$password = $cookie;
}
$user = $app['password'];
$isValidUser = in_array(strtolower($password), $user);
$admin = strtolower($app['adminPassword']);
if (!$isValidUser) {
return new Response('', 301, ['location' => '/?invalid']);
}
if ($password === $admin) {
$app['isAdmin'] = true;
}
if ($needsCookie) {
setcookie('founder', $password);
}
});
}