How to generate Absolute URL from Early/Auto loaded Symfony 3 router

≡放荡痞女 提交于 2019-12-02 19:37:07

问题


I am writing Guards to handle OAuth for my Symfony 3 application.

As part of it, in one of my services, I need to generate an absolute URL to send to Twitter as the Callback URL.

#services.yml
...
app.twitter_client:
    class: MyApiBundle\Services\TwitterClient
    arguments:
        - %twitter_client_id%
        - %twitter_client_secret%
        - connect_twitter_check
        - '@request_stack'
        - '@router'
        - '@logger'
app.twitter_authenticator:
    class: MyApiBundle\Security\TwitterAuthenticator
    arguments:
        - '@app.twitter_client'
        - '@logger'

The logger is temporary for debugging.

#TwitterClient.php service
...
use Monolog\Logger;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
class TwitterClient
{

/**
 * TwitterClient constructor.
 * @param string          $identifier
 * @param string          $secret
 * @param string          $callbackUrl
 * @param RequestStack    $requestStack
 * @param RouterInterface $router
 * @param Logger          $logger
 */
public function __construct(
    string $identifier,
    string $secret,
    string $callbackUrl,
    RequestStack $requestStack,
    RouterInterface $router,
    Logger $logger
) {
    $callbackUrl = $router->generate($callbackUrl, [], RouterInterface::ABSOLUTE_URL);
    $logger->info($callbackUrl);
    ...
}

And when it outputs the $callbackUrl to the logs, it just says localhost, even though I am accessing it using a different URL.

http://localhost/connect/twitter/check

But if I do the same from my a controller, it outputs the full proper URL.

#TwitterController.php
...
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;


class TwitterController extends Controller
{
    /**
     * @Route("/connect/twitter")
     * @return RedirectResponse
     */
    public function connectAction()
    {
        /** @var RouterInterface $router */
        $router = $this->container->get('router');
        $callbackUrl = $router->generate('connect_twitter_check', [], RouterInterface::ABSOLUTE_URL);
        /** @var Logger $logger */
        $logger = $this->container->get('logger');
        $this->container->get('logger')
            ->info($callbackUrl);
        ...

This outputs:

https://dev.myapi.com:8082/app_dev.php/connect/twitter/check

The dev.myapi.com domain is set up in my hosts file and points to localhost, to make it easier to differentiate between my local apps and also to make it easier to integrate with OAuth services.


回答1:


I managed to solve this by setting the Router context. I already loaded in the RequestStack to access the user's IP, so I used it to set the context of the Route and then the router worked as expected. I ran into problems trying to use the RequestStack in the constructor, so I ended up refactoring it so that it used the RequestStack as late as possible.

class TwitterClient
{
    private $identifier;
    private $secret;
    private $callbackUrl;
    private $requestStack;
    private $router;
    private $server;

    /**
     * TwitterClient constructor.
     *
     * @param string          $identifier
     * @param string          $secret
     * @param string          $callbackUrl
     * @param RequestStack    $requestStack
     * @param RouterInterface $router
     */
    public function __construct(
        string $identifier,
        string $secret,
        string $callbackUrl,
        RequestStack $requestStack,
        RouterInterface $router
    ) {
        $this->identifier = $identifier;
        $this->secret = $secret;
        $this->callbackUrl = $callbackUrl;
        $this->requestStack = $requestStack;
        $this->router = $router;
    }

    /**
     * Wait until the last moment to create the Twitter object to make sure that the requestStack is loaded.
     *
     * @return \League\OAuth1\Client\Server\Twitter
     */
    private function getServer()
    {
        if (!$this->server) {
            $context = new RequestContext();
            $context->fromRequest($this->requestStack->getCurrentRequest());
            $this->router->setContext($context);
            $callbackUrl = $this->router->generate($this->callbackUrl, [], RouterInterface::ABSOLUTE_URL);
            $this->server = new Twitter(
                [
                    'identifier' => $this->identifier,
                    'secret' => $this->secret,
                    'callback_uri' => $callbackUrl,
                ]
            );
        }

        return $this->server;
    }
    ...
}


来源:https://stackoverflow.com/questions/43630670/how-to-generate-absolute-url-from-early-auto-loaded-symfony-3-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!