From 064c24aed6414daf0f363df547bdd6595cdd3f09 Mon Sep 17 00:00:00 2001 From: Stefan Bauer Date: Mon, 20 Aug 2018 15:47:33 +0200 Subject: [PATCH] initial commit --- .gitignore | 3 + .php_cs.dist | 30 +++ .travis.yml | 15 ++ CHANGELOG.md | 5 + CONTRIBUTING.md | 34 ++++ LICENSE.md | 21 +++ README.md | 94 ++++++++++ composer.json | 49 +++++ config/favicon-extractor.php | 32 ++++ phpunit.xml.dist | 27 +++ .../FaviconCouldNotBeSavedException.php | 9 + src/Exception/InvalidUrlException.php | 9 + src/Facades/FaviconExtractor.php | 15 ++ src/Favicon/Favicon.php | 20 ++ src/Favicon/FaviconFactory.php | 13 ++ src/Favicon/FaviconFactoryInterface.php | 10 + src/Favicon/FaviconInterface.php | 10 + src/FaviconExtractor.php | 94 ++++++++++ src/FaviconExtractorInterface.php | 15 ++ src/FaviconExtractorServiceProvider.php | 48 +++++ src/Generator/FilenameGenerator.php | 13 ++ src/Generator/FilenameGeneratorInterface.php | 10 + src/Provider/GoogleProvider.php | 23 +++ src/Provider/ProviderInterface.php | 10 + tests/Favicon/FaviconFactoryTest.php | 19 ++ tests/Favicon/FaviconTest.php | 17 ++ tests/FaviconExtractorTest.php | 175 ++++++++++++++++++ tests/Generator/FilenameGeneratorTest.php | 18 ++ 28 files changed, 838 insertions(+) create mode 100644 .gitignore create mode 100644 .php_cs.dist create mode 100644 .travis.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 config/favicon-extractor.php create mode 100644 phpunit.xml.dist create mode 100644 src/Exception/FaviconCouldNotBeSavedException.php create mode 100644 src/Exception/InvalidUrlException.php create mode 100644 src/Facades/FaviconExtractor.php create mode 100644 src/Favicon/Favicon.php create mode 100644 src/Favicon/FaviconFactory.php create mode 100644 src/Favicon/FaviconFactoryInterface.php create mode 100644 src/Favicon/FaviconInterface.php create mode 100644 src/FaviconExtractor.php create mode 100644 src/FaviconExtractorInterface.php create mode 100644 src/FaviconExtractorServiceProvider.php create mode 100644 src/Generator/FilenameGenerator.php create mode 100644 src/Generator/FilenameGeneratorInterface.php create mode 100644 src/Provider/GoogleProvider.php create mode 100644 src/Provider/ProviderInterface.php create mode 100644 tests/Favicon/FaviconFactoryTest.php create mode 100644 tests/Favicon/FaviconTest.php create mode 100644 tests/FaviconExtractorTest.php create mode 100644 tests/Generator/FilenameGeneratorTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5414c2c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +composer.lock +phpunit.xml +vendor/ diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..f8d8d5b --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,30 @@ +name('*.php') + ->in(__DIR__.DIRECTORY_SEPARATOR.'src') + ->in(__DIR__.DIRECTORY_SEPARATOR.'tests') +; + +return Config::create() + ->setUsingCache(false) + ->setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + 'array_syntax' => ['syntax' => 'short'], + 'linebreak_after_opening_tag' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'ordered_imports' => true, + 'php_unit_strict' => true, + 'phpdoc_annotation_without_dot' => false, + 'phpdoc_order' => true, + 'semicolon_after_instruction' => true, + 'strict_comparison' => true, + 'strict_param' => true, + 'self_accessor' => false, + ]) + ->setFinder($finder) +; diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..2ab344b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: php + +php: + - 7.0 + - 7.1 + - 7.2 + +sudo: false + +before_script: + - travis_retry composer self-update + - travis_retry composer update --no-interaction --no-suggest --prefer-dist + +script: + - vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..1de82f8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# Change Log + + + +\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..648e26c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,34 @@ +# Contributing + +If you want to contribute to one of my projects and make it better, **your help is very welcome**. It's also a great way to learn more about **social coding on Github** and **new technologies**. + +For contribution please create a PR on [Github](https://github.com/stefanbauer/laravel-favicon-extractor). + +## Pull Requests + +#### Coding Standards + +I use the **[Symfony Coding Standard](https://symfony.com/doc/current/contributing/code/standards.html)**. It's basically the **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)**, just with some additional standards. I always add a `.php_cs.dist`. Run the `php-cs-fixer` to keep code valid. + +#### Feature Branches + +- **Use feature branches:** Create a new branch to work on. Branch from `master`. +- **One feature per PR:** I love simplicity. Please create only one PR per feature. If you would like to change more, create more PRs. + +#### Commits + +- **Don't pollute the git history:** Please don't create several (senseless) commits. Squash/Rebase your commits into one or several meaningful commits. +- **Commit in present tense:** Always write your commit messages in the present tense. Your commit message should describe what the commit, when applied, does to the code – not what you did to the code. + +#### Tests + +- **Don't forget your tests:** I don't accept your PRs without any tests. + +#### Documentation +- **Document behaviour related things:** Update the `README.md` with details of changes if necessary. + +## Running Tests + +``` bash +$ vendor/bin/phpunit +``` diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..17c10f7 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018 Stefan Bauer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b2b7147 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# Laravel Favicon Extractor + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/stefanbauer/laravel-favicon-extractor.svg?style=flat-square)](https://packagist.org/packages/stefanbauer/laravel-favicon-extractor) +[![Build Status](https://img.shields.io/travis/stefanbauer/laravel-favicon-extractor/master.svg?style=flat-square)](https://travis-ci.org/stefanbauer/laravel-favicon-extractor) +[![Total Downloads](https://img.shields.io/packagist/dt/stefanbauer/laravel-favicon-extractor.svg?style=flat-square)](https://packagist.org/packages/stefanbauer/laravel-favicon-extractor) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) + +This package provides a convenient way to extract a favicon from any website by using the appropriate Google service. It allows you to fetch and save it to your local storage. + +## Usage + +Usage is very simple. You can either pull it in via Dependency Injection or use the Facade. + +- For the Dependency Injection version, type hint the `FaviconExtractorInterface`. +- For the Facade version, use the `FaviconExtractor` Facade. + +### General + +- If no favicon could be found, it returns a default one. +- The favicon's extension is always `.png`. It's not necessary to be part of your filename. + +### Fetch the favicon only + +```php +$favicon = FaviconExtractor::fromUrl('https://laravel.com')->fetchOnly(); +``` + +It returns a instance which implements `FaviconInterface` where you can retrieve the raw content of the favicon with `$favicon->getContent()`. + +### Fetch and download the favicon + +If you prefer to save the favicon to your local storage, you can. The only requirement is to define the path, where the favicon should be saved. It's relative to your root path which you defined in `config/filesystems.php`. Saying your path to save is `favicons`, it will be saved to `app/storage/favicons`. + +#### With a random generated filename + +```php +FaviconExtractor::fromUrl('https://laravel.com')->fetchAndSaveTo('favicons'); +// returns favicons/HIgLtwL0iUdNkwfq.png +``` + +#### With a custom filename + +```php +FaviconExtractor::fromUrl('https://laravel.com')->fetchAndSaveTo('favicons', 'myFilename'); +// returns favicons/myFilename.png +``` + +## Installation + +To install this package, require it via composer. + +```shell +$ composer require stefanbauer/laravel-favicon-extractor +``` + +Thanks to Laravel 5.5+ Package Auto-Discovery, there is no need to add the ServiceProvider manually. If you don't use auto-discovery, add the ServiceProvider to the providers array in `config/app.php`. + +```php +StefanBauer\LaravelFaviconExtractor\FaviconExtractorServiceProvider::class, +``` + +If you want to use the facade, add this to your facades array in `config/app.php`. + +```php +'FaviconExtractor' => StefanBauer\LaravelFaviconExtractor\Facades\FaviconExtractor::class, +``` + +## Configuration + +If you would like to modify the configuration, use the publish command to copy the package config over. + +```shell +php artisan vendor:publish --provider="StefanBauer\LaravelFaviconExtractor\FaviconExtractorServiceProvider" --tag="config" +``` + +The configuration file has only two options you can change. The `provider_class` and the `filename_generator_class`. In general, there is no need to change it, unless you like to have a different implementations how the favicon is fetched and how the filename is generated. Pleae take care of implementing the corresponding interfaces. + +## Testing + +```shell +$ vendor/bin/phpunit +``` + +## Changelog + +Please take a look at the [CHANGELOG](CHANGELOG.md) what has changed recently. + +## Contributing + +Please take a look at [CONTRIBUTING](CONTRIBUTING.md) for more information. + +## License + +The MIT License (MIT). Please take a look at the [LICENSE](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..41f4c88 --- /dev/null +++ b/composer.json @@ -0,0 +1,49 @@ +{ + "name": "stefanbauer/laravel-favicon-extractor", + "description": "A favicon extractor for Laravel", + "keywords": [ + "stefanbauer", + "laravel-favicon-extractor", + "favicon" + ], + "homepage": "https://github.com/stefanbauer/laravel-favicon-extractor", + "license": "MIT", + "authors": [ + { + "name": "Stefan Bauer", + "email": "mail@stefanbauer.me", + "homepage": "https://stefanbauer.me" + } + ], + "require": { + "php" : "^7.0", + "illuminate/support": "~5.5.0|~5.6.0", + "graham-campbell/guzzle-factory": "^3.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.2|^7.0", + "orchestra/testbench": "~3.5.0|~3.6.0", + "mockery/mockery": "^1.1", + "friendsofphp/php-cs-fixer": "^2.12" + }, + "autoload": { + "psr-4": { + "StefanBauer\\LaravelFaviconExtractor\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "StefanBauer\\LaravelFaviconExtractor\\": "tests" + } + }, + "extra": { + "laravel": { + "providers": [ + "StefanBauer\\LaravelFaviconExtractor\\FaviconExtractorServiceProvider" + ], + "aliases": { + "FaviconExtractor": "StefanBauer\\LaravelFaviconExtractor\\Facades\\FaviconExtractor" + } + } + } +} diff --git a/config/favicon-extractor.php b/config/favicon-extractor.php new file mode 100644 index 0000000..0afbca0 --- /dev/null +++ b/config/favicon-extractor.php @@ -0,0 +1,32 @@ + \StefanBauer\LaravelFaviconExtractor\Provider\GoogleProvider::class, + + /* + |-------------------------------------------------------------------------- + | Filename Generator + |-------------------------------------------------------------------------- + | + | If you don't specify a custom filename on saving the downloaded favicon + | to your storage, this package generates a random string for it. You + | can override this behaviour at any time by using a custom + | implementation which implements the following interface. + | + | \StefanBauer\LaravelFaviconExtractor\Generator\FilenameGeneratorInterface + | + */ + 'filename_generator_class' => \StefanBauer\LaravelFaviconExtractor\Generator\FilenameGenerator::class +]; diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..0e9efec --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,27 @@ + + + + + + + + + ./tests/ + + + + + + ./src + + + diff --git a/src/Exception/FaviconCouldNotBeSavedException.php b/src/Exception/FaviconCouldNotBeSavedException.php new file mode 100644 index 0000000..68b22de --- /dev/null +++ b/src/Exception/FaviconCouldNotBeSavedException.php @@ -0,0 +1,9 @@ +content = $content; + } + + public function getContent(): string + { + return $this->content; + } +} diff --git a/src/Favicon/FaviconFactory.php b/src/Favicon/FaviconFactory.php new file mode 100644 index 0000000..cefb91a --- /dev/null +++ b/src/Favicon/FaviconFactory.php @@ -0,0 +1,13 @@ +provider = $provider; + $this->faviconFactory = $faviconFactory; + $this->filenameGenerator = $filenameGenerator; + } + + public function fromUrl(string $url): FaviconExtractorInterface + { + if (!$this->isValidUrl($url)) { + throw new InvalidUrlException(); + } + + $this->url = $url; + + return $this; + } + + public function getUrl(): string + { + return $this->url; + } + + public function fetchOnly(): FaviconInterface + { + $this->favicon = $this->faviconFactory->create( + $this->provider->fetchFromUrl($this->getUrl()) + ); + + return $this->favicon; + } + + public function fetchAndSaveTo(string $path, string $filename = null): string + { + if (null === $filename) { + $filename = $this->filenameGenerator->generate(16); + } + + $favicon = $this->fetchOnly(); + $targetPath = $this->getTargetPath($path, $filename); + + if (!Storage::put($targetPath, $favicon->getContent())) { + throw new FaviconCouldNotBeSavedException(sprintf( + 'The favicon of %s could not be saved at path "%s" ', + $this->getUrl(), $targetPath + )); + } + + return $targetPath; + } + + private function getTargetPath(string $path, string $filename): string + { + return $path.DIRECTORY_SEPARATOR.$filename.'.png'; + } + + private function isValidUrl(string $url): bool + { + $pattern = '/^ + (http|https):\\/\\/ + ( + [a-z0-9]+([\\-\\.]{1}[a-z_0-9]+)*\\.[a-z]{2,5} + | + (([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) + ) + (:[0-9]+)? + (\\/.*)? + $/ixu'; + + return preg_match($pattern, $url) > 0; + } +} diff --git a/src/FaviconExtractorInterface.php b/src/FaviconExtractorInterface.php new file mode 100644 index 0000000..0ea2b51 --- /dev/null +++ b/src/FaviconExtractorInterface.php @@ -0,0 +1,15 @@ +publishes([ + __DIR__.'/../config/favicon-extractor.php' => config_path('favicon-extractor.php') + ], 'config'); + + $this->mergeConfigFrom(__DIR__.'/../config/favicon-extractor.php', 'favicon-extractor'); + } + + public function register() + { + $this->app->bind( + FaviconFactoryInterface::class, + FaviconFactory::class + ); + + $this->app->bind( + ProviderInterface::class, + config('favicon-extractor.provider_class') + ); + + $this->app->bind( + FilenameGeneratorInterface::class, + config('favicon-extractor.filename_generator_class') + ); + + $this->app->bind( + FaviconExtractorInterface::class, + FaviconExtractor::class + ); + + $this->app->alias(FaviconExtractorInterface::class, 'favicon.extractor'); + } +} diff --git a/src/Generator/FilenameGenerator.php b/src/Generator/FilenameGenerator.php new file mode 100644 index 0000000..9506dcb --- /dev/null +++ b/src/Generator/FilenameGenerator.php @@ -0,0 +1,13 @@ +get($this->getUrl($url)); + + return $response->getBody()->getContents(); + } + + private function getUrl(string $url): string + { + return 'https://www.google.com/s2/favicons?domain='.urlencode($url); + } +} diff --git a/src/Provider/ProviderInterface.php b/src/Provider/ProviderInterface.php new file mode 100644 index 0000000..1414af1 --- /dev/null +++ b/src/Provider/ProviderInterface.php @@ -0,0 +1,10 @@ +create($expectedContent = 'content'); + + $this->assertInstanceOf(Favicon::class, $favicon); + $this->assertSame($expectedContent, $favicon->getContent()); + } +} diff --git a/tests/Favicon/FaviconTest.php b/tests/Favicon/FaviconTest.php new file mode 100644 index 0000000..fc0af33 --- /dev/null +++ b/tests/Favicon/FaviconTest.php @@ -0,0 +1,17 @@ +assertSame($expectedContent, $favicon->getContent()); + } +} diff --git a/tests/FaviconExtractorTest.php b/tests/FaviconExtractorTest.php new file mode 100644 index 0000000..e1dc765 --- /dev/null +++ b/tests/FaviconExtractorTest.php @@ -0,0 +1,175 @@ +faviconFactory = \Mockery::mock(FaviconFactoryInterface::class); + $this->provider = \Mockery::mock(ProviderInterface::class); + $this->filenameGenerator = \Mockery::mock(FilenameGeneratorInterface::class); + + $this->extractor = new FaviconExtractor($this->faviconFactory, $this->provider, $this->filenameGenerator); + + parent::setUp(); + } + + public function test_it_accepts_a_valid_url() + { + $extractor = $this->extractor->fromUrl($expectedUrl = 'https://example.com'); + + $this->assertInstanceOf(FaviconExtractor::class, $extractor); + $this->assertSame($expectedUrl, $extractor->getUrl()); + } + + public function provideInvalidUrls() + { + return [ + 'Missing protocol' => ['example.com'], + 'Invalid protocol' => ['ftp://example.com'], + 'Missing tld' => ['http://example'], + ]; + } + + /** + * @dataProvider provideInvalidUrls + */ + public function test_it_does_not_accept_an_invalid_url(string $url) + { + $this->expectException(InvalidUrlException::class); + + $this->extractor->fromUrl($url); + } + + public function test_it_fetches_the_favicon() + { + $expectedUrl = 'http://example.com'; + $expectedContent = 'example-content'; + + $this->provider + ->shouldReceive('fetchFromUrl') + ->once() + ->with($expectedUrl) + ->andReturn($expectedContent) + ; + + $this->faviconFactory + ->shouldReceive('create') + ->once() + ->with($expectedContent) + ; + + $this->extractor->fromUrl($expectedUrl)->fetchOnly(); + } + + public function test_it_generates_a_filename_if_none_given() + { + $this->provider->shouldIgnoreMissing(); + + $expectedFavicon = new Favicon('content'); + + $this->faviconFactory + ->shouldReceive('create') + ->withAnyArgs() + ->andReturn($expectedFavicon) + ; + + $this->filenameGenerator + ->shouldReceive('generate') + ->once() + ->with(16) + ->andReturn('random-filename') + ; + + $this->extractor + ->fromUrl('http://example.com') + ->fetchAndSaveTo('some-path') + ; + } + + public function test_it_saves_it_properly() + { + $this->provider->shouldIgnoreMissing(); + + $expectedFavicon = new Favicon('content'); + + $this->faviconFactory + ->shouldReceive('create') + ->withAnyArgs() + ->andReturn($expectedFavicon) + ; + + Storage::fake(); + Storage:: + shouldReceive('put') + ->once() + ->with('some-path/a-filename.png', 'content') + ->andReturn(true) + ; + + $this->extractor + ->fromUrl('http://example.com') + ->fetchAndSaveTo('some-path', 'a-filename') + ; + } + + public function test_it_throws_an_exception_when_saving_was_not_successful() + { + $this->provider->shouldIgnoreMissing(); + + $expectedFavicon = new Favicon('content'); + + $this->faviconFactory + ->shouldReceive('create') + ->withAnyArgs() + ->andReturn($expectedFavicon) + ; + + Storage::fake(); + Storage:: + shouldReceive('put') + ->once() + ->andReturn(false) + ; + + $this->expectException(FaviconCouldNotBeSavedException::class); + + $this->extractor + ->fromUrl('http://example.com') + ->fetchAndSaveTo('some-path', 'a-filename') + ; + } +} diff --git a/tests/Generator/FilenameGeneratorTest.php b/tests/Generator/FilenameGeneratorTest.php new file mode 100644 index 0000000..8fd3d9c --- /dev/null +++ b/tests/Generator/FilenameGeneratorTest.php @@ -0,0 +1,18 @@ +generate($expectedLength = 10); + + $this->assertSame($expectedLength, strlen($generated)); + } +}