modules/Screeenly/Contracts/CanCaptureScreenshot.php
use Screeenly\Entities\Url; interface CanCaptureScreenshot{ public function capture(Url $url, $storageUrl);}
use Screeenly\Entities\Url; interface CanCaptureScreenshot{ public function capture(Url $url, $storageUrl);}
use Screeenly\Contracts\CanCaptureScreenshot;use Screeenly\Entities\Screenshot;use Screeenly\Entities\Url; class InMemoryBrowser extends Browser implements CanCaptureScreenshot{ public function capture(Url $url, $storageUrl) { return new Screenshot(storage_path('testing/test-screenshot.jpg')); }}
use Illuminate\Support\Facades\Storage;use Screeenly\Contracts\CanCaptureScreenshot;use Screeenly\Entities\Screenshot;use Screeenly\Entities\Url;use Spatie\Browsershot\Browsershot; class ChromeBrowser extends Browser implements CanCaptureScreenshot{ public function capture(Url $url, $filename) { $browser = Browsershot::url($url->getUrl()) ->ignoreHttpsErrors() ->windowSize($this->width, is_null($this->height) ? 768 : $this->height) ->timeout(30) ->setDelay($this->delay * 1000) ->userAgent('screeenly-bot 2.0'); Storage::disk(config('screeenly.filesystem_disk'))->put($filename, $browser->screenshot()); $path = Storage::disk(config('screeenly.filesystem_disk'))->path($filename); return new Screenshot($path); }}
// We specify in the Service Provider, that the class of CanCaptureScreenshot interface should be ChromeBrowser class use Screeenly\Contracts\CanCaptureScreenshot;use Screeenly\Services\ChromeBrowser; class ScreeenlyServiceProvider extends ServiceProvider{ public function boot() { // ... $this->app->bind(CanCaptureScreenshot::class, ChromeBrowser::class); }}
use Screeenly\Contracts\CanCaptureScreenshot;use Screeenly\Entities\Url; class CaptureService{ protected $browser; // By this point, Laravel knows that CanCaptureScreenshot should be resolved as ChromeBrowser public function __construct(CanCaptureScreenshot $browser) { $this->browser = $browser; } public function capture() { $filename = uniqid().'_'.Str::random(30) . ".png"; return $this->browser->capture( $this->url, $filename ); }}
use Screeenly\Contracts\CanCaptureScreenshot;use Screeenly\Services\InMemoryBrowser; class ApiV2ScreenshotTest extends BrowserKitTestCase{ public function it_returns_base64_representation_of_screenshot() { // But in the automated test we can easily resolve the same interface with a DIFFERENT class - InMemoryBrowser $this->app->bind(CanCaptureScreenshot::class, function ($app) { return new InMemoryBrowser('http://foo.bar', '/path/to/storage'); }); $this->json('POST', '/api/v2/screenshot', [ 'key' => $apiKey->key, 'url' => 'http://google.com', ]) ->seeJsonStructure([ 'data' => [ 'path', 'base64', ], ]); }}