Repository: cviebrock/image-validator Branch: master Commit: 955e6a076f0e Files: 37 Total size: 39.3 KB Directory structure: gitextract_ncb9tb7h/ ├── .github/ │ ├── ISSUE_TEMPLATE.md │ └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .nitpick.json ├── .scrutinizer.yml ├── .semver ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── TODO.md ├── composer.json ├── lang/ │ ├── de/ │ │ └── validation.php │ ├── en/ │ │ └── validation.php │ ├── es/ │ │ └── validation.php │ ├── et/ │ │ └── validation.php │ ├── fa/ │ │ └── validation.php │ ├── fr/ │ │ └── validation.php │ ├── hu/ │ │ └── validation.php │ ├── it/ │ │ └── validation.php │ ├── lv/ │ │ └── validation.php │ ├── nl/ │ │ └── validation.php │ ├── pt/ │ │ └── validation.php │ ├── pt-BR/ │ │ └── validation.php │ ├── ru/ │ │ └── validation.php │ ├── sr/ │ │ └── validation.php │ ├── tr/ │ │ └── validation.php │ ├── zh-CN/ │ │ └── validation.php │ └── zh-tw/ │ └── validation.php ├── phpunit.xml ├── src/ │ ├── ImageValidator.php │ └── ImageValidatorServiceProvider.php └── tests/ ├── .gitkeep ├── ValidateServiceProviderTest.php ├── ValidatorImageAspectTest.php └── ValidatorImageSizeTest.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ This package has been abandoned since Laravel 5.2 and later now include built-in rules to validate images: https://laravel.com/docs/5.5/validation#rule-dimensions Issues for fixes to versions prior to Laravel 5.2 will be addressed on a case-by-case basis. **Thank you!** ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ Thank you for helping to make this package better! However, this package has been abandoned since Laravel 5.2 and later now include built-in rules to validate images: https://laravel.com/docs/5.5/validation#rule-dimensions Pull requests are now longer being accepted. **Thank you!** ================================================ FILE: .gitignore ================================================ /build/ /vendor/ composer.lock composer.phar ================================================ FILE: .nitpick.json ================================================ { "ignore": [ "tests/*" ] } ================================================ FILE: .scrutinizer.yml ================================================ filter: paths: ['src/*'] checks: php: code_rating: true remove_extra_empty_lines: true remove_php_closing_tag: true remove_trailing_whitespace: true fix_use_statements: remove_unused: true preserve_multiple: false preserve_blanklines: true order_alphabetically: true fix_php_opening_tag: true fix_linefeed: true fix_line_ending: true fix_identation_4spaces: true fix_doc_comments: true tools: external_code_coverage: false php_analyzer: true php_code_coverage: false php_code_sniffer: config: standard: PSR2 filter: paths: ['src'] php_loc: enabled: true excluded_dirs: [vendor, tests] php_cpd: enabled: true excluded_dirs: [vendor, tests] ================================================ FILE: .semver ================================================ --- :major: 2 :minor: 2 :patch: 2 :special: '' :metadata: '' ================================================ FILE: .travis.yml ================================================ # Travis CI configuration language: php php: - 5.6 - 7.0 matrix: include: - php: 5.6 env: 'COMPOSER_FLAGS="--prefer-stable --prefer-lowest"' before_script: - travis_retry composer self-update - travis_retry composer install --prefer-source --no-interaction --dev $PREFER_LOWEST script: - php vendor/bin/phpunit after_script: - php vendor/bin/ocular code-coverage:upload --format=php-clover build/clover.xml ================================================ FILE: CHANGELOG.md ================================================ # Change Log ## 2.2.2 - 04-Apr-2017 - Correction to Italian (#55, thanks @neomusic) ## 2.2.1 - 08-Feb-2017 - Hungarian translation (#54, thanks @GaraiViktor) ## 2.2.0 - 07-Feb-2017 - Laravel 5.4 support ## 2.1.5 - 30-Jan-2017 - Correction to Persian (#51, thanks @smart-twists) - Estonian translation (#52, thanks @kaidoj) ## 2.1.4 - 13-Dec-2016 - Serbian (Latin) translation (#49, thanks @Shonetow) - Persian translation (#50, thanks @smart-twists) ## 2.1.3 - 12-Aug-2016 - Chinese-Simplified translation (#48, thanks @php-cpm) ## 2.1.2 - 20-Jul-2016 - Chinese-Traditional translation (#47, thanks @CaraWang) ## 2.1.1 - 19-Jul-2016 - Fix for translations not loading in closure (#45, thanks @nWidart) ## 2.1.0 - 27-May-2016 - Latvian translation (#42, thanks @scvaer) - Fix for aspect ratio checking on images where the result would be fractional pixels (#31) - Fix where aspect error message only lists one parameter when using `3,2` format for aspect (#41) - Fix for Lumen (#44, thanks @WrongWay) - Fix where translations aren't yet available (#30, thanks @superdummy) ## 2.0.1 - 11-Apr-2016 - Spanish translation (#32, thanks @keyduq). - French translation fixes (#39, thanks @DevJuju). ## 2.0.0 - 07-Oct-2015 - Russian translation (#29, thanks @DexinDev). ## 2.0.0-beta - 02-Mar-2015 - Laravel 5 release version. - German and Dutch translations (#18 and #19, thanks @gpluess). ## 2.0.0-alpha - 11-Feb-2015 - Laravel 5 alpha version. ## 1.0.5 - 11-Feb-2015 - Fixed Turkish translation (#7, thanks @mayoz). - Fixed Italian translation (#55, thanks @neomusic). - Last version that works with Laravel 4. ## 1.0.4 - 17-Jun-2014 - Added translation for French (merci @yazuu). ## 1.0.3 - 04-Jun-2014 - Added translations for Portuguese (thanks @helio-correia) and Turkish (thanks @Ardakilic). ## 1.0.2 - 04-Feb-2014 - Bug fixes. ## 1.0.0 - 04-Feb-2014 - Rename package to `cviebrock/image-validator`. - Require Laravel >= 4.1.21 due to validation replacement rules. - Use better validation extension. ## 0.2.0 - 20-Dec-2013 - Added `image_aspect` validation. ## 0.1.1 - 16-Dec-2013 - Initial release. ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Contributions are **welcome** and will be fully **credited**. We accept contributions via pull requests via [Github](https://github.com/cviebrock/image-validator). 1. Fork the project. 2. Create your bugfix/feature branch and write your (well-commented) code. 3. Create unit tests for your code: - Run `composer install --dev` in the root directory to install required testing packages. - Add your test classes/methods to the `/tests/` directory. - Run `vendor/bin/phpunit` and make sure everything passes (new and old tests). 3. Commit your changes (and your tests) and push to your branch. 4. Create a new pull request against this package's `master` branch. ## Pull Requests - **Use the [PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).** The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). - **Add tests!** Your pull request won't be accepted if it doesn't have tests. - **Document any change in behaviour.** Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle.** We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches.** Don't ask us to pull from your master branch. - **One pull request per feature.** If you want to do more than one thing, send multiple pull requests. - **Send coherent history.** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. - Don't worry about updating `CHANGELOG.md` or `.semver`. The package administrator will handle updating those when new releases are created. **Thank you!** ================================================ FILE: LICENSE.md ================================================ # The MIT License (MIT) Copyright (c) 2013 Colin Viebrock > 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. ================================================ FILE: README.md ================================================ # Image-Validator Extra validation rules for dealing with images in Laravel 5. > *NOTE*: As of Laravel version 5.2, there are now [built-in validation rules for image dimensions and aspect ratios](https://laravel.com/docs/validation#rule-dimensions). > This package is not required and will no longer be maintained. [![Build Status](https://travis-ci.org/cviebrock/image-validator.svg?branch=master&format=flat)](https://travis-ci.org/cviebrock/image-validator) [![Total Downloads](https://poser.pugx.org/cviebrock/image-validator/downloads?format=flat)](https://packagist.org/packages/cviebrock/image-validator) [![Latest Stable Version](https://poser.pugx.org/cviebrock/image-validator/v/stable?format=flat)](https://packagist.org/packages/cviebrock/image-validator) [![Latest Unstable Version](https://poser.pugx.org/cviebrock/image-validator/v/unstable?format=flat)](https://packagist.org/packages/cviebrock/image-validator) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/cviebrock/image-validator/badges/quality-score.png?format=flat)](https://scrutinizer-ci.com/g/cviebrock/image-validator) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/bc2c9e90-2edf-4047-9b3c-a5aa15da165b/mini.png)](https://insight.sensiolabs.com/projects/bc2c9e90-2edf-4047-9b3c-a5aa15da165b) [![License: MIT](https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square)](https://opensource.org/licenses/MIT) * [Installation](#installation) * [Usage](#usage) * [image_size](#image_size) * [image_aspect](#image_aspect) * [Examples](#examples) * [Bugs, Suggestions and Contributions](#bugs-suggestions-and-contributions) * [Copyright and License](#copyright-and-license) --- ## Installation > **NOTE**: Depending on your version of Laravel, you should install a different > version of the package: > > | Laravel Version | Package Version | > |:---------------:|:---------------:| > | 4.* | 1.x | > | 5.0–5.3 | 2.1† | > | 5.4 | 2.2† | > | 5.5 | not supported† | > > † Laravel 5.2 and later have [built-in validation rules for image dimensions](https://laravel.com/docs/5.5/validation#rule-dimensions). Install the package through [Composer](http://getcomposer.org). ```shell composer require "cviebrock/image-validator" ``` Add the following to your `providers` array in `app/config/app.php`: ```php 'providers' => [ ... \Cviebrock\ImageValidator\ImageValidatorServiceProvider::class, ], ``` ## Usage Use it like any `Validator` rule. The package offers two rules for image validation: ### image_size ```php $rules = [ 'my_image_field' => 'image_size:[,]', ]; ``` The values for _width_ and _height can be integers, or integers with a modifier prefix: - `300` or `=300` means the dimension must be exactly 300 pixels. - `<300` means the dimension must be less than 300 pixels - `<=300` means the dimension must be less than or equal to 300 pixels - `>300` means the dimension must be greater than 300 pixels - `>=300` means the dimension must be greater than or equal to 300 pixels - `200-300` means the dimension must be between 200 and 300 pixels (inclusive) - `*` means the dimension can be any value If you only pass one value, it's assumed to apply to both dimensions (i.e. a square image with the given dimensions). ### image_aspect ```php $rules = [ 'my_image_field' => 'image_aspect:', ]; ``` The value for _ratio_ represents _width ÷ height_ and be either a decimal or two values (width, height; both integers): - `0.75` - `3,4` The value (or first value, if providing height and width) can also be prefixed with a tilde `~` character, in which case the orientation does not matter: - `~3,4` means the image can have an aspect ratio of either 3:4 or 4:3. Note that you may run into issues with floating point rounding. ## Examples ```php // logo must be 300px wide by 400px tall $rules = [ 'logo' => 'required|image|image_size:300,400', ]; // logo must be less than or equal to 300x300px. $rules = [ 'logo' => 'required|image|image_size:<=300', ]; // logo must be 300px wide but can be any height $rules = [ 'logo' => 'required|image|image_size:300,*', ]; // logo must be at least 100px tall and 200-300 pixels wide (inclusive) $rules = [ 'logo' => 'required|image|image_size:>=100,200-300', ]; // logo must be square $rules = [ 'logo' => 'required|image|image_aspect:1', ]; // logo must be ready for the big screen TV :) $rules = [ 'logo' => 'required|image|image_aspect:16,9', ]; ``` ## Bugs, Suggestions and Contributions Thanks to [everyone](https://github.com/cviebrock/image-validator/graphs/contributors) who has contributed to this project! Please use [Github](https://github.com/cviebrock/image-validator) for reporting bugs, and making comments or suggestions. See [CONTRIBUTING.md](CONTRIBUTING.md) for how to contribute changes. ## Copyright and License [image-validator](https://github.com/cviebrock/image-validator) was written by [Colin Viebrock](http://viebrock.ca) and is released under the [MIT License](LICENSE.md). Copyright 2013 Colin Viebrock ## Thanks Lots of thanks to https://bitbucket.org/hampel/validate-laravel for the structure of creating a package to add validator rules to Laravel, and setting up useful unit tests. ================================================ FILE: TODO.md ================================================ # TODO - [ ] add more rules? - [ ] make error messages publishable via `artisan vendor:publish` - [ ] test in an actual Laravel 5 project - [ ] test validator messages / translations ================================================ FILE: composer.json ================================================ { "name": "cviebrock/image-validator", "description": "Custom Laravel Validator for image dimensions - abandoned since these are now built in to Laravel 5.2 and later", "keywords": [ "laravel", "validator", "image", "deprecated" ], "homepage": "https://github.com/cviebrock/image-validator", "license": "MIT", "authors": [ { "name": "Colin Viebrock", "email": "colin@viebrock.ca" } ], "require": { "php": ">=5.6.4", "illuminate/config": "^5.4", "illuminate/database": "^5.4", "illuminate/support": "^5.4" }, "require-dev": { "friendsofphp/php-cs-fixer": "^1.11", "mockery/mockery": "^0.9.4", "orchestra/testbench": "^3.4", "phpunit/phpunit": "~5.7", "scrutinizer/ocular": "^1.3" }, "autoload": { "psr-4": { "Cviebrock\\ImageValidator\\": "src/" } }, "autoload-dev": { "psr-4": { "Cviebrock\\ImageValidator\\Test\\": "tests" } }, "scripts": { "test": [ "parallel-lint . --exclude vendor", "phpunit" ] }, "minimum-stability": "dev", "prefer-stable": true } ================================================ FILE: lang/de/validation.php ================================================ ':attribute muss :width breit und :height hoch sein.', 'between' => 'zwischen :size1 und :size2 Pixel', 'lessthan' => 'kleiner als :size Pixel', 'lessthanorequal' => 'höchstens :size Pixel', 'greaterthan' => 'größer als :size Pixel', 'greaterthanorequal' => 'mindestens :size Pixel', 'equal' => ':size Pixel', 'anysize' => 'irgendeine Größe', 'image_aspect' => 'Das Seitenverhältnis von :attribute muss :aspect sein', ]; ================================================ FILE: lang/en/validation.php ================================================ 'The :attribute must be :width wide and :height tall.', 'between' => 'between :size1 and :size2 pixels', 'lessthan' => 'less than :size pixels', 'lessthanorequal' => 'less than or equal to :size pixels', 'greaterthan' => 'greater than :size pixels', 'greaterthanorequal' => 'greater than or equal to :size pixels', 'equal' => ':size pixels', 'anysize' => 'any size', 'image_aspect' => 'The :attribute aspect ratio must be :aspect.', ]; ================================================ FILE: lang/es/validation.php ================================================ "El campo :attribute debe ser :width de ancho y :height de alto.", 'between' => 'entre :size1 y :size2 pixeles', 'lessthan' => 'menor que :size pixeles', 'lessthanorequal' => 'menor que o equivalente a :size pixeles', 'greaterthan' => 'mayor que :size pixeles', 'greaterthanorequal' => 'mayor que o equivalente a :size pixeles', 'equal' => ':size pixeles', 'anysize' => 'cualquier tamaño', 'image_aspect' => 'El campo :attribute debe poseer un ratio de :aspect.', ]; ================================================ FILE: lang/et/validation.php ================================================ 'Pilt peab olema :width laiust ja :height kõrgust.', 'between' => ':size1 ja :size2 piksli vahel', 'lessthan' => 'vähem, kui :size pikslit', 'lessthanorequal' => 'väiksem või võrdne :size pikslit', 'greaterthan' => 'suurem, kui :size pikslit', 'greaterthanorequal' => 'suurem või võrdne :size pikslit', 'equal' => ':size pikslit', 'anysize' => 'iga suurus', 'image_aspect' => ':attribute kuvasuhe peab olema :aspect.', ]; ================================================ FILE: lang/fa/validation.php ================================================ ':attribute باید دارای طول :width و عرض :height باشد.', 'between' => 'بین :size1 و :size2 پیکسل باید باشد', 'lessthan' => 'کوچکتر از :size پیکسل', 'lessthanorequal' => 'کوچکتر یا برابر :size پیکسل', 'greaterthan' => 'بزرگتر از :size پیکسل', 'greaterthanorequal' => 'بزرگتر یا برابر :size پیکسل', 'equal' => ':size پیکسل', 'anysize' => 'هر اندازه ای', 'image_aspect' => ':attribute تناسب طول عرص برابر :aspect باید باشد.', ]; ================================================ FILE: lang/fr/validation.php ================================================ 'La taille de :attribute doit être :width de large et :height de haut', 'between' => 'entre :size1 et :size2 pixels', 'lessthan' => 'plus petite que :size pixels', 'lessthanorequal' => 'plus petite ou égale à :size pixels', 'greaterthan' => 'plus grande que :size pixels', 'greaterthanorequal' => 'plus grande ou égale à :size pixels', 'equal' => 'de :size pixels', 'anysize' => "de n'importe quelle taille", 'image_aspect' => 'Le ratio de :attribute doit être de :aspect', ]; ================================================ FILE: lang/hu/validation.php ================================================ 'A(z) :attribute :width szélesnek és :height magasnak kell lennie.', 'between' => ':size1 és :size2 pixel között', 'lessthan' => 'kevesebb mint :size pixel', 'lessthanorequal' => 'kevesebb vagy pont :size pixel', 'greaterthan' => 'nagyobb mint :size pixel', 'greaterthanorequal' => 'nagyobb vagy pont :size pixel', 'equal' => ':size pixel', 'anysize' => 'bármilyen méret', 'image_aspect' => 'Az) :attribute képarányának :aspect kell lennie.', ]; ================================================ FILE: lang/it/validation.php ================================================ 'Il campo :attribute dev\'essere :width in larghezza e :height in altezza.', 'between' => 'tra i :size1 e :size2 pixels', 'lessthan' => 'minore di :size pixels', 'lessthanorequal' => 'minore o uguale a :size pixels', 'greaterthan' => 'maggiore di :size pixels', 'greaterthanorequal' => 'maggiore o uguale a :size pixels', 'equal' => 'di :size pixels', 'anysize' => 'qualunque dimensione', 'image_aspect' => 'Il campo :attribute deve avere un ratio uguale a :aspect.', ]; ================================================ FILE: lang/lv/validation.php ================================================  ':attribute jābūt :width platam un :height augstam.', 'between' => 'starp :size1 un :size2 pikseļiem(i)', 'lessthan' => 'mazākam par :size pikseļiem(i)', 'lessthanorequal' => 'mazākam vai vienādam par :size pikseļiem(i)', 'greaterthan' => 'lielākam par :size pikseļiem(i)', 'greaterthanorequal' => 'lielākam vai vienādam par :size pikseļiem(i)', 'equal' => ':size pikseļus(i)', 'anysize' => 'jebkura izmēra', 'image_aspect' => ':attribute malu attiecībai jābūt :aspect.', ]; ================================================ FILE: lang/nl/validation.php ================================================ 'Het :attribute moet :width breed en :height hoog zijn.', 'between' => 'tussen :size1 en :size2 pixels', 'lessthan' => 'kleiner dan :size pixels', 'lessthanorequal' => 'maximaal :size pixels', 'greaterthan' => 'groter dan :size pixels', 'greaterthanorequal' => 'minimaal :size pixels', 'equal' => ':size pixels', 'anysize' => 'elke grootte', 'image_aspect' => 'De :attribute aspect ratio moet :aspect zijn.', ]; ================================================ FILE: lang/pt/validation.php ================================================ 'O campo :attribute tem que ser :width de largura e :height de altura.', 'between' => 'entre :size1 e :size2 pixels', 'lessthan' => 'menor que :size pixels', 'lessthanorequal' => 'menor ou igual a :size pixels', 'greaterthan' => 'maior que :size pixels', 'greaterthanorequal' => 'maior ou igual a :size pixels', 'equal' => 'de :size pixels', 'anysize' => 'qualquer tamanho', 'image_aspect' => 'A proporção do campo :attribute tem que ser de :aspect.', ]; ================================================ FILE: lang/pt-BR/validation.php ================================================ 'O campo :attribute tem que ser :width de largura e :height de altura.', 'between' => 'entre :size1 e :size2 pixels', 'lessthan' => 'menor que :size pixels', 'lessthanorequal' => 'menor ou igual a :size pixels', 'greaterthan' => 'maior que :size pixels', 'greaterthanorequal' => 'maior ou igual a :size pixels', 'equal' => 'de :size pixels', 'anysize' => 'qualquer tamanho', 'image_aspect' => 'A proporção do campo :attribute tem que ser de :aspect.', ]; ================================================ FILE: lang/ru/validation.php ================================================ 'Изображение :attribute должно быть :width по ширине и :height по высоте.', 'between' => 'между :size1 и :size2 пикселей(я)', 'lessthan' => 'меньше, чем :size пикселей(я)', 'lessthanorequal' => 'меньше или равно :size пикселей(я)', 'greaterthan' => 'больше, чем :size пикселей(я)', 'greaterthanorequal' => 'больше или равно :size пикселей(я)', 'equal' => ':size пикселей(я)', 'anysize' => 'любого размера', 'image_aspect' => ':attribute сжатие должно быть :aspect.', ]; ================================================ FILE: lang/sr/validation.php ================================================ ':attribute mora biti :width u širini i :height u visini.', 'between' => 'između :size1 i :size2 px', 'lessthan' => 'manja od :size px', 'lessthanorequal' => 'manja ili jednaka :size px', 'greaterthan' => 'veća od :size px', 'greaterthanorequal' => 'veća ili jednaka :size px', 'equal' => ':size px', 'anysize' => 'bilo kojih dimenzija', 'image_aspect' => ':attribute mora da bude u proporciji :aspect.', ]; ================================================ FILE: lang/tr/validation.php ================================================ ':attribute :width genişliği ve :height yüksekliği olmalıdır.', 'between' => ':size1 ve :size2 piksel aralığında', 'lessthan' => ':size pikselden az', 'lessthanorequal' => ':size piksele eşit veya az', 'greaterthan' => ':size pikselden fazla', 'greaterthanorequal' => ':size piksele eşit veya fazla', 'equal' => ':size piksel', 'anysize' => 'herhangi bir', 'image_aspect' => ':attribute en/boy oranı :aspect olmalıdır.', ]; ================================================ FILE: lang/zh-CN/validation.php ================================================ ':attribute 的宽度为 :width, 高度为 :height', 'between' => '必须在 :size1 和 :size2 像素之间', 'lessthan' => '必须小于 :size 像素', 'lessthanorequal' => '必须小于或等于 :size 像素', 'greaterthan' => '必须大于 :size 像素', 'greaterthanorequal' => '必须大于或等于 :size 像素', 'equal' => '必须等于 :size 像素', 'anysize' => '可以为任意大小', 'image_aspect' => ':attribute 长宽比必须为 :aspect', ]; ================================================ FILE: lang/zh-tw/validation.php ================================================ ':attribute 欄位的寬度 :width, 而高度 :height', 'between' => '必須介於 :size1 與 :size2 像素之間', 'lessthan' => '必須小於 :size 像素', 'lessthanorequal' => '必須小於或等於 :size 像素', 'greaterthan' => '必須大於 :size 像素', 'greaterthanorequal' => '必須大於或等於 :size 像素', 'equal' => '必須等於 :size 像素', 'anysize' => '可以是任意大小', 'image_aspect' => ':attribute 欄位的長寬比必須是 :aspect', ]; ================================================ FILE: phpunit.xml ================================================ ./tests/ src/ ================================================ FILE: src/ImageValidator.php ================================================ getImagePath($value); // Get the image dimension info, or fail. $image_size = @getimagesize($image); if ($image_size === false) { return false; } // If only one dimension rule is passed, assume it applies to both height and width. if (!isset($parameters[1])) { $parameters[1] = $parameters[0]; } // Parse the parameters. Options are: // // "300" or "=300" - dimension must be exactly 300 pixels // "<300" - dimension must be less than 300 pixels // "<=300" - dimension must be less than or equal to 300 pixels // ">300" - dimension must be greater than 300 pixels // ">=300" - dimension must be greater than or equal to 300 pixels $width_check = $this->checkDimension($parameters[0], $image_size[0]); $height_check = $this->checkDimension($parameters[1], $image_size[1]); return $width_check['pass'] && $height_check['pass']; } /** * Build the error message for validation failures. * * @param string $message * @param string $attribute * @param string $rule * @param array $parameters * @return string */ public function replaceImageSize($message, $attribute, $rule, $parameters) { $width = $height = $this->checkDimension($parameters[0]); if (isset($parameters[1])) { $height = $this->checkDimension($parameters[1]); } return str_replace( [':width', ':height'], [$width['message'], $height['message']], $message ); } /** * Usage: image_aspect:ratio * * @param $attribute string * @param $value string|array * @param $parameters array * @return boolean * @throws \RuntimeException */ public function validateImageAspect($attribute, $value, $parameters) { $image = $this->getImagePath($value); // Get the image dimension info, or fail. $image_size = @getimagesize($image); if ($image_size === false) { return false; } $image_width = $image_size[0]; $image_height = $image_size[1]; // Parse the parameter(s). Options are: // // "0.75" - one param: a decimal ratio (width/height) // "3,4" - two params: width, height // // If the first value is prefixed with "~", the orientation doesn't matter, i.e.: // // "~3,4" - would accept either "3:4" or "4:3" images $both_orientations = false; if (substr($parameters[0], 0, 1) === '~') { $parameters[0] = substr($parameters[0], 1); $both_orientations = true; } if (count($parameters) === 1) { $aspect_width = $parameters[0]; $aspect_height = 1; } else { $aspect_width = (int) $parameters[0]; $aspect_height = (int) $parameters[1]; } if ($aspect_width === 0 || $aspect_height === 0) { throw new RuntimeException('Aspect is zero or infinite: ' . $parameters[0]); } $check = ($image_width * $aspect_height) / $aspect_width; if ((int) round($check) === $image_height) { return true; } if ($both_orientations) { $check = ($image_width * $aspect_width) / $aspect_height; if ((int) round($check) === $image_height) { return true; } } return false; } /** * Build the error message for validation failures. * * @param string $message * @param string $attribute * @param string $rule * @param array $parameters * @return string */ public function replaceImageAspect($message, $attribute, $rule, $parameters) { return str_replace(':aspect', implode(':', $parameters), $message); } /** * Parse the dimension rule and check if the dimension passes the rule. * * @param string $rule * @param integer $dimension * @return array * @throws \RuntimeException */ protected function checkDimension($rule, $dimension = 0) { $dimension = (int) $dimension; if ($rule === '*') { $message = $this->translator->trans('image-validator::validation.anysize'); $pass = true; } else if (preg_match('/^(\d+)\-(\d+)$/', $rule, $matches)) { $size1 = (int) $matches[1]; $size2 = (int) $matches[2]; $message = $this->translator->trans('image-validator::validation.between', compact('size1', 'size2')); $pass = ($dimension >= $size1) && ($dimension <= $size2); } else if (preg_match('/^([<=>]*)(\d+)$/', $rule, $matches)) { $size = (int) $matches[2]; switch ($matches[1]) { case '>': $message = $this->translator->trans('image-validator::validation.greaterthan', compact('size')); $pass = $dimension > $size; break; case '>=': $message = $this->translator->trans('image-validator::validation.greaterthanorequal', compact('size')); $pass = $dimension >= $size; break; case '<': $message = $this->translator->trans('image-validator::validation.lessthan', compact('size')); $pass = $dimension < $size; break; case '<=': $message = $this->translator->trans('image-validator::validation.lessthanorequal', compact('size')); $pass = $dimension <= $size; break; case '=': case '': $message = $this->translator->trans('image-validator::validation.equal', compact('size')); $pass = $dimension == $size; break; default: throw new RuntimeException('Unknown image size validation rule: ' . $rule); } } else { throw new RuntimeException('Unknown image size validation rule: ' . $rule); } return compact('message', 'pass'); } /** * @param mixed $value * @return string */ protected function getImagePath($value) { // if were passed an instance of UploadedFile, return the path if ($value instanceof UploadedFile) { return $value->getPathname(); } // if we're passed a PHP file upload array, return the "tmp_name" if (is_array($value) && array_get($value, 'tmp_name') !== null) { return $value['tmp_name']; } // fallback: we were likely passed a path already return $value; } } ================================================ FILE: src/ImageValidatorServiceProvider.php ================================================ loadTranslationsFrom(__DIR__ . '/../lang', 'image-validator'); $messages = trans('image-validator::validation'); $this->app->bind(ImageValidator::class, function($app) use ($messages) { $validator = new ImageValidator($app['translator'], [], [], $messages); if (isset($app['validation.presence'])) { $validator->setPresenceVerifier($app['validation.presence']); } return $validator; }); $this->addNewRules(); } /** * Get the list of new rules being added to the validator. * * @return array */ public function getRules() { return $this->rules; } /** * Add new rules to the validator. */ protected function addNewRules() { foreach ($this->getRules() as $rule) { $this->extendValidator($rule); } } /** * Extend the validator with new rules. * * @param string $rule * @return void */ protected function extendValidator($rule) { $method = studly_case($rule); $translation = $this->app['translator']->trans('image-validator::validation.' . $rule); $this->app['validator']->extend($rule, 'Cviebrock\ImageValidator\ImageValidator@validate' . $method, $translation); $this->app['validator']->replacer($rule, 'Cviebrock\ImageValidator\ImageValidator@replace' . $method); } } ================================================ FILE: tests/.gitkeep ================================================ ================================================ FILE: tests/ValidateServiceProviderTest.php ================================================ assertTrue(true); } } ================================================ FILE: tests/ValidatorImageAspectTest.php ================================================ translator = Mockery::mock(Translator::class); $this->translator->shouldReceive('trans'); $this->data = [ 'image' => __DIR__ . '/images/200x250.png', ]; } public function tearDown() { Mockery::close(); } public function testValidatesAspect() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_aspect:4,5'] ); $this->assertTrue($validator->passes()); } public function testValidatesAspectDecimal() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_aspect:0.8'] ); $this->assertTrue($validator->passes()); } public function testValidatesReverseAspect() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_aspect:~5,4'] ); $this->assertTrue($validator->passes()); } public function testValidatesReverseAspectDecimal() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_aspect:~1.25'] ); $this->assertTrue($validator->passes()); } public function testRoundingAspects() { $validator = new ImageValidator( $this->translator, ['image' => __DIR__ . '/images/1024x682.png'], ['image' => 'image_aspect:3,2'] ); $this->assertFalse($validator->passes()); $validator = new ImageValidator( $this->translator, ['image' => __DIR__ . '/images/1024x683.png'], ['image' => 'image_aspect:3,2'] ); $this->assertTrue($validator->passes()); } } ================================================ FILE: tests/ValidatorImageSizeTest.php ================================================ translator = Mockery::mock(Translator::class); $this->translator->shouldReceive('trans'); $this->data = [ 'image' => __DIR__ . '/images/200x250.png', ]; } public function tearDown() { Mockery::close(); } public function testValidatesMatch() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:200,250'] ); $this->assertTrue($validator->passes()); } public function testValidatesSquare() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:200'] ); $this->assertTrue($validator->fails()); } public function testValidatesLessThan() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:<200,<250'] ); $this->assertTrue($validator->fails()); } public function testValidatesLessThanEqual() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:<=200,<=250'] ); $this->assertTrue($validator->passes()); } public function testValidatesGreaterThan() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:>200,>250'] ); $this->assertTrue($validator->fails()); } public function testValidatesGreaterThanEqual() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:>=200,>=250'] ); $this->assertTrue($validator->passes()); } public function testValidatesAnySize() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:*,250'] ); $this->assertTrue($validator->passes()); } public function testValidatesRange() { $validator = new ImageValidator( $this->translator, $this->data, ['image' => 'image_size:200-300'] ); $this->assertTrue($validator->passes()); } }