作者:Geminey
项目:BecklynPageTreeBundl
/**
* Builds the pagetree
*
* @param RouterInterface $router
*
* @throws PageTree\InvalidPageTreeException
*/
private function buildPageTree(RouterInterface $router)
{
$this->pageTree = [];
$this->directAccess = [];
// collect all routes, which are configured to be in the page tree
foreach ($router->getRouteCollection() as $routeName => $route) {
/** @var Route $route */
$node = $this->transformRouteToNode($routeName, $route);
if (!is_null($node)) {
$this->directAccess[$routeName] = $node;
}
}
// apply correct nesting of routes
foreach ($this->directAccess as $node) {
if ($node->isRootNode()) {
$this->pageTree[] = $node;
} else {
if (array_key_exists($node->getParent(), $this->directAccess)) {
$this->directAccess[$node->getParent()]->addChild($node);
} else {
throw new InvalidPageTreeException("Invalid pagetree at route „{$node->getRoute()}“: parent '{$node->getParent()}' requested, but route was not found. Did you forget to define the route „{$node->getRoute()}“ as root?");
}
}
}
}
作者:mbabenko2
项目:likedimion-serve
public function action(RouterInterface $router, RequestContext $context)
{
$request = Request::createFromGlobals();
$bPath = $context->getPathInfo();
try {
$parameters = $router->match($bPath);
var_dump($parameters);
$_controller = $parameters["_controller"];
$_controller = explode(":", $_controller);
$class = $_controller[0];
$action = strtolower($_controller[1]) . "Action";
$class = new $class();
ob_start();
if (method_exists($class, $action)) {
$class->{$action}($request, new JsonResponse());
$response = new Response(ob_get_clean());
} else {
$response = new Response('Not Found', 404);
}
} catch (ResourceNotFoundException $e) {
$response = new Response('Not Found', 404);
} catch (Exception $e) {
$response = new Response('An error occurred', 500);
}
$response->send();
}
作者:CG7
项目:ezpublish-kerne
public function onSiteAccessMatch(PostSiteAccessMatchEvent $event)
{
$rootLocationId = $this->configResolver->getParameter('content.tree_root.location_id');
$this->urlAliasRouter->setRootLocationId($rootLocationId);
$this->urlAliasGenerator->setRootLocationId($rootLocationId);
$this->urlAliasGenerator->setExcludedUriPrefixes($this->configResolver->getParameter('content.tree_root.excluded_uri_prefixes'));
}
作者:alehers
项目:Syliu
/**
* @param string $route
* @param array $data
*
* @return RedirectResponse
*/
public function redirectToRoute($route, array $data = array())
{
if ('referer' === $route) {
return $this->redirectToReferer();
}
return $this->redirect($this->router->generate($route, $data));
}
作者:mattvic
项目:FOSUserBundleMandrillMaile
/**
* {@inheritDoc}
*/
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['resetting_password.template'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()), true);
$rendered = $this->templating->render($template, array('confirmationUrl' => $url, 'user' => $user));
$this->sendEmailMessage($rendered, $user->getEmail());
}
作者:gravity-cm
项目:menu-bundl
public function serializeRouteArrayToJson(JsonSerializationVisitor $visitor, array $route, array $type, Context $context)
{
if (is_array($route)) {
list($routeName, $routeParameters) = $route;
return $this->router->generate($routeName, $routeParameters);
}
}
作者:kasobu
项目:EDENS-Mauti
/**
* {@inheritdoc}
*/
public function warmUp($cacheDir)
{
$processedRoutes = array();
$routeCollection = $this->router->getRouteCollection();
foreach ($routeCollection->all() as $name => $route) {
if (!isset($processedRoutes[$route->getPattern()])) {
$processedRoutes[$route->getPattern()] = array('methods' => array(), 'names' => array());
}
$processedRoutes[$route->getPattern()]['names'][] = $name;
$requirements = $route->getRequirements();
if (isset($requirements['_method'])) {
$methods = explode('|', $requirements['_method']);
$processedRoutes[$route->getPattern()]['methods'] = array_merge($processedRoutes[$route->getPattern()]['methods'], $methods);
}
}
$allowedMethods = array();
foreach ($processedRoutes as $processedRoute) {
if (count($processedRoute['methods']) > 0) {
foreach ($processedRoute['names'] as $name) {
$allowedMethods[$name] = array_unique($processedRoute['methods']);
}
}
}
$this->cache->write(sprintf('<?php return %s;', var_export($allowedMethods, true)), $routeCollection->getResources());
}
作者:sainthardawa
项目:atlassian-connect-bundl
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$routes = $this->router->getRouteCollection();
$route = $routes->get($request->attributes->get('_route'));
if (!$route->getOption('requires_license')) {
return;
}
if ('active' != $request->get('lic') && $this->kernel->getEnvironment() == 'prod') {
// Checking for whitelisted users
try {
$user = $this->tokenStorage->getToken()->getUser();
$today = date('Y-m-d');
if ($user instanceof UserInterface) {
$whitelist = $this->kernel->getContainer()->getParameter('license_whitelist');
foreach ($whitelist as $allowed) {
if ($allowed['client_key'] == $user->getClientKey() && $today <= $allowed['valid_till']) {
return;
}
}
}
} catch (\Exception $e) {
// Do nothing
}
$url = $this->router->generate('atlassian_connect_unlicensed');
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
作者:thelia-module
项目:BoSearc
public function onMainTopMenuTools(HookRenderBlockEvent $event)
{
$isGranted = $this->securityContext->isGranted(["ADMIN"], [], [BoSearch::getModuleCode()], [AccessManager::VIEW]);
if ($isGranted) {
$event->add(['title' => $this->trans('Search product', [], BoSearch::DOMAIN_NAME), 'url' => $this->router->generate('bosearch.product.view')]);
}
}
作者:qiyu258
项目:php-wallet-sampl
/**
* @param Request $request
* @return Response
* @throws \Exception
*/
public function __invoke(Request $request)
{
$walletId = $request->get('walletId');
$walletDto = $this->walletServiceFacade->getWallet($walletId);
$this->checkAuthorizationForWallet($walletDto);
$createTransactionCommand = $this->createCreateTransactionCommand($walletId);
$user = $this->getUser();
$createTransactionForm = $this->transactionFormFactory->createCreateForm($createTransactionCommand, $user->getId()->getValue());
$createTransactionForm->handleRequest($request);
if (!$createTransactionForm->isValid()) {
$validationMsg = $this->getAllFormErrorMessagesAsString($createTransactionForm);
$this->addFlash('error', $this->trans('create_transaction_form.flash.invalid_form') . ' ' . $validationMsg);
} else {
/** @var CreateTransactionCommand $createTransactionCommand */
$createTransactionCommand = $createTransactionForm->getData();
try {
$commandValidator = new CreateTransactionCommandValidator();
$commandValidator->validate($createTransactionCommand);
$this->commandBus->handle($createTransactionCommand);
$this->addFlash('success', $this->trans('transaction.flash.create_successfully'));
$url = $this->router->generate('bc_app_wallet_transaction.index', array('walletId' => $createTransactionCommand->getWalletId()));
return new RedirectResponse($url);
} catch (\Exception $e) {
$this->addFlash('error', $e->getMessage());
}
}
$walletDto = $this->walletServiceFacade->getWallet($walletId);
return $this->renderTransactionShowNew($request, $createTransactionForm->createView(), $walletDto);
}
作者:aspreg
项目:BreadcrumbBundl
/**
* @param BreadcrumbItem $item
* @param array $variables
* @return ProcessedBreadcrumbItem
*/
public function process(BreadcrumbItem $item, $variables)
{
// Process the label
if ($item->getLabel()[0] === '$') {
$processedLabel = $this->parseValue($item->getLabel(), $variables);
} else {
$processedLabel = $this->translator->trans($item->getLabel());
}
// Process the route
// TODO: cache parameters extracted from current request
$params = [];
foreach ($this->requestStack->getCurrentRequest()->attributes as $key => $value) {
if ($key[0] !== '_') {
$params[$key] = $value;
}
}
foreach ($item->getRouteParams() ?: [] as $key => $value) {
if ($value[0] === '$') {
$params[$key] = $this->parseValue($value, $variables);
} else {
$params[$key] = $value;
}
}
if ($item->getRoute() !== null) {
$processedUrl = $this->router->generate($item->getRoute(), $params);
} else {
$processedUrl = null;
}
return new ProcessedBreadcrumbItem($processedLabel, $processedUrl);
}
作者:rogcha
项目:Diakoni
/**
* {@inheritdoc}
*/
protected function getUriFromNode(NodeInterface $node)
{
if ($node instanceof RouterNodeInterface && null !== $node->getRoute()) {
return $this->router->generate($node->getRoute(), $node->getRouteParameters(), $node->isRouteAbsolute());
}
return $node->getUri();
}
作者:atompuls
项目:ran-bundl
/**
* Intercept Exceptions and send valid ajax errors
* The idea is to NOT send HTML response when an issue(i.e.session expired) is encountered
* in an ajax request.
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
// Get the exception object from the received event
$exception = $event->getException();
$request = $event->getRequest();
$isAjaxRequest = $request->isXmlHttpRequest();
if ($isAjaxRequest) {
$headers = [];
// handle session expired
if ($exception instanceof AuthenticationException) {
$loginUrl = $this->router->generate('fos_user_security_login');
// add custom header to redirect to login page on the client
$headers['relogin'] = true;
$headers['login-url'] = $loginUrl;
$response = new Response('Authentication Required', 200, $headers);
} elseif ($exception instanceof AccessDeniedException) {
$headers['not-authorized'] = true;
$response = new Response('Not authorized', 403, $headers);
} else {
$responseData = ['status' => false, 'msg' => 'Unknown Issue Encountered', 'data' => ['exception' => ['message' => $exception->getMessage(), 'file' => "{$exception->getFile()}:{$exception->getLine()}", 'trace' => $exception->getTraceAsString()]]];
$response = new Response(json_encode($responseData), 500, $headers);
}
$event->setResponse($response);
$event->stopPropagation();
}
}
作者:jaapjansm
项目:homefinanc
public function lostPasswordMail(User $user)
{
$template = 'HomefinanceBundle:mailer:lost_password.txt.twig';
$url = $this->router->generate('reset_password_check_token', array('token' => $user->getConfirmationToken()), true);
$context = array('user' => $user, 'confirmationUrl' => $url);
$this->sendMessage($template, $context, $user->getEmail());
}
作者:remine
项目:DunglasApiBundl
/**
* Sends the Hydra header on each response.
*
* @param FilterResponseEvent $event
*/
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$event->getResponse()->headers->set('Link', sprintf('<%s>; rel="%sapiDocumentation"', $this->router->generate('api_hydra_vocab', [], UrlGeneratorInterface::ABSOLUTE_URL), ContextBuilder::HYDRA_NS));
}
作者:scottstuf
项目:GCProtractorJ
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
$session = $event->getRequest()->getSession();
/** @var BaseController $ctrl */
$ctrl = $controller[0];
if (!is_object($ctrl) || !$ctrl instanceof BaseController) {
return;
}
// no loop for you, also allow username checking
if ($ctrl instanceof ProfileController && ($controller[1] == 'updateUsernameAction' || $controller[1] == 'checkUsernameAction')) {
return;
}
/** @var User $user */
$user = $ctrl->getUser();
if ($user && $this->isGUID($user->getUsername())) {
$session->getFlashBag()->add('error', "We recently changed our username restrictions. Your previous username is no longer valid. Please create a new one.");
$url = $this->router->generate('reset_username');
$event->setController(function () use($url) {
return new RedirectResponse($url);
});
}
}
作者:blab201
项目:se
/**
* Creates a Response object to send upon a successful logout.
*
* @param Request $request
*
* @return Response never null
*/
public function onLogoutSuccess(Request $request)
{
if ($request->isXmlHttpRequest() or 'json' == $request->getRequestFormat()) {
return new JsonResponse(true);
}
return new RedirectResponse($this->router->generate('homepage'));
}
作者:mikowe
项目:vsymfo-core-bundl
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$format = null;
if (is_string($this->forceFormat)) {
$format = $this->forceFormat;
} else {
$request = $event->getRequest();
if ($this->router instanceof I18nRouter) {
$collection = $this->router->getOriginalRouteCollection();
} else {
$collection = $this->router->getRouteCollection();
}
$route = $collection->get($request->get('_route'));
if (!empty($route)) {
$defaultFormat = is_null($route->getDefault('_format')) ? 'html' : $route->getDefault('_format');
} else {
$defaultFormat = 'html';
}
$format = !is_null($request->attributes->get('_format')) ? $request->attributes->get('_format') : $defaultFormat;
}
if (!is_null($format)) {
$serviceName = 'vsymfo_core.service.' . strtolower($format) . '_document';
if ($this->container->has($serviceName) && $this->container->get($serviceName) instanceof DocumentFactoryInterface) {
$service = $this->container->get($serviceName);
} else {
$service = $this->container->get('vsymfo_core.service.txt_document');
}
$doc = $service->createDocument();
$this->container->get('vsymfo_core.service.document')->setDefaultsToDocument($doc);
$this->container->set($this->serviceName, $doc);
}
}
作者:uirapur
项目:event
/**
* @param array $workshops
* @return array
*/
public function decorate(array $workshops = [])
{
$workshops = array_map(function (Workshop $workshop) {
return ["id" => $workshop->getSlug(), "start" => $workshop->getStartDate()->format(DateTime::ISO8601), "end" => $workshop->getEndDate()->format(DateTime::ISO8601), "title" => sprintf("%s: %s", $workshop->getCity(), $workshop->getTitle()), "editable" => false, "backgroundColor" => '', "url" => $this->router->generate("evento_show", ["slug" => $workshop->getSlug()])];
}, $workshops);
return $workshops;
}
作者:uirapur
项目:event
/**
* @param array $lessons
* @return array
*/
public function decorate(array $lessons = [])
{
$lessons = array_map(function (Lesson $lesson) {
return ["id" => sprintf("%s#%s", $lesson->getWorkshop()->getSlug(), $lesson->getId()), "start" => $lesson->getStartDate()->format("Y-m-d H:i:s"), "end" => $lesson->getEndDate()->format("Y-m-d H:i:s"), "editable" => false, "url" => sprintf("%s#%s", $this->router->generate("evento_show", ["slug" => $lesson->getWorkshop()->getSlug()]), $lesson->getId())];
}, $lessons);
return $lessons;
}