diff --git a/_docs/1-Installation-and-Setup.md b/_docs/1-Installation-and-Setup.md index a86f0bd..aba8349 100644 --- a/_docs/1-Installation-and-Setup.md +++ b/_docs/1-Installation-and-Setup.md @@ -56,23 +56,6 @@ Once the package is installed, you can register the service provider in `config/ > No need to register the Localization facade, it's done automagically. -##### Now you need to update your Http Kernel to use the Localization Router. - -```php -// app/Http/Kernel.php -=5.6.4", - "arcanedev/support": "~3.20" + "arcanedev/support": "~4.1" }, "require-dev": { "phpunit/phpcov": "~3.0", diff --git a/config/localization.php b/config/localization.php index af08c77..d11fea3 100644 --- a/config/localization.php +++ b/config/localization.php @@ -1,10 +1,12 @@ ['en', 'es', 'fr'], 'accept-language-header' => true, @@ -13,10 +15,11 @@ 'facade' => 'Localization', - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Route - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ + 'route' => [ 'middleware' => [ 'localization-session-redirect' => true, @@ -27,10 +30,11 @@ ], ], - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Locales - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ + 'locales' => [ // A //====================================================> diff --git a/src/Contracts/LocalesManager.php b/src/Contracts/LocalesManager.php index 48df03b..cbc99fc 100644 --- a/src/Contracts/LocalesManager.php +++ b/src/Contracts/LocalesManager.php @@ -8,9 +8,9 @@ */ interface LocalesManager { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Set and return current locale. @@ -90,9 +90,9 @@ public function getSupportedLocalesKeys(); */ public function setSupportedLocales(array $supportedLocales); - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Check Methods + | ----------------------------------------------------------------- */ /** * Check if default is supported. diff --git a/src/Contracts/Localization.php b/src/Contracts/Localization.php index ce4a548..b6fe73c 100644 --- a/src/Contracts/Localization.php +++ b/src/Contracts/Localization.php @@ -10,9 +10,9 @@ */ interface Localization { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Returns default locale. @@ -93,6 +93,13 @@ public function getCurrentLocaleNative(); */ public function getCurrentLocaleRegional(); + /** + * Get all locales. + * + * @return \Arcanedev\Localization\Entities\LocaleCollection + */ + public function getAllLocales(); + /** * Set and return current locale. * @@ -116,9 +123,9 @@ public function setBaseUrl($url); */ public function setRouteNameFromRequest(Request $request); - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Translate routes and save them to the translated routes array (used in the localize route filter). @@ -168,9 +175,9 @@ public function getLocalizedURL($locale = null, $url = null, $attributes = []); */ public function createUrlFromUri($uri); - /* ------------------------------------------------------------------------------------------------ - | Translation Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Translation Methods + | ----------------------------------------------------------------- */ /** * Returns an URL adapted to the route name and the locale given. @@ -183,27 +190,23 @@ public function createUrlFromUri($uri); */ public function getUrlFromRouteName($locale, $transKey, $attributes = []); - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Check Methods + | ----------------------------------------------------------------- */ /** - * Check if Locale exists on the supported locales collection. - * - * @param string|bool $locale + * Hide the default locale in URL ?? * * @return bool */ - public function isLocaleSupported($locale); + public function isDefaultLocaleHiddenInUrl(); - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ - */ /** - * Hide the default locale in URL ?? + * Check if Locale exists on the supported locales collection. + * + * @param string|bool $locale * * @return bool */ - public function isDefaultLocaleHiddenInUrl(); + public function isLocaleSupported($locale); } diff --git a/src/Contracts/Negotiator.php b/src/Contracts/Negotiator.php index c46db60..42e72ec 100644 --- a/src/Contracts/Negotiator.php +++ b/src/Contracts/Negotiator.php @@ -1,5 +1,6 @@ setRegional(isset($data['regional']) ? $data['regional'] : ''); } - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Get local key. @@ -181,7 +181,7 @@ public function direction() /** * Set Direction. * - * @param string $direction + * @param string $direction * * @return self */ @@ -264,9 +264,9 @@ private function setDefault() return $this; } - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Create Locale instance. @@ -281,9 +281,9 @@ public static function make($key, array $data) return new self($key, $data); } - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Get the locale entity as an array. diff --git a/src/Entities/LocaleCollection.php b/src/Entities/LocaleCollection.php index af5aec9..d2b68e2 100644 --- a/src/Entities/LocaleCollection.php +++ b/src/Entities/LocaleCollection.php @@ -10,17 +10,10 @@ */ class LocaleCollection extends Collection { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Properties - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ - /** - * Locale collection. - * - * @var array - */ - protected $items = []; - /** * Supported locales. * @@ -28,9 +21,9 @@ class LocaleCollection extends Collection */ protected $supported = []; - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Set supported locales keys. @@ -46,9 +39,9 @@ public function setSupportedKeys(array $supported) return $this; } - /* ------------------------------------------------------------------------------------------------ - | Main Function - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Get the first locale from the collection. diff --git a/src/Facades/Localization.php b/src/Facades/Localization.php index 6a8dc86..43d48d9 100644 --- a/src/Facades/Localization.php +++ b/src/Facades/Localization.php @@ -1,5 +1,6 @@ localesManager = $localesManager; $this->localesManager->setDefaultLocale( - $this->app->getLocale() + $this->app['config']->get('app.locale') ); } - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Get Request instance. @@ -239,9 +240,9 @@ public function setBaseUrl($url) return $this; } - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Translate routes and save them to the translated routes array (used in the localize route filter). @@ -293,21 +294,18 @@ public function getNonLocalizedURL($url = null) */ public function getLocalizedURL($locale = null, $url = null, $attributes = []) { - if (is_null($locale)) { + if (is_null($locale)) $locale = $this->getCurrentLocale(); - } $this->isLocaleSupportedOrFail($locale); - if (empty($attributes)) { + if (empty($attributes)) $attributes = Url::extractAttributes($url); - } if (empty($url)) { if ($this->routeTranslator->hasCurrentRoute()) { - if (empty($attributes)) { + if (empty($attributes)) $attributes = $this->request()->route()->parameters(); - } return $this->getUrlFromRouteName( $locale, @@ -333,9 +331,8 @@ public function getLocalizedURL($locale = null, $url = null, $attributes = []) $baseUrl, $parsedUrl, $this->getDefaultLocale(), $this->getSupportedLocales() ); - if ($translatedRoute !== false) { + if ($translatedRoute !== false) return $this->getUrlFromRouteName($locale, $translatedRoute, $attributes); - } if ( ! empty($locale) && @@ -349,15 +346,11 @@ public function getLocalizedURL($locale = null, $url = null, $attributes = []) $url = Url::unparse($parsedUrl); - if (filter_var($url, FILTER_VALIDATE_URL)) { - return $url; - } + if (filter_var($url, FILTER_VALIDATE_URL)) return $url; - if (empty($url)) { - $url = $parsedUrl['path']; - } - - return $this->createUrlFromUri($url); + return $this->createUrlFromUri( + empty($url) ? $parsedUrl['path'] : $url + ); } /** @@ -371,7 +364,7 @@ public function createUrlFromUri($uri) { $uri = ltrim($uri, '/'); - return empty($this->baseUrl) ? app('url')->to($uri) : $this->baseUrl.$uri; + return empty($this->baseUrl) ? $this->app['url']->to($uri) : $this->baseUrl.$uri; } /** @@ -381,14 +374,14 @@ public function createUrlFromUri($uri) */ public function localesNavbar() { - $supportedLocales = $this->getSupportedLocales(); - - return view('localization::navbar', compact('supportedLocales'))->render(); + return $this->app[ViewFactoryContract::class] + ->make('localization::navbar', ['supportedLocales' => $this->getSupportedLocales()]) + ->render(); } - /* ------------------------------------------------------------------------------------------------ - | Translation Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Translation Methods + | ----------------------------------------------------------------- */ /** * Returns the translated route for an url and the attributes given and a locale @@ -407,9 +400,8 @@ private function findTranslatedRouteByUrl($url, $attributes, $locale) foreach ($this->routeTranslator->getTranslatedRoutes() as $translatedRoute) { $translatedUrl = $this->getUrlFromRouteName($locale, $translatedRoute, $attributes); - if ($this->getNonLocalizedURL($translatedUrl) === $this->getNonLocalizedURL($url)) { + if ($this->getNonLocalizedURL($translatedUrl) === $this->getNonLocalizedURL($url)) return $translatedRoute; - } } return false; @@ -456,9 +448,9 @@ public function setRouteNameFromRequest(Request $request) $this->routeTranslator->setCurrentRoute($routeName); } - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Check Methods + | ----------------------------------------------------------------- */ /** * Hide the default locale in URL ?? @@ -491,10 +483,9 @@ public function isLocaleSupported($locale) */ private function isLocaleSupportedOrFail($locale) { - if ( ! $this->isLocaleSupported($locale)) { + if ( ! $this->isLocaleSupported($locale)) throw new UnsupportedLocaleException( - "Locale '$locale' is not in the list of supported locales." + "Locale '{$locale}' is not in the list of supported locales." ); - } } } diff --git a/src/LocalizationServiceProvider.php b/src/LocalizationServiceProvider.php index 89bde86..f991909 100644 --- a/src/LocalizationServiceProvider.php +++ b/src/LocalizationServiceProvider.php @@ -21,20 +21,6 @@ class LocalizationServiceProvider extends PackageServiceProvider */ protected $package = 'localization'; - /* ------------------------------------------------------------------------------------------------ - | Getters & Setters - | ------------------------------------------------------------------------------------------------ - */ - /** - * Get the base path of the package. - * - * @return string - */ - public function getBasePath() - { - return dirname(__DIR__); - } - /* ------------------------------------------------------------------------------------------------ | Main Functions | ------------------------------------------------------------------------------------------------ @@ -44,6 +30,8 @@ public function getBasePath() */ public function register() { + parent::register(); + $this->registerConfig(); $this->registerProviders([ Providers\RoutingServiceProvider::class, @@ -86,14 +74,7 @@ public function provides() */ private function registerLocalization() { - $this->singleton(Contracts\Localization::class, function($app) { - return new Localization( - $app, - $app[Contracts\RouteTranslator::class], - $app[Contracts\LocalesManager::class] - ); - }); - + $this->singleton(Contracts\Localization::class, Localization::class); $this->singleton('arcanedev.localization', Contracts\Localization::class); $this->alias( diff --git a/src/Middleware/LocaleCookieRedirect.php b/src/Middleware/LocaleCookieRedirect.php index 0108c69..9cf3e4c 100644 --- a/src/Middleware/LocaleCookieRedirect.php +++ b/src/Middleware/LocaleCookieRedirect.php @@ -1,6 +1,5 @@ - * - * @todo: Refactoring */ class LocaleCookieRedirect extends Middleware { - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Handle an incoming request. @@ -29,20 +26,18 @@ class LocaleCookieRedirect extends Middleware public function handle(Request $request, Closure $next) { // If the request URL is ignored from localization. - if ($this->shouldIgnore($request)) - return $next($request); + if ($this->shouldIgnore($request)) return $next($request); $segment = $request->segment(1, null); - $locale = $request->cookie('locale', null); - if (localization()->isLocaleSupported($segment)) { + if ($this->localization->isLocaleSupported($segment)) return $next($request)->withCookie(cookie()->forever('locale', $segment)); - } + + $locale = $request->cookie('locale', null); if ($locale !== null && ! $this->isDefaultLocaleHidden($locale)) { - if ( ! is_null($redirect = $this->getLocalizedRedirect($locale))) { + if ( ! is_null($redirect = $this->getLocalizedRedirect($locale))) return $redirect->withCookie(cookie()->forever('locale', $segment)); - } } return $next($request); diff --git a/src/Middleware/LocaleSessionRedirect.php b/src/Middleware/LocaleSessionRedirect.php index 8da818f..a4d5af6 100644 --- a/src/Middleware/LocaleSessionRedirect.php +++ b/src/Middleware/LocaleSessionRedirect.php @@ -1,6 +1,5 @@ shouldIgnore($request)) - return $next($request); + if ($this->shouldIgnore($request)) return $next($request); $segment = $request->segment(1, null); $locale = session('locale', null); - if (localization()->isLocaleSupported($segment)) { + if ($this->localization->isLocaleSupported($segment)) { session()->put(['locale' => $segment]); return $next($request); } - elseif (localization()->isDefaultLocaleHiddenInUrl()) { - $locale = localization()->getDefaultLocale(); + elseif ($this->localization->isDefaultLocaleHiddenInUrl()) { + $locale = $this->localization->getDefaultLocale(); session()->put(compact('locale')); } if (is_string($locale) && ! $this->isDefaultLocaleHidden($locale)) { session()->reflash(); - $redirect = $this->getLocalizedRedirect($locale); - - if ( ! is_null($redirect)) return $redirect; + if ( ! is_null($redirect = $this->getLocalizedRedirect($locale))) + return $redirect; } return $next($request); diff --git a/src/Middleware/LocalizationRedirect.php b/src/Middleware/LocalizationRedirect.php index 4c58bb8..426f8fc 100644 --- a/src/Middleware/LocalizationRedirect.php +++ b/src/Middleware/LocalizationRedirect.php @@ -1,6 +1,5 @@ - * - * @todo: Refactoring */ class LocalizationRedirect extends Middleware { - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Handle an incoming request. @@ -29,8 +26,7 @@ class LocalizationRedirect extends Middleware public function handle(Request $request, Closure $next) { // If the request URL is ignored from localization. - if ($this->shouldIgnore($request)) - return $next($request); + if ($this->shouldIgnore($request)) return $next($request); if ($redirectUrl = $this->getRedirectionUrl($request)) { // Save any flashed data for redirect @@ -42,9 +38,9 @@ public function handle(Request $request, Closure $next) return $next($request); } - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Get redirection. @@ -57,11 +53,10 @@ protected function getRedirectionUrl(Request $request) { $locale = $request->segment(1, null); - if ($this->getSupportedLocales()->has($locale)) { + if ($this->getSupportedLocales()->has($locale)) return $this->isDefaultLocaleHidden($locale) - ? localization()->getNonLocalizedURL() + ? $this->localization->getNonLocalizedURL() : false; - } // If the current url does not contain any locale // The system redirect the user to the very same url "localized" we use the current locale to redirect him @@ -69,7 +64,7 @@ protected function getRedirectionUrl(Request $request) $this->getCurrentLocale() !== $this->getDefaultLocale() || ! $this->hideDefaultLocaleInURL() ) { - return localization()->getLocalizedURL(session('locale'), $request->fullUrl()); + return $this->localization->getLocalizedURL(session('locale'), $request->fullUrl()); } return false; diff --git a/src/Middleware/LocalizationRoutes.php b/src/Middleware/LocalizationRoutes.php index d8174be..0082ec8 100644 --- a/src/Middleware/LocalizationRoutes.php +++ b/src/Middleware/LocalizationRoutes.php @@ -1,6 +1,5 @@ shouldIgnore($request)) - return $next($request); + if ($this->shouldIgnore($request)) return $next($request); - localization()->setRouteNameFromRequest($request); + $this->localization->setRouteNameFromRequest($request); return $next($request); } diff --git a/src/Bases/Middleware.php b/src/Middleware/Middleware.php similarity index 71% rename from src/Bases/Middleware.php rename to src/Middleware/Middleware.php index df5c617..d535317 100644 --- a/src/Bases/Middleware.php +++ b/src/Middleware/Middleware.php @@ -1,5 +1,6 @@ -localization = $localization; + } + + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Get the default locale. @@ -35,7 +57,7 @@ abstract class Middleware extends BaseMiddleware */ public function getDefaultLocale() { - return localization()->getDefaultLocale(); + return $this->localization->getDefaultLocale(); } /** @@ -45,7 +67,7 @@ public function getDefaultLocale() */ public function getCurrentLocale() { - return localization()->getCurrentLocale(); + return $this->localization->getCurrentLocale(); } /** @@ -57,7 +79,7 @@ public function getCurrentLocale() */ public function getSupportedLocales() { - return localization()->getSupportedLocales(); + return $this->localization->getSupportedLocales(); } /** @@ -67,12 +89,12 @@ public function getSupportedLocales() */ protected function hideDefaultLocaleInURL() { - return localization()->isDefaultLocaleHiddenInUrl(); + return $this->localization->isDefaultLocaleHiddenInUrl(); } - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Check Methods + | ----------------------------------------------------------------- */ /** * Check is default locale hidden. @@ -106,20 +128,20 @@ protected function shouldIgnore($request) return false; } - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Get the redirection response. * * @param string $locale * - * @return RedirectResponse|null + * @return \Illuminate\Http\RedirectResponse|null */ protected function getLocalizedRedirect($locale) { - $localizedUrl = localization()->getLocalizedURL($locale); + $localizedUrl = $this->localization->getLocalizedURL($locale); if ( ! is_string($localizedUrl)) return null; @@ -132,7 +154,7 @@ protected function getLocalizedRedirect($locale) * @param string $url * @param int $code * - * @return RedirectResponse + * @return \Illuminate\Http\RedirectResponse */ protected function makeRedirectResponse($url, $code = 302) { diff --git a/src/Middleware/TranslationRedirect.php b/src/Middleware/TranslationRedirect.php index c4981f4..3b279eb 100644 --- a/src/Middleware/TranslationRedirect.php +++ b/src/Middleware/TranslationRedirect.php @@ -1,6 +1,5 @@ shouldIgnore($request)) - return $next($request); + if ($this->shouldIgnore($request)) return $next($request); - $translatedUrl = $this->getTranslatedUrl($request); - - if ( ! is_null($translatedUrl)) { - return $this->makeRedirectResponse($translatedUrl); - } - - return $next($request); + return is_null($translatedUrl = $this->getTranslatedUrl($request)) + ? $next($request) + : $this->makeRedirectResponse($translatedUrl); } - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Get translated URL. * - * @param Request $request + * @param \Illuminate\Http\Request $request * - * @return null|string + * @return string|null */ private function getTranslatedUrl(Request $request) { /** @var Route $route */ $route = $request->route(); - if ( ! ($route instanceof Route) || is_null($route->getName())) { + if ( ! ($route instanceof Route) || is_null($route->getName())) return null; - } - return $this->translateRoute( - $route->getName(), $route->parameters() - ); + return $this->translateRoute($route->getName(), $route->parameters()); } /** @@ -77,23 +68,16 @@ private function getTranslatedUrl(Request $request) * @param string $routeName * @param array $attributes * - * @return Route|null + * @return string|null */ public function translateRoute($routeName, $attributes = []) { - if (empty($attributes)) { - return null; - } + if (empty($attributes)) return null; - $transAttributes = $this->fireEvent( - $this->getCurrentLocale(), $routeName, $attributes - ); + $transAttributes = $this->fireEvent($this->getCurrentLocale(), $routeName, $attributes); - if ( - ! empty($transAttributes) && $transAttributes !== $attributes - ) { + if ( ! empty($transAttributes) && $transAttributes !== $attributes) return route($routeName, $transAttributes); - } return null; } @@ -109,17 +93,13 @@ public function translateRoute($routeName, $attributes = []) */ private function fireEvent($locale, $route, $attributes) { - $response = event(self::EVENT_NAME, [ - $locale, $route, $attributes - ]); + $response = event(self::EVENT_NAME, [$locale, $route, $attributes]); - if ( ! empty($response)) { + if ( ! empty($response)) $response = array_shift($response); - } - if (is_array($response)) { + if (is_array($response)) $attributes = array_merge($attributes, $response); - } return $attributes; } diff --git a/src/Providers/RoutingServiceProvider.php b/src/Providers/RoutingServiceProvider.php index 4cd87c4..9d46d4f 100644 --- a/src/Providers/RoutingServiceProvider.php +++ b/src/Providers/RoutingServiceProvider.php @@ -1,7 +1,7 @@ Middleware\LocaleSessionRedirect::class, + 'localization-cookie-redirect' => Middleware\LocaleCookieRedirect::class, + 'localization-redirect' => Middleware\LocalizationRedirect::class, + 'localized-routes' => Middleware\LocalizationRoutes::class, + 'translation-redirect' => Middleware\TranslationRedirect::class, + ]; /* ------------------------------------------------------------------------------------------------ | Main Functions @@ -29,12 +37,12 @@ class RoutingServiceProvider extends ServiceProvider */ /** * Register the service provider. - * - * @return void */ public function register() { $this->registerRouter(); + + parent::register(); } /* ------------------------------------------------------------------------------------------------ @@ -49,58 +57,5 @@ protected function registerRouter() $this->app->singleton('router', function ($app) { return new Router($app['events'], $app); }); - - $this->registerMiddlewares(); - } - - /** - * Register the middlewares. - */ - private function registerMiddlewares() - { - /** @var Router $router */ - $router = $this->app['router']; - $middlewares = [ - 'localization-session-redirect' => Middleware\LocaleSessionRedirect::class, - 'localization-cookie-redirect' => Middleware\LocaleCookieRedirect::class, - 'localization-redirect' => Middleware\LocalizationRedirect::class, - 'localized-routes' => Middleware\LocalizationRoutes::class, - 'translation-redirect' => Middleware\TranslationRedirect::class, - ]; - - foreach ($middlewares as $name => $class) { - $this->registerMiddleware($router, $name, $class); - } - } - - /** - * Register a middleware. - * - * @param Router $router - * @param string $name - * @param string $class - */ - private function registerMiddleware(Router $router, $name, $class) - { - $router->aliasMiddleware($name, $class); - - if ($this->getMiddleware($name)) { - $this->middleware[] = $name; - } - } - - /** - * Get the middleware status. - * - * @param string $name - * - * @return bool - */ - private function getMiddleware($name) - { - /** @var \Illuminate\Contracts\Config\Repository $config */ - $config = $this->app['config']; - - return (bool) $config->get("localization.route.middleware.{$name}", false); } } diff --git a/src/Providers/UtilitiesServiceProvider.php b/src/Providers/UtilitiesServiceProvider.php index fadf2db..b7557ff 100644 --- a/src/Providers/UtilitiesServiceProvider.php +++ b/src/Providers/UtilitiesServiceProvider.php @@ -67,9 +67,7 @@ private function registerRouteTranslator() */ private function registerLocalesManager() { - $this->singleton(LocalesManagerContract::class, function ($app) { - return new LocalesManager($app); - }); + $this->singleton(LocalesManagerContract::class, LocalesManager::class); $this->singleton('arcanedev.localization.locales-manager', LocalesManagerContract::class); } diff --git a/src/Routing/Router.php b/src/Routing/Router.php index befbfc1..3e4de27 100644 --- a/src/Routing/Router.php +++ b/src/Routing/Router.php @@ -58,7 +58,7 @@ public function localizedGroup(Closure $callback, $attributes = []) public function transGet($trans, $action) { return $this->get( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -73,7 +73,7 @@ public function transGet($trans, $action) public function transPost($trans, $action) { return $this->post( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -88,7 +88,7 @@ public function transPost($trans, $action) public function transPut($trans, $action) { return $this->put( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -103,7 +103,7 @@ public function transPut($trans, $action) public function transPatch($trans, $action) { return $this->patch( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -118,7 +118,7 @@ public function transPatch($trans, $action) public function transDelete($trans, $action) { return $this->delete( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -133,7 +133,7 @@ public function transDelete($trans, $action) public function transOptions($trans, $action) { return $this->options( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } @@ -148,7 +148,23 @@ public function transOptions($trans, $action) public function transAny($trans, $action) { return $this->any( - localization()->transRoute($trans), $action + $this->transRoute($trans), $action ); } + + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- + */ + /** + * Translate the route. + * + * @param string $key + * + * @return string + */ + private function transRoute($key) + { + return localization()->transRoute($key); + } } diff --git a/src/Traits/LocalizationKernelTrait.php b/src/Traits/LocalizationKernelTrait.php index ffb0e55..9fd94f5 100644 --- a/src/Traits/LocalizationKernelTrait.php +++ b/src/Traits/LocalizationKernelTrait.php @@ -6,57 +6,9 @@ * @package Arcanedev\Localization\Traits * @author ARCANEDEV * - * @property \Illuminate\Foundation\Application app - * @property \Arcanedev\Localization\Routing\Router router - * @property array middlewareGroups - * @property array routeMiddleware + * @deprecated since v1.0.3 */ trait LocalizationKernelTrait { - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ - */ - /** - * Get the route dispatcher callback. - * - * @return \Closure - */ - protected function dispatchToRouter() - { - $this->router = $this->app['router']; - - $this->registerMiddlewareGroups(); - $this->registerMiddleware(); - - return parent::dispatchToRouter(); - } - - /* ------------------------------------------------------------------------------------------------ - | Middleware Functions - | ------------------------------------------------------------------------------------------------ - */ - /** - * Register middleware groups to router (since Laravel 5.2). - */ - protected function registerMiddlewareGroups() - { - if (property_exists($this, 'middlewareGroups')) { - foreach ($this->middlewareGroups as $key => $middleware) { - $this->router->middlewareGroup($key, $middleware); - } - } - } - - /** - * Register middleware to router. - */ - protected function registerMiddleware() - { - foreach ($this->routeMiddleware as $key => $middleware) { - method_exists($this->router, 'aliasMiddleware') - ? $this->router->aliasMiddleware($key, $middleware) - : $this->router->middleware($key, $middleware);; - } - } + // } diff --git a/src/Utilities/LocalesManager.php b/src/Utilities/LocalesManager.php index 8f8bf0e..09de552 100644 --- a/src/Utilities/LocalesManager.php +++ b/src/Utilities/LocalesManager.php @@ -5,7 +5,7 @@ use Arcanedev\Localization\Entities\LocaleCollection; use Arcanedev\Localization\Exceptions\UndefinedSupportedLocalesException; use Arcanedev\Localization\Exceptions\UnsupportedLocaleException; -use Illuminate\Contracts\Foundation\Application; +use Illuminate\Contracts\Foundation\Application as ApplicationContract; /** * Class LocalesManager @@ -15,9 +15,9 @@ */ class LocalesManager implements LocalesManagerContract { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Properties - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Default locale. @@ -50,16 +50,16 @@ class LocalesManager implements LocalesManagerContract */ private $app; - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Constructor - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** - * Create LocaleManager instance. + * LocalesManager constructor. * * @param \Illuminate\Contracts\Foundation\Application $app */ - public function __construct(Application $app) + public function __construct(ApplicationContract $app) { $this->app = $app; $this->locales = new LocaleCollection; @@ -78,9 +78,9 @@ private function load() $this->setDefaultLocale(); } - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Set and return current locale. @@ -103,7 +103,7 @@ public function setLocale($locale = null) else { // if the first segment/locale passed is not valid the system would ask which locale have to take // it could be taken by the browser depending on your configuration - $locale = null; + $locale = null; $this->getCurrentOrDefaultLocale(); } @@ -133,9 +133,8 @@ public function getDefaultLocale() */ public function setDefaultLocale($defaultLocale = null) { - if (is_null($defaultLocale)) { - $defaultLocale = $this->app->getLocale(); - } + if (is_null($defaultLocale)) + $defaultLocale = $this->config()->get('app.locale'); $this->isDefaultLocaleSupported($defaultLocale); $this->defaultLocale = $defaultLocale; @@ -151,13 +150,11 @@ public function setDefaultLocale($defaultLocale = null) */ public function getCurrentLocale() { - if ( ! is_null($this->currentLocale)) { + if ( ! is_null($this->currentLocale)) return $this->currentLocale; - } - if ($this->useAcceptLanguageHeader()) { + if ($this->useAcceptLanguageHeader()) return $this->negotiateLocale(); - } // Get application default language return $this->getDefaultLocale(); @@ -214,9 +211,7 @@ public function getSupportedLocales() */ public function getSupportedLocalesKeys() { - $supportedLocales = $this->getSupportedLocales(); - - return $supportedLocales->keys()->toArray(); + return $this->getSupportedLocales()->keys()->toArray(); } /** @@ -226,13 +221,12 @@ public function getSupportedLocalesKeys() * * @return self * - * @throws UndefinedSupportedLocalesException + * @throws \Arcanedev\Localization\Exceptions\UndefinedSupportedLocalesException */ public function setSupportedLocales(array $supportedLocales) { - if ( ! is_array($supportedLocales) || empty($supportedLocales)) { + if ( ! is_array($supportedLocales) || empty($supportedLocales)) throw new UndefinedSupportedLocalesException; - } $this->supportedLocales = $this->filterLocales($supportedLocales); @@ -242,7 +236,7 @@ public function setSupportedLocales(array $supportedLocales) /** * Get config repository. * - * @return \Illuminate\Contracts\Config\Repository Config + * @return \Illuminate\Contracts\Config\Repository */ private function config() { @@ -279,14 +273,13 @@ private function getConfig($name, $default = null) */ private function negotiateLocale() { - $negotiator = new Negotiator($this->getDefaultLocale(), $this->getSupportedLocales()); - - return $negotiator->negotiate($this->request()); + return Negotiator::make($this->getDefaultLocale(), $this->getSupportedLocales()) + ->negotiate($this->request()); } - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Methods Functions + | ----------------------------------------------------------------- */ /** * Check if default is supported. @@ -297,11 +290,10 @@ private function negotiateLocale() */ public function isDefaultLocaleSupported($defaultLocale) { - if ( ! $this->isSupportedLocale($defaultLocale)) { + if ( ! $this->isSupportedLocale($defaultLocale)) throw new UnsupportedLocaleException( "Laravel default locale [{$defaultLocale}] is not in the `supported-locales` array." ); - } } /** @@ -345,17 +337,16 @@ public function getCurrentOrDefaultLocale() { // If we reached this point and isDefaultLocaleHiddenInUrl is true we have to assume we are routing // to a default locale route. - if ($this->isDefaultLocaleHiddenInUrl()) { + if ($this->isDefaultLocaleHiddenInUrl()) $this->setCurrentLocale($this->getDefaultLocale()); - } // But if isDefaultLocaleHiddenInUrl is false, we have to retrieve it from the browser... return $this->getCurrentLocale(); } - /* ------------------------------------------------------------------------------------------------ - | Other Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Filter locale collection. diff --git a/src/Utilities/Negotiator.php b/src/Utilities/Negotiator.php index 18dc21f..b6e3b1b 100644 --- a/src/Utilities/Negotiator.php +++ b/src/Utilities/Negotiator.php @@ -24,9 +24,9 @@ */ class Negotiator implements NegotiatorContract { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Properties - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Default Locale. @@ -49,9 +49,9 @@ class Negotiator implements NegotiatorContract */ private $request; - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Constructor + | ----------------------------------------------------------------- */ /** * Make Negotiator instance. @@ -65,10 +65,23 @@ public function __construct($defaultLocale, LocaleCollection $supportedLanguages $this->supportedLocales = $supportedLanguages; } - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- + */ + /** + * Make Negotiator instance. + * + * @param string $defaultLocale + * @param \Arcanedev\Localization\Entities\LocaleCollection $supportedLanguages + * + * @return self */ + public static function make($defaultLocale, LocaleCollection $supportedLanguages) + { + return new static($defaultLocale, $supportedLanguages); + } + /** * Negotiate the request. * @@ -80,17 +93,14 @@ public function negotiate(Request $request) { $this->request = $request; - $locale = $this->getFromAcceptedLanguagesHeader(); - - if ( ! is_null($locale)) return $locale; - - $locale = $this->getFromHttpAcceptedLanguagesServer(); - - if ( ! is_null($locale)) return $locale; + if ( ! is_null($locale = $this->getFromAcceptedLanguagesHeader())) + return $locale; - $locale = $this->getFromRemoteHostServer(); + if ( ! is_null($locale = $this->getFromHttpAcceptedLanguagesServer())) + return $locale; - if ( ! is_null($locale)) return $locale; + if ( ! is_null($locale = $this->getFromRemoteHostServer())) + return $locale; // TODO: Adding negotiate form IP Address ?? @@ -128,16 +138,13 @@ private function getFromHttpAcceptedLanguagesServer() $httpAcceptLanguage = $this->request->server('HTTP_ACCEPT_LANGUAGE'); // @codeCoverageIgnoreStart - if ( ! class_exists('Locale') || empty($httpAcceptLanguage)) { + if ( ! class_exists('Locale') || empty($httpAcceptLanguage)) return null; - } // @codeCoverageIgnoreEnd $locale = Locale::acceptFromHttp($httpAcceptLanguage); - if ($this->isSupported($locale)) { - return $locale; - } + if ($this->isSupported($locale)) return $locale; return null; } @@ -159,7 +166,7 @@ private function getFromRemoteHostServer() } /* ------------------------------------------------------------------------------------------------ - | Check Functions + | Check Methods | ------------------------------------------------------------------------------------------------ */ /** @@ -172,14 +179,12 @@ private function getFromRemoteHostServer() private function inSupportedLocales(array $matches) { foreach (array_keys($matches) as $locale) { - if ($this->isSupported($locale)) - return $locale; + if ($this->isSupported($locale)) return $locale; // Search for acceptable locale by 'regional' => 'fr_FR' match. foreach ($this->supportedLocales as $key => $entity) { /** @var \Arcanedev\Localization\Entities\Locale $entity */ - if ($entity->regional() == $locale) - return $key; + if ($entity->regional() == $locale) return $key; } } @@ -277,18 +282,15 @@ private function retrieveGenericMatches($acceptLanguages, &$matches) */ private function getQualityFactor($locale, $option) { - if (isset($option[1])) { + if (isset($option[1])) return (float) str_replace('q=', '', $option[1]); - } // Assign default low weight for generic values - if ($locale === '*/*') { + if ($locale === '*/*') return 0.01; - } - if (substr($locale, -1) === '*') { + if (substr($locale, -1) === '*') return 0.02; - } return null; } diff --git a/src/Utilities/RouteTranslator.php b/src/Utilities/RouteTranslator.php index 3466f0d..65a4c58 100644 --- a/src/Utilities/RouteTranslator.php +++ b/src/Utilities/RouteTranslator.php @@ -13,9 +13,9 @@ */ class RouteTranslator implements RouteTranslatorContract { - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Properties - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * The translator instance. @@ -38,9 +38,9 @@ class RouteTranslator implements RouteTranslatorContract */ protected $translatedRoutes = []; - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Constructor - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Create RouteTranslator instance. @@ -52,9 +52,9 @@ public function __construct(Translator $translator) $this->translator = $translator; } - /* ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- | Getters & Setters - | ------------------------------------------------------------------------------------------------ + | ----------------------------------------------------------------- */ /** * Get current route. @@ -75,9 +75,8 @@ public function getCurrentRoute() */ public function setCurrentRoute($currentRoute) { - if (is_string($currentRoute)) { + if (is_string($currentRoute)) $this->currentRoute = $currentRoute; - } return $this; } @@ -92,9 +91,9 @@ public function getTranslatedRoutes() return $this->translatedRoutes; } - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Translate routes and save them to the translated routes array (used in the localize route filter). @@ -106,9 +105,8 @@ public function getTranslatedRoutes() */ public function trans($route, $locale = null) { - if ( ! in_array($route, $this->translatedRoutes)) { + if ( ! in_array($route, $this->translatedRoutes)) $this->translatedRoutes[] = $route; - } return $this->translate($route, $locale); } @@ -166,9 +164,7 @@ public function getRouteNameFromPath($uri, $locale) foreach ($this->translatedRoutes as $routeName) { $url = Url::substituteAttributes($attributes, $this->translate($routeName)); - if ($url === $uri) { - return $routeName; - } + if ($url === $uri) return $routeName; } return false; @@ -186,9 +182,8 @@ public function findTranslatedRouteByPath($path, $locale) { // check if this url is a translated url foreach ($this->translatedRoutes as $route) { - if ($this->translate($route, $locale) == rawurldecode($path)) { + if ($this->translate($route, $locale) == rawurldecode($path)) return $route; - } } return false; @@ -205,24 +200,21 @@ public function findTranslatedRouteByPath($path, $locale) * * @return string */ - public function getUrlFromRouteName($locale, $defaultLocale, $transKey, $attributes = [], $defaultHidden = false) - { - if ( ! is_string($locale)) { + public function getUrlFromRouteName( + $locale, $defaultLocale, $transKey, $attributes = [], $defaultHidden = false + ) { + if ( ! is_string($locale)) $locale = $defaultLocale; - } - $route = ''; + $url = ''; - if ( ! ($locale === $defaultLocale && $defaultHidden)) { - $route = '/' . $locale; - } + if ( ! ($locale === $defaultLocale && $defaultHidden)) + $url = '/'.$locale; - if ($this->hasTranslation($transKey, $locale)) { - $translation = $this->trans($transKey, $locale); - $route = Url::substituteAttributes($attributes, $route . '/' . $translation); - } + if ($this->hasTranslation($transKey, $locale)) + $url = Url::substituteAttributes($attributes, $url.'/'.$this->trans($transKey, $locale)); - return $route; + return $url; } /** @@ -237,26 +229,24 @@ public function getUrlFromRouteName($locale, $defaultLocale, $transKey, $attribu */ private function translate($key, $locale = null) { - if (is_null($locale)) { + if (is_null($locale)) $locale = $this->translator->getLocale(); - } $translation = $this->translator->trans($key, [], $locale); // @codeCoverageIgnoreStart - if ( ! is_string($translation)) { + if ( ! is_string($translation)) throw new InvalidTranslationException( - "The translation key [$key] for locale [$locale] should return a string value." + "The translation key [{$key}] for locale [{$locale}] should return a string value." ); - } // @codeCoverageIgnoreEnd return (string) $translation; } - /* ------------------------------------------------------------------------------------------------ - | Check Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Check Methods + | ----------------------------------------------------------------- */ /** * Check if has current route. diff --git a/src/Utilities/Url.php b/src/Utilities/Url.php index ea30f89..a0e75cf 100644 --- a/src/Utilities/Url.php +++ b/src/Utilities/Url.php @@ -14,9 +14,9 @@ */ class Url implements UrlContract { - /* ------------------------------------------------------------------------------------------------ - | Main Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Main Methods + | ----------------------------------------------------------------- */ /** * Extract attributes for current url. @@ -27,9 +27,9 @@ class Url implements UrlContract */ public static function extractAttributes($url = false) { - $parse = parse_url($url); - $path = isset($parse['path']) ? explode('/', $parse['path']) : []; - $url = []; + $parse = parse_url($url); + $path = isset($parse['path']) ? explode('/', $parse['path']) : []; + $url = []; foreach ($path as $segment) { if ( ! empty($segment)) $url[] = $segment; @@ -52,9 +52,8 @@ public static function extractAttributes($url = false) public static function substituteAttributes(array $attributes, $uri) { foreach ($attributes as $key => $value) { - if ($value instanceof RouteBindable) { + if ($value instanceof RouteBindable) $value = $value->getWildcardValue(); - } $uri = str_replace(['{' . $key . '?}', '{' . $key . '}'], $value, $uri); } @@ -83,9 +82,9 @@ public static function unparse($parsed) return $url; } - /* ------------------------------------------------------------------------------------------------ - | Extract Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Extract Methods + | ----------------------------------------------------------------- */ /** * Extract attributes from routes. @@ -106,9 +105,8 @@ private static function extractAttributesFromRoutes($url, $routes) */ $request = Request::create(implode('/', $url)); - if ( ! $route->matches($request)) { + if ( ! $route->matches($request)) continue; - } $match = self::hasAttributesFromUriPath($url, $route->uri(), $attributes); @@ -184,9 +182,9 @@ private static function extractAttributesFromSegment($url, $path, $i, $j, $segme } } - /* ------------------------------------------------------------------------------------------------ - | Unparse Functions - | ------------------------------------------------------------------------------------------------ + /* ----------------------------------------------------------------- + | Other Methods + | ----------------------------------------------------------------- */ /** * Check parsed URL. @@ -195,17 +193,17 @@ private static function extractAttributesFromSegment($url, $path, $i, $j, $segme */ private static function checkParsedUrl(array &$parsed) { - $scheme =& $parsed['scheme']; - $user =& $parsed['user']; - $pass =& $parsed['pass']; - $host =& $parsed['host']; - $port =& $parsed['port']; - $path =& $parsed['path']; - $path = '/' . ltrim($path, '/'); // If / is missing for path. - $query =& $parsed['query']; - $fragment =& $parsed['fragment']; - - $parsed = compact( + $scheme =& $parsed['scheme']; + $user =& $parsed['user']; + $pass =& $parsed['pass']; + $host =& $parsed['host']; + $port =& $parsed['port']; + $path =& $parsed['path']; + $path = '/'.ltrim($path, '/'); // If / is missing for path. + $query =& $parsed['query']; + $fragment =& $parsed['fragment']; + + $parsed = compact( 'scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment' ); } @@ -219,13 +217,9 @@ private static function checkParsedUrl(array &$parsed) */ private static function getUrl(array $parsed) { - $url = ''; - - if (strlen($parsed['scheme'])) { - $url = $parsed['scheme'] . ':' . self::getHierPart($parsed); - } - - return $url; + return strlen($parsed['scheme']) + ? $parsed['scheme'].':'.self::getHierPart($parsed) + : ''; } /** @@ -237,14 +231,9 @@ private static function getUrl(array $parsed) */ private static function getHierPart(array $parsed) { - $path = $parsed['path']; - $authority = self::getAuthority($parsed); - - if (strlen($authority)) { - $path = '//' . $authority . $path; - } - - return $path; + return strlen($authority = self::getAuthority($parsed)) + ? '//'.$authority.$parsed['path'] + : $parsed['path']; } /** @@ -256,14 +245,11 @@ private static function getHierPart(array $parsed) */ private static function getAuthority(array $parsed) { - $userInfo = self::getUserInfo($parsed); - $host = self::getHost($parsed); + $host = self::getHost($parsed); - if (strlen($userInfo)) { - return $userInfo . '@' . $host; - } - - return $host; + return strlen($userInfo = self::getUserInfo($parsed)) + ? $userInfo.'@'.$host + : $host; } /** @@ -275,13 +261,9 @@ private static function getAuthority(array $parsed) */ private static function getUserInfo(array $parsed) { - $userInfo = ''; - - if (strlen($parsed['pass'])) { - $userInfo = $parsed['user'] . ':' . $parsed['pass']; - } - - return $userInfo; + return strlen($parsed['pass']) + ? $parsed['user'].':'.$parsed['pass'] + : ''; } /** @@ -293,13 +275,9 @@ private static function getUserInfo(array $parsed) */ private static function getHost(array $parsed) { - $host = $parsed['host']; - - if ( ! empty((string) $parsed['port'])) { - $host = $host . ':' . $parsed['port']; - } - - return $host; + return empty((string) $parsed['port']) + ? $parsed['host'] + : $parsed['host'].':'.$parsed['port']; } /** @@ -311,13 +289,7 @@ private static function getHost(array $parsed) */ private static function getQuery(array $parsed) { - $query = ''; - - if (strlen($parsed['query'])) { - $query = '?' . $parsed['query']; - } - - return $query; + return strlen($parsed['query']) ? '?'.$parsed['query'] : ''; } /** @@ -329,12 +301,8 @@ private static function getQuery(array $parsed) */ private static function getFragment(array $parsed) { - $fragment = ''; - - if (strlen($parsed['fragment'])) { - $fragment = '#' . $parsed['fragment']; - } - - return $fragment; + return strlen($parsed['fragment']) + ? '#'.$parsed['fragment'] + : ''; } }