├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── code_of_conduct.md ├── composer.json ├── contributing.md ├── phpunit.xml.dist ├── src ├── EloquentDataProvider.php ├── EloquentProcessingService.php ├── EloquentProcessorResolver.php ├── Exception │ ├── EloquentDataProcessingExceptionInterface.php │ └── InvalidDataSourceException.php └── Processor │ ├── FilterProcessor.php │ ├── PaginateProcessor.php │ └── SortProcessor.php └── tests ├── bootstrap.php ├── mock └── TestUser.php └── phpunit ├── DataSourceSupportTest.php ├── DbTableProcessingServiceTest.php └── Processor ├── FilterProcessorTest.php └── PaginateProcessorTest.php /.gitignore: -------------------------------------------------------------------------------- 1 | vendor 2 | composer.phar 3 | composer.lock 4 | apigen.phar 5 | phpunit.phar 6 | build 7 | *.sqlite 8 | .env -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | php: 4 | - 5.5 5 | - 5.6 6 | - 7.0 7 | - hhvm 8 | - nightly 9 | matrix: 10 | allow_failures: 11 | - php: nightly 12 | sudo: false 13 | 14 | before_script: 15 | - travis_retry composer self-update 16 | - travis_retry composer create-project --prefer-source --no-interaction 17 | 18 | script: 19 | - vendor/bin/phpunit 20 | - vendor/bin/phpcs --standard=psr2 src/ 21 | 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015—2016 Vitalii Stepanenko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Logo](https://raw.githubusercontent.com/view-components/logo/master/view-components-logo-without-text-42.png) ViewComponents\EloquentDataProcessing 2 | ===== 3 | 4 | [![Release](https://img.shields.io/packagist/v/view-components/eloquent-data-processing.svg)](https://packagist.org/packages/view-components/eloquent-data-processing) 5 | [![Build Status](https://travis-ci.org/view-components/eloquent-data-processing.svg?branch=master)](https://travis-ci.org/view-components/eloquent-data-processing) 6 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/view-components/eloquent-data-processing/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/view-components/eloquent-data-processing/?branch=master) 7 | [![Code Coverage](https://scrutinizer-ci.com/g/view-components/eloquent-data-processing/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/view-components/eloquent-data-processing/?branch=master) 8 | 9 | Eloquent ORM support for ViewComponents 10 | 11 | 12 | ## Table of Contents 13 | - [Requirements](#requirements) 14 | - [Installation](#installation) 15 | - [Usage](#usage) 16 | - [Contributing](#contributing) 17 | - [Testing](#testing) 18 | - [Security](#security) 19 | - [License](#license) 20 | 21 | 22 | ## Requirements 23 | 24 | * PHP 5.5+ (hhvm & php7 are supported) 25 | 26 | 27 | ## Installation 28 | 29 | The recommended way of installing the component is through [Composer](https://getcomposer.org). 30 | 31 | Run following command: 32 | 33 | ```bash 34 | composer require view-components/eloquent-data-processing 35 | ``` 36 | 37 | ## Usage 38 | 39 | ### Creating Data Provider 40 | 41 | EloquentDataProvider supports 3 types of data sources: 42 | 43 | - Illuminate\Database\Eloquent\Builder instance (database query builder created from model) 44 | - Illuminate\Database\Query\Builder instance (standard database query builder, don't know about models) 45 | - Class name of Eloquent model 46 | 47 | #### Using Class Name of Eloquent Model as Data Source 48 | 49 | ```php 50 | use MyApp\UserModel; 51 | use ViewComponents\Eloquent\EloquentDataProvider; 52 | $provider = new EloquentDataProvider(UserModel::class); 53 | ``` 54 | 55 | If you use class name of Eloquent model as data source, 56 | the only way to modify database query is specifying data provider operations: 57 | 58 | 59 | ```php 60 | use ViewComponents\ViewComponents\Data\Operation\FilterOperation; 61 | 62 | $provider->operations()->add( 63 | new FilterOperation('role', FilterOperation::OPERATOR_EQ, 'Manager') 64 | ); 65 | ``` 66 | #### Using Illuminate\Database\Eloquent\Builder as Data Source 67 | 68 | ```php 69 | use ViewComponents\Eloquent\EloquentDataProvider; 70 | 71 | $provider = new EloquentDataProvider((new MyApp\UserModel)->newQuery()); 72 | ``` 73 | 74 | It's possible to specify query parts before creating EloquentDataProvider 75 | but note that some parts of query may be changed by data provider operations. 76 | 77 | ```php 78 | use ViewComponents\Eloquent\EloquentDataProvider; 79 | 80 | $query = MyApp\UserModel 81 | ::where('role', '=', 'Manager') 82 | ->where('company', '=', 'Facebook') 83 | ->orderBy('id'); 84 | 85 | $provider = new EloquentDataProvider($query); 86 | ``` 87 | 88 | #### Using Illuminate\Database\Query\Builder as Data Source 89 | 90 | It's possible to use EloquentDataProvider if you not deal with Eloquent models. 91 | 92 | ```php 93 | use DB; 94 | use ViewComponents\Eloquent\EloquentDataProvider; 95 | 96 | $provider = new EloquentDataProvider( 97 | DB::table('users')->where('name', '=', 'David') 98 | ); 99 | ``` 100 | 101 | ### Data Provider Operations 102 | 103 | Eloquent Data provider modifies database query when it has operations. 104 | 105 | Use operations() method for accessing operations collection. 106 | 107 | Documentation related to collections can be found [here](https://github.com/Nayjest/Collection). 108 | 109 | Example of adding operation: 110 | 111 | ```php 112 | $provider 113 | ->operations() 114 | ->add(new SortOperation('id', SortOperation::ASC)); 115 | 116 | ``` 117 | 118 | Also operations can be specified on data provider creation: 119 | 120 | ```php 121 | 122 | use MyApp\UserModel; 123 | use ViewComponents\Eloquent\EloquentDataProvider; 124 | use ViewComponents\ViewComponents\Data\Operation\FilterOperation; 125 | 126 | $provider = new EloquentDataProvider( 127 | UserModel::class 128 | [ 129 | new FilterOperation('role', FilterOperation::OPERATOR_EQ, 'Manager') 130 | new SortOperation('id', SortOperation::DESC), 131 | ] 132 | ); 133 | ``` 134 | 135 | ### Extracting data 136 | 137 | Data providers implements IteratorAggregate interface, so you can iterate it like array: 138 | ```php 139 | 140 | use MyApp\UserModel; 141 | use ViewComponents\Eloquent\EloquentDataProvider; 142 | 143 | $provider = new EloquentDataProvider(UserModel::class); 144 | foreach ($provider as $user) { 145 | var_dump($user); // instance of UserModel 146 | } 147 | 148 | ``` 149 | Data provider executes DB query when getIterator() method is called or when iteration begins in case if data is not loaded yet, 150 | i. e. calling getIterator() twice will not produce 2 database queries. 151 | But changing operations collection will cause resetting cache: 152 | 153 | ```php 154 | 155 | use MyApp\UserModel; 156 | use ViewComponents\Eloquent\EloquentDataProvider; 157 | use ViewComponents\ViewComponents\Data\Operation\FilterOperation; 158 | 159 | $provider = new EloquentDataProvider(UserModel::class); 160 | // databse query will be executed 161 | $provider->getIterator(); 162 | 163 | // databse query will not be executed again, iterating over same data 164 | $provider->getIterator(); 165 | 166 | $provider->operations->add( 167 | new FilterOperation('id', FilterOperation::OPERATOR_LTE, 5) 168 | ) 169 | // databse query will be executed again 170 | $provider->getIterator(); 171 | 172 | ``` 173 | 174 | 175 | ## Contributing 176 | 177 | Please see [Contributing Guidelines](contributing.md) and [Code of Conduct](code_of_conduct.md) for details. 178 | 179 | 180 | ## Testing 181 | 182 | This package bundled with unit tests (PHPUnit). 183 | 184 | To run tests locally, you must install this package as stand-alone project with dev-dependencies: 185 | 186 | ```bash 187 | composer create-project view-components/eloquent-data-processing 188 | ``` 189 | 190 | Command for running tests: 191 | 192 | ```bash 193 | composer test 194 | ``` 195 | 196 | 197 | ## Security 198 | 199 | If you discover any security related issues, please email mail@vitaliy.in instead of using the issue tracker. 200 | 201 | 202 | ## License 203 | 204 | © 2015 — 2016 Vitalii Stepanenko 205 | 206 | Licensed under the MIT License. 207 | 208 | Please see [License File](LICENSE) for more information. 209 | -------------------------------------------------------------------------------- /code_of_conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at mail@vitaliy.in. The project team 59 | will review and investigate all complaints, and will respond in a way that it deems 60 | appropriate to the circumstances. The project team is obligated to maintain 61 | confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "view-components/eloquent-data-processing", 3 | "description": "Eloquent ORM support for ViewComponents", 4 | "keywords": [ 5 | "laravel", 6 | "laravel-5", 7 | "laravel5", 8 | "laravel4", 9 | "laravel-4" 10 | ], 11 | "homepage": "https://github.com/view-components/eloquent-data-processing", 12 | "type": "library", 13 | "license": "MIT", 14 | "authors": [ 15 | { 16 | "name": "Vitalii [Nayjest] Stepanenko", 17 | "email": "mail@vitaliy.in", 18 | "role": "Developer" 19 | } 20 | ], 21 | "require": { 22 | "view-components/view-components": "^0.24.2||^0.25||^0.26.6", 23 | "php": "^5.5||^7||^8" 24 | }, 25 | "require-dev": { 26 | "view-components/testing-helpers":"^2.0.1", 27 | "illuminate/database": "*" 28 | }, 29 | "autoload": { 30 | "psr-4": { 31 | "ViewComponents\\Eloquent\\": "src/" 32 | } 33 | }, 34 | "autoload-dev": { 35 | "psr-4": { 36 | "ViewComponents\\Eloquent\\Test\\Mock\\": "tests/mock/", 37 | "ViewComponents\\Eloquent\\Test\\": "tests/phpunit/" 38 | } 39 | }, 40 | "scripts": { 41 | "post-create-project-cmd": [ 42 | "ViewComponents\\TestingHelpers\\Installer\\Installer::runFromComposer" 43 | ], 44 | "post-update-cmd": [ 45 | "ViewComponents\\TestingHelpers\\Installer\\Installer::runFromComposer" 46 | ], 47 | "post-install-cmd": [ 48 | "ViewComponents\\TestingHelpers\\Installer\\Installer::runFromComposer" 49 | ], 50 | "test": "php vendor/phpunit/phpunit/phpunit", 51 | "cs": "php vendor/squizlabs/php_codesniffer/scripts/phpcs --standard=psr2 src/" 52 | }, 53 | "support": { 54 | "email": "mail@vitaliy.in", 55 | "source": "https://github.com/view-components/eloquent-data-processing", 56 | "issues": "https://github.com/view-components/eloquent-data-processing/issues" 57 | }, 58 | "minimum-stability": "stable" 59 | } 60 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | Contributing Guidelines 2 | === 3 | 4 | Contributions are **welcome** and will be fully **credited**. 5 | 6 | We accept contributions via Pull Requests on [Github](https://github.com/view-components/eloquent-data-processing). 7 | 8 | 9 | ## Pull Requests 10 | 11 | - **[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 use [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). Run `composer cs` before creating pull-request. 12 | 13 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 14 | 15 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 16 | 17 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 18 | 19 | - **Create feature branches** - Don't ask us to pull from your master branch. 20 | 21 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 22 | 23 | - **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 before submitting. 24 | 25 | 26 | ## Running Tests 27 | 28 | ``` bash 29 | $ composer test 30 | ``` 31 | 32 | 33 | **Happy coding**! 34 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ./tests/phpunit 6 | 7 | 8 | 9 | 10 | ./src 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/EloquentDataProvider.php: -------------------------------------------------------------------------------- 1 | validateSource($src); 25 | $this->operations()->set($operations); 26 | $this->processingService = new EloquentProcessingService( 27 | new EloquentProcessorResolver(), 28 | $this->operations(), 29 | $src 30 | ); 31 | } 32 | 33 | protected function validateSource($src) 34 | { 35 | if ($src instanceof EloquentBuilder || $src instanceof Builder) { 36 | return $src; 37 | } 38 | 39 | if (is_string($src) && class_exists($src) && is_a($src, Model::class, true)) { 40 | /** @var Model $model */ 41 | $model = new $src; 42 | return $model->newQuery(); 43 | } 44 | 45 | throw InvalidDataSourceException::forSrc($src); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/EloquentProcessingService.php: -------------------------------------------------------------------------------- 1 | get(); 25 | } elseif ($data instanceof Builder) { 26 | return new ArrayIterator($data->get()); 27 | } 28 | throw new RuntimeException('Unsupported type of data source.'); 29 | } 30 | 31 | /** 32 | * @param Builder|EloquentBuilder $data 33 | * @return Builder|EloquentBuilder 34 | */ 35 | protected function beforeOperations($data) 36 | { 37 | return clone $data; 38 | } 39 | 40 | /** 41 | * @return int 42 | */ 43 | public function count() 44 | { 45 | return $this->applyOperations( 46 | $this->beforeOperations($this->dataSource) 47 | )->count(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/EloquentProcessorResolver.php: -------------------------------------------------------------------------------- 1 | register(SortOperation::class, SortProcessor::class) 19 | ->register(FilterOperation::class, FilterProcessor::class) 20 | ->register(PaginateOperation::class, PaginateProcessor::class) 21 | ; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Exception/EloquentDataProcessingExceptionInterface.php: -------------------------------------------------------------------------------- 1 | getValue(); 20 | $operator = $operation->getOperator(); 21 | $field = $operation->getField(); 22 | switch ($operator) { 23 | case FilterOperation::OPERATOR_STR_STARTS_WITH: 24 | $operator = FilterOperation::OPERATOR_LIKE; 25 | $value .= '%'; 26 | break; 27 | case FilterOperation::OPERATOR_STR_ENDS_WITH: 28 | $operator = FilterOperation::OPERATOR_LIKE; 29 | $value = '%' . $value; 30 | break; 31 | case FilterOperation::OPERATOR_STR_CONTAINS: 32 | $operator = FilterOperation::OPERATOR_LIKE; 33 | $value = '%' . $value . '%'; 34 | break; 35 | case FilterOperation::OPERATOR_SET_CONTAINS: 36 | $values = is_array($value) 37 | ? $value 38 | : array_map(function($value){ 39 | return trim($value); 40 | }, preg_split('/[\n\t\,\|\s]+/', trim($value)) 41 | ); 42 | 43 | $src->whereIn($field, $values); 44 | return $src; 45 | } 46 | $src->where($field, $operator, $value); 47 | return $src; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Processor/PaginateProcessor.php: -------------------------------------------------------------------------------- 1 | limit($operation->getPageSize()) 22 | ->offset($this->getOffset($operation)); 23 | return $src; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Processor/SortProcessor.php: -------------------------------------------------------------------------------- 1 | getField(); 20 | $order = $operation->getOrder(); 21 | $src->orderBy($field, $order); 22 | return $src; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | addConnection([ 6 | 'driver' => 'sqlite', 7 | 'database' => __DIR__ . '/../db.sqlite', 8 | 'prefix' => '', 9 | ]); 10 | $capsule->setAsGlobal(); 11 | $capsule->bootEloquent(); 12 | // set timezone for timestamps etc 13 | date_default_timezone_set('UTC'); -------------------------------------------------------------------------------- /tests/mock/TestUser.php: -------------------------------------------------------------------------------- 1 | newQuery()); 16 | self::assertEquals( 17 | DefaultFixture::getTotalCount(), 18 | $provider->count() 19 | ); 20 | } 21 | 22 | public function testEloquentBuilderWithPreCondition() 23 | { 24 | $provider = new EloquentDataProvider(TestUser::where('name', '=', 'David')); 25 | self::assertEquals( 26 | 1, 27 | $provider->count() 28 | ); 29 | } 30 | 31 | public function testModelName() 32 | { 33 | $provider = new EloquentDataProvider(TestUser::class); 34 | self::assertEquals( 35 | DefaultFixture::getTotalCount(), 36 | $provider->count() 37 | ); 38 | } 39 | 40 | public function testDatabaseQueryBuilder() 41 | { 42 | $provider = new EloquentDataProvider(DB::table('test_users')); 43 | self::assertEquals( 44 | DefaultFixture::getTotalCount(), 45 | $provider->count() 46 | ); 47 | } 48 | 49 | public function testDatabaseQueryBuilderWithPreCondition() 50 | { 51 | $provider = new EloquentDataProvider( 52 | DB 53 | ::table('test_users') 54 | ->where('name', '=', 'David') 55 | ->orderBy('id') 56 | ); 57 | self::assertEquals( 58 | 1, 59 | $provider->count() 60 | ); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/phpunit/DbTableProcessingServiceTest.php: -------------------------------------------------------------------------------- 1 | data = (new TestUser())->newQuery(); 18 | $this->operations = new OperationCollection(); 19 | $this->service = new EloquentProcessingService( 20 | new EloquentProcessorResolver(), 21 | $this->operations, 22 | $this->data 23 | ); 24 | $this->totalCount = (new TestUser())->newQuery()->get()->count(); 25 | } 26 | } -------------------------------------------------------------------------------- /tests/phpunit/Processor/FilterProcessorTest.php: -------------------------------------------------------------------------------- 1 | count(); 15 | if ($recordsQty <= 5) { 16 | throw new \Exception("Can't test PaginateProcessor: not enough fixture data"); 17 | } 18 | $provider = new EloquentDataProvider(TestUser::class); 19 | $provider->operations()->add(new PaginateOperation(1,3)); 20 | $data = iterator_to_array($provider); 21 | $id1 = array_first($data)->id; 22 | self::assertEquals(3, count($data)); 23 | 24 | $provider = new EloquentDataProvider(DB::table((new TestUser)->getTable())); 25 | $provider->operations()->add(new PaginateOperation(2,2)); 26 | $data = iterator_to_array($provider); 27 | self::assertEquals(2, count($data)); 28 | 29 | $id2 = array_first($data)->id; 30 | self::assertTrue($id2 > 0 && $id2 > 0 && $id1 !== $id2); 31 | } 32 | } 33 | --------------------------------------------------------------------------------