Created
April 18, 2016 18:15
-
-
Save punkstar/f62b49cd8473d67854d28788aa2d3d07 to your computer and use it in GitHub Desktop.
Laravel: Match protocol of incoming request when generating routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Providers; | |
| use Illuminate\Http\Request; | |
| use Illuminate\Routing\UrlGenerator; | |
| use Illuminate\Support\ServiceProvider; | |
| /** | |
| * Class ApplyUrlSchemeStrategyProvider | |
| * | |
| * Configuring using the SCHEME_STRATEGY environment variable, this provider will configure the URL generation in the | |
| * application to either force secure, force insecure or match scheme with the incoming request. | |
| * | |
| * @package App\Providers | |
| */ | |
| class ApplyUrlSchemeStrategyProvider extends ServiceProvider | |
| { | |
| const ENV_KEY = 'SCHEME_STRATEGY'; | |
| const STRATEGY_MATCH = 'match'; | |
| const STRATEGY_SECURE = 'secure'; | |
| const STRATEGY_INSECURE = 'insecure'; | |
| const SCHEME_SECURE = 'https'; | |
| const SCHEME_INSECURE = 'http'; | |
| /** | |
| * Bootstrap the application services. | |
| */ | |
| public function boot() | |
| { | |
| $this->app['vanilla_url'] = $this->app['url']; | |
| $this->app['url'] = $this->app->share(function ($app) { | |
| /** @var Request $request */ | |
| $request = $app['request']; | |
| /** @var UrlGenerator $url */ | |
| $url = $app['vanilla_url']; | |
| $schemeStrategy = env(self::ENV_KEY); | |
| $scheme = null; | |
| switch ($schemeStrategy) { | |
| case self::STRATEGY_SECURE: | |
| $scheme = self::SCHEME_SECURE; | |
| break; | |
| case self::STRATEGY_INSECURE: | |
| $scheme = self::SCHEME_INSECURE; | |
| break; | |
| case self::STRATEGY_MATCH: | |
| if ($request->secure()) { | |
| $scheme = self::SCHEME_SECURE; | |
| } else { | |
| $scheme = self::SCHEME_INSECURE; | |
| } | |
| break; | |
| } | |
| if ($scheme) { | |
| $url->forceSchema($scheme); | |
| } | |
| return $url; | |
| }); | |
| } | |
| /** | |
| * Register the application services. | |
| * | |
| * @return void | |
| */ | |
| public function register() | |
| { | |
| // Do nothing. | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment