diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 8210968..dd923a2 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,3 +1,3 @@ # Security Policy -If you discover any security related issues, please email hi@codebar.ch instead of using the issue tracker. +If you discover any security related issues, please email info@codebar.ch instead of using the issue tracker. diff --git a/.github/workflows/php-cs-fixer.yml b/.github/workflows/php-cs-fixer.yml index f062062..9910297 100644 --- a/.github/workflows/php-cs-fixer.yml +++ b/.github/workflows/php-cs-fixer.yml @@ -1,6 +1,6 @@ name: Check & fix styling -on: [ push ] +on: [push] jobs: style: diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index d26db30..ce9cb2a 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -1,4 +1,4 @@ -name: Tests +name: run-tests on: [push, pull_request] @@ -57,13 +57,4 @@ jobs: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest - name: Execute tests - run: vendor/bin/phpunit --coverage-clover=coverage.xml - - - name: Upload test coverage to Codecov - uses: codecov/codecov-action@v1 - with: - token: ${{ secrets.CODECOV_TOKEN }} - file: ./coverage.xml - name: laravel-prerender - flags: P${{ matrix.php }},L${{ matrix.laravel }},${{ matrix.dependency-version }},${{ matrix.os }} - fail_ci_if_error: true + run: vendor/bin/phpunit diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ef0aac0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,27 @@ +# Changelog + +All notable changes to `laravel-prerender` will be documented in this file. + +## Not released + +## 3.1.0 - 2021-04-28 + +- Added additional [user agents](https://github.com/codebar-ag/laravel-prerender/commit/a8706a678b2f990cd1f108866c7d2b10f4b4e658) +- Refactored +- Moved the default branch to `main` + +## 3.0.3 - 2021-02-09 + +- Support for PHP 8.0 added. + +## 3.0.2 - 2020-09-18 + +- Updated README.md + +## 3.0.1 - 2020-09-14 + +- Updated README.md + +## 3.0.0 - 2020-09-14 + +- Support for Laravel 8 added. diff --git a/README.md b/README.md index c0e96b8..9e9c6e2 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,280 @@ -Laravel | Prerender.io ![Tests](https://github.com/codebar-ag/Laravel-Prerender/workflows/Tests/badge.svg) ![codecov.io](https://codecov.io/github/codebar-ag/Laravel-Prerender/coverage.svg?branch=master) -=========================== + -## Credits -This package is a clone from [jeroennoten/Laravel-Prerender](https://github.com/jeroennoten/Laravel-Prerender) with [jeroennoten](https://github.com/jeroennoten) as author. [CasperLaiTW](https://github.com/CasperLaiTW) provided Laravel 6,7 & 8 Support by an unmerged (14th September 2020) Pull-Request. +[![Latest Version on Packagist](https://img.shields.io/packagist/v/codebar-ag/laravel-prerender.svg?style=flat-square)](https://packagist.org/packages/codebar-ag/laravel-prerender) +[![Total Downloads](https://img.shields.io/packagist/dt/codebar-ag/laravel-prerender.svg?style=flat-square)](https://packagist.org/packages/codebar-ag/laravel-prerender) +[![run-tests](https://github.com/codebar-ag/laravel-prerender/actions/workflows/run-tests.yml/badge.svg)](https://github.com/codebar-ag/laravel-prerender/actions/workflows/run-tests.yml) +[![Check & fix styling](https://github.com/codebar-ag/laravel-prerender/actions/workflows/php-cs-fixer.yml/badge.svg)](https://github.com/codebar-ag/laravel-prerender/actions/workflows/php-cs-fixer.yml) -## Laravel Support -This package currently only supports >= Laravel 6 && >= PHP 5.5.9 If you're looking for an older version checkout [jeroennoten/Laravel-Prerender](https://github.com/jeroennoten/Laravel-Prerender). +This package was developed to give you a quick start to integrate with the +Prerender.io service in your Laravel application. -## Introduction -Modern search engines like Google are constantly trying to visit and render your website. Unfortunately, they don't execute javascript. So the content of your website is not getting indexed. Prerender helps you out there. A middleware intercepts requests to your Laravel website or application from crawlers. It then makes a call to the external Prerender Service to get the static HTML instead of the javascript for that page. It is a perfect match for Vue JS, Angular JS, Backbone JS, Ember JS and any other Javascript Framework. +## 🙇 Credits -Prerender adheres to google's `_escaped_fragment_` proposal, which we recommend you use. It's easy: -- Just add `` to the `` of all of your pages -- If you use hash urls (#), change them to the hash-bang (#!), but you can also use HTML5's push-state -- That's it! Perfect SEO on javascript pages. +This package is a clone from [jeroennoten/Laravel-Prerender](https://github.com/jeroennoten/Laravel-Prerender) +with [jeroennoten](https://github.com/jeroennoten) as the original author. +[CasperLaiTW](https://github.com/CasperLaiTW) provided Laravel 6,7 & 8 +compatibility by an unmerged (14th September 2020) Pull-Request. -## Installation +## 💡 What is Prerender.io? -Require this package run: -``` +The Prerender.io middleware will check each request to see if it's a from a +crawler. If it is a request from a crawler, the middleware will send a request +to Prerender.io for the static HTML of that page. If not, the request will +continue on to your normal server routes. The crawler never knows that you are +using Prerender.io since the response always goes through your server. + +> Google now recommends that you use Prerender.io in their +> [Dynamic Rendering](https://docs.prerender.io/article/9-google-support) +> documentation! + +## 🛠 Requirements + +- PHP: `^7.2` +- Laravel: `^6` +- Prerender.io access + +## ⚙️ Installation + +You can install the package via composer: + +```shell composer require codebar-ag/laravel-prerender ``` -Apply the Prerender Middleware to your app/Http/Middleware/Kernel.php or routes/web.php +If you want to make use of the Prerender.io service, add the following to your `.env` file: -``` -CodebarAg\LaravelPrerender\PrerenderMiddleware; +```dotenv +PRERENDER_TOKEN=token ``` -If you want to make use of the prerender.io service, add the following to your `.env` file: +Or if you are using a self-hosted service, add the server address in the `.env` file. - PRERENDER_TOKEN=yoursecrettoken +```dotenv +PRERENDER_URL=https://prerender.services +``` -If you are using a self-hosted service, add the server address in the `.env` file. +That's it. Every GET-Request from a crawler will be prerendered. - PRERENDER_URL=http://example.com +## ✋ Disable the service You can disable the service by adding the following to your `.env` file: - PRERENDER_ENABLE=false +```dotenv +PRERENDER_ENABLE=false +``` This may be useful for your local development environment. -## How it works +## ✏️ How it works + 1. The middleware checks to make sure we should show a prerendered page - 1. The middleware checks if the request is from a crawler (`_escaped_fragment_` or agent string) + 1. The middleware checks if the request is from a crawler (agent string or `_escaped_fragment_`) 2. The middleware checks to make sure we aren't requesting a resource (js, css, etc...) 3. (optional) The middleware checks to make sure the url is in the whitelist 4. (optional) The middleware checks to make sure the url isn't in the blacklist 2. The middleware makes a `GET` request to the [prerender service](https://github.com/prerender/prerender) (phantomjs server) for the page's prerendered HTML 3. Return the HTML to the crawler -# Customization -To customize the whitelist and the blacklist, you first have to publish the configuration file: +## 🔧 Configuration file + +You can publish the config file with: + +```shell +php artisan vendor:publish --provider="CodebarAg\LaravelPrerender\LaravelPrerenderServiceProvider" +``` + +Afterwards you can customize the Whitelist/Blacklist on your own. + +This is the contents of the published config file: + +```php + env('PRERENDER_ENABLE', true), + + /* + |-------------------------------------------------------------------------- + | Prerender URL + |-------------------------------------------------------------------------- + | + | This is the prerender URL to the service that prerenders the pages. + | By default, Prerender's hosted service on prerender.io is used + | (https://service.prerender.io). But you can also set it to your + | own server address. + | + */ + + 'prerender_url' => env('PRERENDER_URL', 'https://service.prerender.io'), + + /* + |-------------------------------------------------------------------------- + | Return soft HTTP status codes + |-------------------------------------------------------------------------- + | + | By default Prerender returns soft HTTP codes. If you would like it to + | return the real ones in case of Redirection (3xx) or status Not Found (404), + | set this parameter to false. + | Keep in mind that returning real HTTP codes requires appropriate meta tags + | to be set. For more details, see github.com/prerender/prerender#httpheaders + | + */ + + 'prerender_soft_http_codes' => env('PRERENDER_SOFT_HTTP_STATUS_CODES', true), + + /* + |-------------------------------------------------------------------------- + | Prerender Token + |-------------------------------------------------------------------------- + | + | If you use prerender.io as service, you need to set your prerender.io + | token here. It will be sent via the X-Prerender-Token header. If + | you do not provide a token, the header will not be added. + | + */ + + 'prerender_token' => env('PRERENDER_TOKEN'), - $ php artisan vendor:publish --provider="CodebarAg\LaravelPrerender\LaravelPrerenderServiceProvider" + /* + |-------------------------------------------------------------------------- + | Prerender Whitelist + |-------------------------------------------------------------------------- + | + | Whitelist paths or patterns. You can use asterix syntax, or regular + | expressions (without start and end markers). If a whitelist is supplied, + | only url's containing a whitelist path will be prerendered. An empty + | array means that all URIs will pass this filter. Note that this is the + | full request URI, so including starting slash and query parameter string. + | See github.com/JeroenNoten/Laravel-Prerender for an example. + | + */ -### Whitelist + 'whitelist' => [], + + /* + |-------------------------------------------------------------------------- + | Prerender Blacklist + |-------------------------------------------------------------------------- + | + | Blacklist paths to exclude. You can use asterix syntax, or regular + | expressions (without start and end markers). If a blacklist is supplied, + | all url's will be prerendered except ones containing a blacklist path. + | By default, a set of asset extentions are included (this is actually only + | necessary when you dynamically provide assets via routes). Note that this + | is the full request URI, so including starting slash and query parameter + | string. See github.com/JeroenNoten/Laravel-Prerender for an example. + | + */ + + 'blacklist' => [ + '*.js', + '*.css', + '*.xml', + '*.less', + '*.png', + '*.jpg', + '*.jpeg', + '*.svg', + '*.gif', + '*.pdf', + '*.doc', + '*.txt', + '*.ico', + '*.rss', + '*.zip', + '*.mp3', + '*.rar', + '*.exe', + '*.wmv', + '*.doc', + '*.avi', + '*.ppt', + '*.mpg', + '*.mpeg', + '*.tif', + '*.wav', + '*.mov', + '*.psd', + '*.ai', + '*.xls', + '*.mp4', + '*.m4a', + '*.swf', + '*.dat', + '*.dmg', + '*.iso', + '*.flv', + '*.m4v', + '*.torrent', + '*.eot', + '*.ttf', + '*.otf', + '*.woff', + '*.woff2' + ], + + /* + |-------------------------------------------------------------------------- + | Crawler User Agents + |-------------------------------------------------------------------------- + | + | Requests from crawlers that do not support _escaped_fragment_ will + | nevertheless be served with prerendered pages. You can customize + | the list of crawlers here. + | + */ + + 'crawler_user_agents' => [ + 'googlebot', + 'yahoo', + 'bingbot', + 'yandex', + 'baiduspider', + 'facebookexternalhit', + 'twitterbot', + 'rogerbot', + 'linkedinbot', + 'embedly', + 'bufferbot', + 'quora link preview', + 'showyoubot', + 'outbrain', + 'pinterest', + 'pinterest/0.', + 'developers.google.com/+/web/snippet', + 'www.google.com/webmasters/tools/richsnippets', + 'slackbot', + 'vkShare', + 'W3C_Validator', + 'redditbot', + 'Applebot', + 'WhatsApp', + 'flipboard', + 'tumblr', + 'bitlybot', + 'SkypeUriPreview', + 'nuzzel', + 'Discordbot', + 'Google Page Speed', + 'Qwantify' + ], + +]; +``` + +### 🤍 Whitelist Whitelist paths or patterns. You can use asterix syntax. If a whitelist is supplied, only url's containing a whitelist path will be prerendered. @@ -70,11 +288,11 @@ Note that this is the full request URI, so including starting slash and query pa ], ``` -### Blacklist +### 🖤 Blacklist Blacklist paths to exclude. You can use asterix syntax. If a blacklist is supplied, all url's will be prerendered except ones containing a blacklist path. -By default, a set of asset extentions are included (this is actually only necessary when you dynamically provide assets via routes). +By default, a set of asset extensions are included (this is actually only necessary when you dynamically provide assets via routes). Note that this is the full request URI, so including starting slash and query parameter string. ```php @@ -84,14 +302,60 @@ Note that this is the full request URI, so including starting slash and query pa ], ``` -## Contributing +## 🚧 Local testing + +> Based on the [Getting started](https://docs.prerender.io/article/15-getting-started) +> guide in the Prerender.io documentation. + +1. Download and run the prerender Server locally +```shell +git clone https://github.com/prerender/prerender.git +cd prerender +npm clean-install +node server.js +``` + +The default port is 3000. You can start the node server on a different port +like this: + +```shell +PORT=3333 node server.js +``` + +2. Set the prerender URL: + +```dotenv +PRERENDER_URL=http://localhost:3000 +``` + +3. (Optional) Open your browser and visit the following URL. Make sure to + change `domain.test` to your local domain: + +``` +http://localhost:3000/render?url=https://domain.test +``` + +4. Test your page as a crawler. Make sure to change `domain.test` to your local + domain: + +```shell +curl -A Googlebot https://domain.test +``` + +6. 🎉 You made it. You should see your prerendered html! + +## 📝 Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## ✏️ Contributing Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. -## Security +## 🧑‍💻 Security Vulnerabilities -If you discover any security related issues, please email helpdesk@codebar.ch instead of using the issue tracker. +Please review [our security policy](.github/SECURITY.md) on how to report security vulnerabilities. -## License +## 🎭 License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json index 3f31c67..060767c 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,11 @@ - { "name": "codebar-ag/laravel-prerender", "description": "Laravel middleware for prerendering javascript-rendered pages on the fly for SEO", - "keywords": ["laravel", "prerender"], + "keywords": [ + "laravel", + "prerender", + "codebar-ag" + ], "homepage": "https://github.com/codebar-ag/Laravel-Prerender", "license": "MIT", "authors": [ @@ -16,6 +19,12 @@ "name": "Casper Lai", "email": "casper.lai@sleepingdesign.com", "role": "Developer" + }, + { + "name": "Ruslan Steiger", + "email": "ruslan.steiger@codebar.ch", + "homepage": "https://www.codebar.ch", + "role": "Developer" } ], "require": { @@ -23,12 +32,11 @@ "illuminate/support": "^6.0|^7.0|^8.0", "guzzlehttp/guzzle": "^6.0|^7.0", "symfony/psr-http-message-bridge": "^1.3|^2.0" - }, "require-dev": { - "phpunit/phpunit": "^8.4|^9.0", + "friendsofphp/php-cs-fixer": "^2.16", "orchestra/testbench": "^4.0|^5.0|^6.0", - "friendsofphp/php-cs-fixer": "^2.16" + "phpunit/phpunit": "^8.4|^9.0" }, "autoload": { "psr-4": { @@ -41,7 +49,6 @@ } }, "scripts": { - "psalm": "vendor/bin/psalm", "test": "vendor/bin/phpunit", "test-coverage": "vendor/bin/phpunit --coverage-html coverage", "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes --config=.php_cs" diff --git a/config/prerender.php b/config/prerender.php index ee67e08..ef64691 100644 --- a/config/prerender.php +++ b/config/prerender.php @@ -1,4 +1,6 @@ - env('PRERENDER_URL', 'https://service.prerender.io'), - /* |-------------------------------------------------------------------------- | Return soft HTTP status codes @@ -134,7 +135,6 @@ '*.woff2' ], - /* |-------------------------------------------------------------------------- | Crawler User Agents @@ -157,11 +157,28 @@ 'rogerbot', 'linkedinbot', 'embedly', + 'bufferbot', 'quora link preview', 'showyoubot', 'outbrain', 'pinterest', + 'pinterest/0.', 'developers.google.com/+/web/snippet', + 'www.google.com/webmasters/tools/richsnippets', 'slackbot', + 'vkShare', + 'W3C_Validator', + 'redditbot', + 'Applebot', + 'WhatsApp', + 'flipboard', + 'tumblr', + 'bitlybot', + 'SkypeUriPreview', + 'nuzzel', + 'Discordbot', + 'Google Page Speed', + 'Qwantify' ], + ]; diff --git a/src/LaravelPrerenderServiceProvider.php b/src/LaravelPrerenderServiceProvider.php index 69e293f..9c0442b 100644 --- a/src/LaravelPrerenderServiceProvider.php +++ b/src/LaravelPrerenderServiceProvider.php @@ -2,37 +2,36 @@ namespace CodebarAg\LaravelPrerender; +use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\ServiceProvider; class LaravelPrerenderServiceProvider extends ServiceProvider { - protected $package = 'nutsweb/laravel-prerender'; - /** - * Bootstrap the application events. - * - * @return void + * Bootstrap any package services. */ - public function boot() + public function boot(): void { $this->publishes([ __DIR__ . '/../config/prerender.php' => config_path('prerender.php'), ], 'config'); - if ($this->app['config']->get('prerender.enable')) { - /** @var \Illuminate\Foundation\Http\Kernel $kernel */ - $kernel = $this->app['Illuminate\Contracts\Http\Kernel']; + if (config('prerender.enable')) { + /** @var Kernel $kernel */ + $kernel = $this->app->make(Kernel::class); + $kernel->pushMiddleware(PrerenderMiddleware::class); } } /** - * Register the service provider. - * - * @return void + * Register any application services. */ - public function register() + public function register(): void { - $this->mergeConfigFrom(__DIR__ . '/../config/prerender.php', 'prerender'); + $this->mergeConfigFrom( + __DIR__ . '/../config/prerender.php', + 'prerender' + ); } } diff --git a/src/PrerenderMiddleware.php b/src/PrerenderMiddleware.php index 1e3d5c7..22dfe1a 100644 --- a/src/PrerenderMiddleware.php +++ b/src/PrerenderMiddleware.php @@ -2,29 +2,21 @@ namespace CodebarAg\LaravelPrerender; -use App; use Closure; use GuzzleHttp\Client as Guzzle; use GuzzleHttp\Exception\RequestException; -use Illuminate\Contracts\Foundation\Application; +use Illuminate\Http\Request; use Illuminate\Support\Arr; +use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Str; use Psr\Http\Message\ResponseInterface; -use Redirect; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; use Symfony\Component\HttpFoundation\Response; class PrerenderMiddleware { /** - * The application instance - * - * @var Application - */ - private $app; - - /** - * The Guzzle Client that sends GET requests to the prerender server + * The Guzzle Client that sends GET requests to the prerender server. * * @var Guzzle */ @@ -38,50 +30,46 @@ class PrerenderMiddleware private $prerenderToken; /** - * List of crawler user agents that will be + * List of crawler user agents that will be. * * @var array */ private $crawlerUserAgents; /** - * URI whitelist for prerendering pages only on this list + * URI whitelist for prerendering pages only on this list. * * @var array */ private $whitelist; /** - * URI blacklist for prerendering pages that are not on the list + * URI blacklist for prerendering pages that are not on the list. * * @var array */ private $blacklist; /** - * Base URI to make the prerender requests + * Base URI to make the prerender requests. * * @var string */ private $prerenderUri; /** - * Return soft 3xx and 404 HTTP codes + * Return soft 3xx and 404 HTTP codes. * * @var string */ private $returnSoftHttpCodes; /** - * Creates a new PrerenderMiddleware instance - * - * @param Application $app - * @param Guzzle $client + * Creates a new PrerenderMiddleware instance. */ - public function __construct(Application $app, Guzzle $client) + public function __construct(Guzzle $client) { - $this->app = $app; - $this->returnSoftHttpCodes = $app['config']->get('prerender')['prerender_soft_http_codes']; + $this->returnSoftHttpCodes = config('prerender.prerender_soft_http_codes'); if ($this->returnSoftHttpCodes) { $this->client = $client; @@ -92,7 +80,7 @@ public function __construct(Application $app, Guzzle $client) $this->client = new Guzzle($config); } - $config = $app['config']->get('prerender'); + $config = config('prerender'); $this->prerenderUri = $config['prerender_url']; $this->crawlerUserAgents = $config['crawler_user_agents']; @@ -104,13 +92,9 @@ public function __construct(Application $app, Guzzle $client) /** * Handles a request and prerender if it should, otherwise call the next middleware. * - * @param $request - * @param Closure $next - * @return Response - * @internal param int $type - * @internal param bool $catch + * @return mixed */ - public function handle($request, Closure $next) + public function handle(Request $request, Closure $next) { if ($this->shouldShowPrerenderedPage($request)) { $prerenderedResponse = $this->getPrerenderedPageResponse($request); @@ -133,11 +117,8 @@ public function handle($request, Closure $next) /** * Returns whether the request must be prerendered. - * - * @param \Illuminate\Http\Request $request - * @return bool */ - private function shouldShowPrerenderedPage($request) + private function shouldShowPrerenderedPage(Request $request): bool { $userAgent = strtolower($request->server->get('HTTP_USER_AGENT')); $bufferAgent = $request->server->get('X-BUFFERBOT'); @@ -150,6 +131,7 @@ private function shouldShowPrerenderedPage($request) if (!$userAgent) { return false; } + if (!$request->isMethod('GET')) { return false; } @@ -160,10 +142,8 @@ private function shouldShowPrerenderedPage($request) } // prerender if a crawler is detected - foreach ($this->crawlerUserAgents as $crawlerUserAgent) { - if (Str::contains($userAgent, strtolower($crawlerUserAgent))) { - $isRequestingPrerenderedPage = true; - } + if (in_array(strtolower($userAgent), $this->crawlerUserAgents)) { + $isRequestingPrerenderedPage = true; } if ($bufferAgent) { @@ -184,10 +164,12 @@ private function shouldShowPrerenderedPage($request) // only check blacklist if it is not empty if ($this->blacklist) { $uris[] = $requestUri; + // we also check for a blacklisted referer if ($referer) { $uris[] = $referer; } + if ($this->isListed($uris, $this->blacklist)) { return false; } @@ -198,16 +180,14 @@ private function shouldShowPrerenderedPage($request) } /** - * Prerender the page and return the Guzzle Response - * - * @param $request - * @return null|void + * Prerender the page and return the Guzzle Response. */ - private function getPrerenderedPageResponse($request) + private function getPrerenderedPageResponse(Request $request): ?ResponseInterface { $headers = [ 'User-Agent' => $request->server->get('HTTP_USER_AGENT'), ]; + if ($this->prerenderToken) { $headers['X-Prerender-Token'] = $this->prerenderToken; } @@ -226,12 +206,13 @@ private function getPrerenderedPageResponse($request) return $this->client->get($this->prerenderUri . '/' . urlencode($protocol.'://'.$host.'/'.$path), compact('headers')); } catch (RequestException $exception) { if (!$this->returnSoftHttpCodes && !empty($exception->getResponse()) && $exception->getResponse()->getStatusCode() === 404) { - App::abort(404); + abort(404); } + // In case of an exception, we only throw the exception if we are in debug mode. Otherwise, // we return null and the handle() method will just pass the request to the next middleware // and we do not show a prerendered page. - if ($this->app['config']->get('app.debug')) { + if (config('app.debug')) { throw $exception; } @@ -240,24 +221,17 @@ private function getPrerenderedPageResponse($request) } /** - * Convert a Guzzle Response to a Symfony Response - * - * @param ResponseInterface $prerenderedResponse - * @return Response + * Convert a Guzzle Response to a Symfony Response. */ - private function buildSymfonyResponseFromGuzzleResponse(ResponseInterface $prerenderedResponse) + private function buildSymfonyResponseFromGuzzleResponse(ResponseInterface $prerenderedResponse): Response { return (new HttpFoundationFactory)->createResponse($prerenderedResponse); } /** * Check whether one or more needles are in the given list - * - * @param $needles - * @param $list - * @return bool */ - private function isListed($needles, $list) + private function isListed($needles, array $list): bool { $needles = Arr::wrap($needles); diff --git a/tests/PrerenderMiddlewareTest.php b/tests/PrerenderMiddlewareTest.php index a105f1c..e598511 100644 --- a/tests/PrerenderMiddlewareTest.php +++ b/tests/PrerenderMiddlewareTest.php @@ -4,9 +4,7 @@ class PrerenderMiddlewareTest extends TestCase { - /** - * @test - */ + /** @test */ public function it_should_prerender_page_on_get_request() { $this->allowSymfonyUserAgent(); @@ -16,9 +14,7 @@ public function it_should_prerender_page_on_get_request() ->assertSuccessful(); } - /** - * @test - */ + /** @test */ public function it_should_not_prerender_page_when_user_agent_does_not_in_list() { $this->get('/test-middleware') @@ -27,9 +23,7 @@ public function it_should_not_prerender_page_when_user_agent_does_not_in_list() ->assertSee('GET - Success'); } - /** - * @test - */ + /** @test */ public function it_should_prerender_page_with_escaped_fragment_in_query_string() { $this->get('/test-middleware?_escaped_fragment_') @@ -37,33 +31,29 @@ public function it_should_prerender_page_with_escaped_fragment_in_query_string() ->assertSuccessful(); } - /** - * @test - */ + /** @test */ public function it_should_prerender_page_with_url_in_whitelist() { config()->set('prerender.whitelist', ['/test-middleware*']); + $this->get('/test-middleware?_escaped_fragment_') ->assertHeader('prerender.io-mock', true) ->assertSuccessful(); } - /** - * @test - */ + /** @test */ public function is_should_not_prerender_page_in_blacklist() { config()->set('prerender.blacklist', ['/test-middleware*']); + $this->get('/test-middleware?_escaped_fragment_') ->assertSuccessful() ->assertHeaderMissing('prerender.io-mock') ->assertSee('GET - Success'); } - /** - * @test - */ - public function it_should_not_prrender_page_on_non_get_request() + /** @test */ + public function it_should_not_prerender_page_on_non_get_request() { $this->allowSymfonyUserAgent(); @@ -72,19 +62,14 @@ public function it_should_not_prrender_page_on_non_get_request() ->assertSee('Success'); } - /** - * @test - */ - public function it_should_not_prerender_page_when_missing_useg_agent() + /** @test */ + public function it_should_not_prerender_page_when_missing_user_agent() { $this->get('/test-middleware', ['User-Agent' => null]) ->assertHeaderMissing('prerender.io-mock') ->assertSee('GET - Success'); } - /** - * - */ private function allowSymfonyUserAgent() { config()->set('prerender.crawler_user_agents', ['symfony']); diff --git a/tests/TestCase.php b/tests/TestCase.php index bafd6c6..75290a9 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -8,20 +8,13 @@ use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Psr7\Response; +use Illuminate\Foundation\Application; use Illuminate\Foundation\Http\Kernel; use Illuminate\Support\Facades\Route; -/** - * Class TestCase - * - * @package CodebarAg\LaravelPrerender\Tests - */ class TestCase extends \Orchestra\Testbench\TestCase { - /** - * - */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -29,11 +22,9 @@ public function setUp(): void } /** - * @param \Illuminate\Foundation\Application $app - * - * @return array + * @param Application $app */ - protected function getPackageProviders($app) + protected function getPackageProviders($app): array { return [ LaravelPrerenderServiceProvider::class, @@ -41,9 +32,9 @@ protected function getPackageProviders($app) } /** - * @param \Illuminate\Foundation\Application $app + * @param Application $app */ - protected function getEnvironmentSetUp($app) + protected function getEnvironmentSetUp($app): void { $app->make(Kernel::class)->prependMiddleware(PrerenderMiddleware::class); @@ -58,10 +49,7 @@ protected function getEnvironmentSetUp($app) }); } - /** - * - */ - protected function setupRoutes() + protected function setupRoutes(): void { Route::get('test-middleware', function () { return 'GET - Success';