├── logo.png ├── .gitignore ├── tests ├── bootstrap.php ├── MyTestClass.php ├── Handler │ ├── ExceptionTestDataTable.php │ ├── InvalidResultsTestDataTable.php │ ├── CustomDataTestDataTable.php │ ├── SuccessfulTestDataTable.php │ └── AutoloadedTestDataTable.php ├── DataTableExceptionTest.php ├── DataTableResultsTest.php ├── DependencyInjection │ └── DataTablesExtensionTest.php ├── OrderTest.php ├── SearchTest.php ├── ValueObjectTest.php ├── ColumnTest.php ├── DataTableQueryTest.php └── DataTablesTest.php ├── src ├── Resources │ └── config │ │ └── datatables.yml ├── AbstractDataTableHandler.php ├── DataTablesBundle.php ├── DataTableException.php ├── DataTableHandlerInterface.php ├── DataTablesInterface.php ├── Search.php ├── Order.php ├── ValueObject.php ├── Column.php ├── DependencyInjection │ └── DataTablesExtension.php ├── DataTableResults.php ├── DataTableQuery.php ├── Parameters.php └── DataTables.php ├── .scrutinizer.yml ├── .travis.yml ├── phpunit.xml.dist ├── LICENSE ├── .php-cs-fixer.dist.php ├── composer.json └── README.md /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webinarium/DataTablesBundle/HEAD/logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /vendor/ 3 | /.php-cs-fixer.php 4 | /.php-cs-fixer.cache 5 | /composer.lock 6 | /composer.phar 7 | .phpunit.result.cache 8 | /phpunit.xml 9 | -------------------------------------------------------------------------------- /tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | abstract class AbstractDataTableHandler implements DataTableHandlerInterface 17 | { 18 | } 19 | -------------------------------------------------------------------------------- /src/DataTablesBundle.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Symfony\Component\HttpKernel\Bundle\Bundle; 17 | 18 | class DataTablesBundle extends Bundle 19 | { 20 | } 21 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | ./tests 13 | 14 | 15 | 16 | 17 | 18 | ./src 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/MyTestClass.php: -------------------------------------------------------------------------------- 1 | . 9 | // 10 | //---------------------------------------------------------------------- 11 | 12 | namespace DataTables; 13 | 14 | /** 15 | * @property mixed $property 16 | */ 17 | class MyTestClass extends ValueObject 18 | { 19 | protected $property; 20 | 21 | public function setProperty($value) 22 | { 23 | $this->property = $value; 24 | } 25 | 26 | public function getProperty() 27 | { 28 | return $this->property; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/Handler/ExceptionTestDataTable.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\Handler; 15 | 16 | use DataTables\DataTableException; 17 | use DataTables\DataTableHandlerInterface; 18 | use DataTables\DataTableQuery; 19 | use DataTables\DataTableResults; 20 | 21 | class ExceptionTestDataTable implements DataTableHandlerInterface 22 | { 23 | public function handle(DataTableQuery $request, array $context = []): DataTableResults 24 | { 25 | throw new DataTableException('Something gone wrong.'); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/DataTableException.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; 17 | 18 | /** 19 | * Exception from a DataTable request handling. 20 | * Contains HTTP status code and can be used in HTTP Response object. 21 | */ 22 | class DataTableException extends BadRequestHttpException 23 | { 24 | /** 25 | * {@inheritdoc} 26 | */ 27 | public function __construct(string $message, int $code = 0, \Throwable $previous = null) 28 | { 29 | parent::__construct($message, $previous, $code); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tests/Handler/InvalidResultsTestDataTable.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\Handler; 15 | 16 | use DataTables\DataTableHandlerInterface; 17 | use DataTables\DataTableQuery; 18 | use DataTables\DataTableResults; 19 | 20 | class InvalidResultsTestDataTable implements DataTableHandlerInterface 21 | { 22 | public function handle(DataTableQuery $request, array $context = []): DataTableResults 23 | { 24 | $results = new DataTableResults(); 25 | 26 | $results->recordsTotal = 100; 27 | $results->recordsFiltered = 10; 28 | $results->data = null; 29 | 30 | return $results; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Handler/CustomDataTestDataTable.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\Handler; 15 | 16 | use DataTables\DataTableHandlerInterface; 17 | use DataTables\DataTableQuery; 18 | use DataTables\DataTableResults; 19 | 20 | class CustomDataTestDataTable implements DataTableHandlerInterface 21 | { 22 | public function handle(DataTableQuery $request, array $context = []): DataTableResults 23 | { 24 | $results = new DataTableResults(); 25 | 26 | $results->recordsTotal = 100; 27 | $results->recordsFiltered = 10; 28 | $results->data = $request->customData; 29 | 30 | return $results; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Handler/SuccessfulTestDataTable.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\Handler; 15 | 16 | use DataTables\DataTableHandlerInterface; 17 | use DataTables\DataTableQuery; 18 | use DataTables\DataTableResults; 19 | 20 | class SuccessfulTestDataTable implements DataTableHandlerInterface 21 | { 22 | public function handle(DataTableQuery $request, array $context = []): DataTableResults 23 | { 24 | $results = new DataTableResults(); 25 | 26 | $results->recordsTotal = 100; 27 | $results->recordsFiltered = $context['test'] ?? 10; 28 | $results->data = []; 29 | 30 | return $results; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Handler/AutoloadedTestDataTable.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\Handler; 15 | 16 | use DataTables\AbstractDataTableHandler; 17 | use DataTables\DataTableQuery; 18 | use DataTables\DataTableResults; 19 | 20 | class AutoloadedTestDataTable extends AbstractDataTableHandler 21 | { 22 | public const ID = 'testAuto'; 23 | 24 | public function handle(DataTableQuery $request, array $context = []): DataTableResults 25 | { 26 | $results = new DataTableResults(); 27 | 28 | $results->recordsTotal = 200; 29 | $results->recordsFiltered = 20; 30 | $results->data = []; 31 | 32 | return $results; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2015-2022 Artem Rodygin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, 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, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/DataTableHandlerInterface.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * DataTable handler. 18 | */ 19 | interface DataTableHandlerInterface 20 | { 21 | /** 22 | * Optional DataTable ID. 23 | */ 24 | public const ID = null; 25 | 26 | /** 27 | * Handles specified DataTable request. 28 | * 29 | * @param DataTableQuery $request Original request 30 | * @param array $context Optional context of the request 31 | * 32 | * @return DataTableResults Object with data to return in JSON response 33 | * 34 | * @throws DataTableException 35 | */ 36 | public function handle(DataTableQuery $request, array $context = []): DataTableResults; 37 | } 38 | -------------------------------------------------------------------------------- /tests/DataTableExceptionTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | 18 | /** 19 | * @coversDefaultClass \DataTables\DataTableException 20 | * 21 | * @internal 22 | */ 23 | final class DataTableExceptionTest extends TestCase 24 | { 25 | /** 26 | * @covers ::__construct 27 | */ 28 | public function testConstructor(): void 29 | { 30 | $expectedMessage = 'Error message'; 31 | $expectedCode = mt_rand(); 32 | 33 | $object = new DataTableException($expectedMessage, $expectedCode); 34 | 35 | self::assertSame($expectedMessage, $object->getMessage()); 36 | self::assertSame($expectedCode, $object->getCode()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/DataTablesInterface.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Symfony\Component\HttpFoundation\Request; 17 | 18 | /** 19 | * DataTables lookup service. 20 | */ 21 | interface DataTablesInterface 22 | { 23 | /** 24 | * Handles specified HTTP request. 25 | * 26 | * @param Request $request Original HTTP request 27 | * @param string $id ID of the DataTable the request belongs to 28 | * @param array $context Optional context of the request 29 | * 30 | * @return DataTableResults Object with data to return in JSON response 31 | * 32 | * @throws DataTableException 33 | */ 34 | public function handle(Request $request, string $id, array $context = []): DataTableResults; 35 | } 36 | -------------------------------------------------------------------------------- /.php-cs-fixer.dist.php: -------------------------------------------------------------------------------- 1 | in(realpath(__DIR__ . '/src')) 5 | ->in(realpath(__DIR__ . '/tests')) 6 | ; 7 | 8 | return (new PhpCsFixer\Config()) 9 | ->setRiskyAllowed(true) 10 | ->setRules([ 11 | 12 | //-------------------------------------------------------------- 13 | // Rule sets 14 | //-------------------------------------------------------------- 15 | '@PSR1' => true, 16 | '@PSR2' => true, 17 | '@Symfony' => true, 18 | '@Symfony:risky' => true, 19 | '@PhpCsFixer' => true, 20 | '@PhpCsFixer:risky' => true, 21 | '@DoctrineAnnotation' => true, 22 | '@PHP70Migration' => true, 23 | 24 | //-------------------------------------------------------------- 25 | // Rules override 26 | //-------------------------------------------------------------- 27 | 'binary_operator_spaces' => ['default' => 'align'], 28 | 'native_function_invocation' => false, 29 | 'self_static_accessor' => true, 30 | 'single_line_comment_spacing' => false, 31 | ]) 32 | ->setFinder($finder) 33 | ; 34 | -------------------------------------------------------------------------------- /tests/DataTableResultsTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | 18 | /** 19 | * @coversDefaultClass \DataTables\DataTableResults 20 | * 21 | * @internal 22 | */ 23 | final class DataTableResultsTest extends TestCase 24 | { 25 | /** 26 | * @covers ::jsonSerialize 27 | */ 28 | public function testJsonSerializable(): void 29 | { 30 | $expected = json_encode([ 31 | 'draw' => 0, 32 | 'recordsTotal' => 100, 33 | 'recordsFiltered' => 78, 34 | 'data' => [], 35 | ]); 36 | 37 | $object = new DataTableResults(); 38 | 39 | $object->recordsTotal = 100; 40 | $object->recordsFiltered = 78; 41 | $object->data = []; 42 | 43 | self::assertSame($expected, json_encode($object)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/DependencyInjection/DataTablesExtensionTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\DependencyInjection; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | use Symfony\Component\DependencyInjection\ContainerBuilder; 18 | 19 | /** 20 | * @coversDefaultClass \DataTables\DependencyInjection\DataTablesExtension 21 | * 22 | * @internal 23 | */ 24 | final class DataTablesExtensionTest extends TestCase 25 | { 26 | /** 27 | * @covers ::load 28 | * @covers ::process 29 | */ 30 | public function testLoadServices(): void 31 | { 32 | $container = new ContainerBuilder(); 33 | 34 | self::assertFalse($container->has('datatables')); 35 | 36 | $extension = new DataTablesExtension(); 37 | $extension->load([], $container); 38 | $extension->process($container); 39 | 40 | self::assertTrue($container->has('datatables')); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Search.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * Search parameters as part of DataTables request. 18 | * 19 | * @see https://www.datatables.net/manual/server-side 20 | * 21 | * @property string $value Search value 22 | * @property bool $regex Whether the search value should be treated as a regular expression for advanced searching 23 | */ 24 | class Search extends ValueObject implements \JsonSerializable 25 | { 26 | protected $value; 27 | protected $regex; 28 | 29 | /** 30 | * Initializing constructor. 31 | */ 32 | public function __construct(string $value = null, bool $regex = false) 33 | { 34 | $this->value = $value; 35 | $this->regex = $regex; 36 | } 37 | 38 | /** 39 | * {@inheritdoc} 40 | */ 41 | public function jsonSerialize(): array 42 | { 43 | return [ 44 | 'value' => $this->value, 45 | 'regex' => $this->regex, 46 | ]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webinarium/datatables-bundle", 3 | "description": "DataTables Symfony bundle", 4 | "type": "symfony-bundle", 5 | "keywords": [ 6 | "datatable", 7 | "datatables" 8 | ], 9 | "homepage": "https://github.com/webinarium/DataTablesBundle", 10 | "license": "MIT", 11 | "support": { 12 | "source": "https://github.com/webinarium/DataTablesBundle", 13 | "wiki": "https://github.com/webinarium/DataTablesBundle/wiki", 14 | "issues": "https://github.com/webinarium/DataTablesBundle/issues" 15 | }, 16 | "require": { 17 | "php": ">=7.2", 18 | "ext-json": "*", 19 | "psr/log": "^2.0", 20 | "symfony/config": "^5.4|^6.0", 21 | "symfony/dependency-injection": "^5.4|^6.0", 22 | "symfony/http-foundation": "^5.4|^6.0", 23 | "symfony/http-kernel": "^5.4|^6.0", 24 | "symfony/validator": "^5.4|^6.0", 25 | "symfony/yaml": "^5.4|^6.0" 26 | }, 27 | "require-dev": { 28 | "doctrine/annotations": "^1.0", 29 | "friendsofphp/php-cs-fixer": "^3.13", 30 | "phpunit/phpunit": "^9.5", 31 | "symfony/cache": "^5.4|^6.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "DataTables\\": "src/" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "DataTables\\": "tests/" 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Order.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * Ordering parameters as part of DataTables request. 18 | * 19 | * @see https://www.datatables.net/manual/server-side 20 | * 21 | * @property int $column Column to which ordering should be applied 22 | * @property string $dir Ordering direction for this column 23 | */ 24 | class Order extends ValueObject implements \JsonSerializable 25 | { 26 | public const ASC = 'asc'; 27 | public const DESC = 'desc'; 28 | 29 | protected $column; 30 | protected $dir; 31 | 32 | /** 33 | * Initializing constructor. 34 | */ 35 | public function __construct(int $column, string $dir) 36 | { 37 | $this->column = $column; 38 | $this->dir = $dir; 39 | } 40 | 41 | /** 42 | * {@inheritdoc} 43 | */ 44 | public function jsonSerialize(): array 45 | { 46 | return [ 47 | 'column' => $this->column, 48 | 'dir' => $this->dir, 49 | ]; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/OrderTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | 18 | /** 19 | * @coversDefaultClass \DataTables\Order 20 | * 21 | * @internal 22 | */ 23 | final class OrderTest extends TestCase 24 | { 25 | /** 26 | * @covers ::__construct 27 | */ 28 | public function testConstructor(): void 29 | { 30 | $column = random_int(1, 10); 31 | $dir = Order::DESC; 32 | 33 | $object = new Order($column, $dir); 34 | 35 | self::assertSame($column, $object->column); 36 | self::assertSame($dir, $object->dir); 37 | } 38 | 39 | /** 40 | * @covers ::jsonSerialize 41 | */ 42 | public function testJsonSerializable(): void 43 | { 44 | $column = random_int(1, 10); 45 | $dir = Order::DESC; 46 | 47 | $expected = json_encode([ 48 | 'column' => $column, 49 | 'dir' => $dir, 50 | ]); 51 | 52 | $object = new Order($column, $dir); 53 | 54 | self::assertSame($expected, json_encode($object)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/SearchTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | 18 | /** 19 | * @coversDefaultClass \DataTables\Search 20 | * 21 | * @internal 22 | */ 23 | final class SearchTest extends TestCase 24 | { 25 | /** 26 | * @covers ::__construct 27 | */ 28 | public function testConstructor(): void 29 | { 30 | $value = bin2hex(random_bytes(10)); 31 | $regex = true; 32 | 33 | $object = new Search($value, $regex); 34 | 35 | self::assertSame($value, $object->value); 36 | self::assertSame($regex, $object->regex); 37 | } 38 | 39 | /** 40 | * @covers ::jsonSerialize 41 | */ 42 | public function testJsonSerializable(): void 43 | { 44 | $value = bin2hex(random_bytes(10)); 45 | $regex = true; 46 | 47 | $expected = json_encode([ 48 | 'value' => $value, 49 | 'regex' => $regex, 50 | ]); 51 | 52 | $object = new Search($value, $regex); 53 | 54 | self::assertSame($expected, json_encode($object)); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/ValueObject.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * Immutable value object. 18 | */ 19 | class ValueObject 20 | { 21 | /** 22 | * Checks whether specified property exists. 23 | * 24 | * @param string $name Name of the property 25 | * 26 | * @return bool TRUE if the property exists, FALSE otherwise 27 | */ 28 | public function __isset(string $name): bool 29 | { 30 | return property_exists($this, $name); 31 | } 32 | 33 | /** 34 | * Returns current value of specified property. 35 | * 36 | * @param string $name Name of the property 37 | * 38 | * @return mixed Current value of the property 39 | * 40 | * @throws \BadMethodCallException If the property doesn't exist 41 | */ 42 | public function __get(string $name) 43 | { 44 | if (!property_exists($this, $name)) { 45 | throw new \BadMethodCallException(sprintf('Unknown property "%s" in class "%s".', $name, static::class)); 46 | } 47 | 48 | return $this->{$name}; 49 | } 50 | 51 | /** 52 | * Prevents object's properties from modification. 53 | * 54 | * @param string $name Name of the property 55 | * @param mixed $value New value of the property 56 | */ 57 | final public function __set(string $name, $value) 58 | { 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PHP](https://img.shields.io/badge/PHP-7.2%2B-blue.svg)](https://secure.php.net/migration72) 2 | [![Latest Stable Version](https://poser.pugx.org/webinarium/datatables-bundle/v/stable)](https://packagist.org/packages/webinarium/datatables-bundle) 3 | [![Build Status](https://travis-ci.com/webinarium/DataTablesBundle.svg?branch=master)](https://travis-ci.com/github/webinarium/DataTablesBundle) 4 | [![Code Coverage](https://scrutinizer-ci.com/g/webinarium/DataTablesBundle/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/webinarium/DataTablesBundle/?branch=master) 5 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/webinarium/DataTablesBundle/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/webinarium/DataTablesBundle/?branch=master) 6 | 7 | # DataTables Symfony bundle 8 | 9 | This bundle helps to implement data source actions for [DataTables](http://www.datatables.net/) JavaScript plugin when it's used in [server-side processing](http://www.datatables.net/manual/server-side) mode. 10 | 11 | ## Requirements 12 | 13 | PHP needs to be a minimum version of PHP 7.2. 14 | 15 | Symfony must be of 5.4 or above. 16 | 17 | ## Installation 18 | 19 | Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle: 20 | 21 | ```console 22 | composer require webinarium/datatables-bundle 23 | ``` 24 | 25 | This command requires you to have Composer installed globally, as explained in the [installation chapter](https://getcomposer.org/doc/00-intro.md) of the Composer documentation. 26 | 27 | ## Development 28 | 29 | ```console 30 | ./vendor/bin/php-cs-fixer fix 31 | XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html=vendor/coverage 32 | ``` 33 | 34 | ## Usage 35 | 36 | Please see the complete usage example [here](../../wiki). 37 | -------------------------------------------------------------------------------- /tests/ValueObjectTest.php: -------------------------------------------------------------------------------- 1 | . 9 | // 10 | //---------------------------------------------------------------------- 11 | 12 | namespace DataTables; 13 | 14 | use PHPUnit\Framework\TestCase; 15 | 16 | /** 17 | * @coversDefaultClass \DataTables\ValueObject 18 | * 19 | * @internal 20 | */ 21 | final class ValueObjectTest extends TestCase 22 | { 23 | /** 24 | * @covers ::__isset 25 | */ 26 | public function testIsSet(): void 27 | { 28 | $object = new MyTestClass(); 29 | 30 | self::assertTrue(isset($object->property)); 31 | self::assertFalse(isset($object->unknown)); 32 | } 33 | 34 | /** 35 | * @covers ::__get 36 | */ 37 | public function testGetPropertySuccess(): void 38 | { 39 | $object = new MyTestClass(); 40 | $expected = mt_rand(); 41 | 42 | $object->setProperty($expected); 43 | 44 | self::assertSame($expected, $object->property); 45 | } 46 | 47 | /** 48 | * @covers ::__get 49 | */ 50 | public function testGetPropertyFailure(): void 51 | { 52 | $this->expectException(\Exception::class); 53 | 54 | $object = new MyTestClass(); 55 | 56 | echo $object->unknown; 57 | } 58 | 59 | /** 60 | * @covers ::__set 61 | */ 62 | public function testSetProperty(): void 63 | { 64 | $object = new MyTestClass(); 65 | $expected = mt_rand(); 66 | $ignored = mt_rand(); 67 | 68 | self::assertNotSame($expected, $ignored); 69 | 70 | $object->setProperty($expected); 71 | $object->property = $ignored; 72 | 73 | self::assertSame($expected, $object->property); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Column.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * Column parameters as part of DataTables request. 18 | * 19 | * @see https://www.datatables.net/manual/server-side 20 | * 21 | * @property string $data Column's data source 22 | * @property string $name Column's name 23 | * @property bool $searchable Flag to indicate if this column is searchable or not 24 | * @property bool $orderable Flag to indicate if this column is orderable or not 25 | * @property Search $search Search value to apply to this specific column 26 | */ 27 | class Column extends ValueObject implements \JsonSerializable 28 | { 29 | protected $data; 30 | protected $name; 31 | protected $searchable; 32 | protected $orderable; 33 | protected $search; 34 | 35 | /** 36 | * Initializing constructor. 37 | */ 38 | public function __construct(string $data, string $name, bool $searchable, bool $orderable, Search $search) 39 | { 40 | $this->data = $data; 41 | $this->name = $name; 42 | $this->searchable = $searchable; 43 | $this->orderable = $orderable; 44 | $this->search = $search; 45 | } 46 | 47 | /** 48 | * {@inheritdoc} 49 | */ 50 | public function jsonSerialize(): array 51 | { 52 | return [ 53 | 'data' => $this->data, 54 | 'name' => $this->name, 55 | 'searchable' => $this->searchable, 56 | 'orderable' => $this->orderable, 57 | 'search' => $this->search->jsonSerialize(), 58 | ]; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/DependencyInjection/DataTablesExtension.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables\DependencyInjection; 15 | 16 | use Symfony\Component\Config\FileLocator; 17 | use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; 18 | use Symfony\Component\DependencyInjection\ContainerBuilder; 19 | use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; 20 | use Symfony\Component\DependencyInjection\Reference; 21 | use Symfony\Component\HttpKernel\DependencyInjection\Extension; 22 | 23 | /** 24 | * This is the class that loads and manages the bundle configuration. 25 | * 26 | * To learn more see {@link https://symfony.com/doc/5.4/bundles/extension.html} 27 | */ 28 | class DataTablesExtension extends Extension implements CompilerPassInterface 29 | { 30 | /** 31 | * {@inheritdoc} 32 | */ 33 | public function load(array $configs, ContainerBuilder $container) 34 | { 35 | $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); 36 | $loader->load('datatables.yml'); 37 | } 38 | 39 | /** 40 | * {@inheritdoc} 41 | */ 42 | public function process(ContainerBuilder $container) 43 | { 44 | if (!$container->has('datatables')) { 45 | return; 46 | } 47 | 48 | $definition = $container->findDefinition('datatables'); 49 | $services = $container->findTaggedServiceIds('datatable'); 50 | 51 | foreach ($services as $id => $tags) { 52 | foreach ($tags as $tag) { 53 | $definition->addMethodCall('addService', [ 54 | new Reference($id), 55 | $tag['id'] ?? null, 56 | ]); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/DataTableResults.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Symfony\Component\Validator\Constraints as Assert; 17 | 18 | /** 19 | * Data to return to DataTables plugin. 20 | * 21 | * @see https://www.datatables.net/manual/server-side 22 | * 23 | * @property int $recordsTotal Total records, before filtering 24 | * @property int $recordsFiltered Total records, after filtering 25 | * @property array $data The data to be displayed in the table 26 | */ 27 | class DataTableResults implements \JsonSerializable 28 | { 29 | public const DT_ROW_ID = 'DT_RowId'; 30 | public const DT_ROW_CLASS = 'DT_RowClass'; 31 | public const DT_ROW_DATA = 'DT_RowData'; 32 | public const DT_ROW_ATTR = 'DT_RowAttr'; 33 | 34 | /** 35 | * @Assert\NotNull 36 | * @Assert\GreaterThanOrEqual(value="0") 37 | */ 38 | public $recordsTotal = 0; 39 | 40 | /** 41 | * @Assert\NotNull 42 | * @Assert\GreaterThanOrEqual(value="0") 43 | */ 44 | public $recordsFiltered = 0; 45 | 46 | /** 47 | * @Assert\NotNull 48 | * @Assert\Type(type="array") 49 | */ 50 | public $data = []; 51 | 52 | /** 53 | * @Assert\NotNull 54 | * @Assert\GreaterThanOrEqual(value="0") 55 | */ 56 | private $draw = 0; 57 | 58 | /** 59 | * Convert results into array as expected by DataTables plugin. 60 | */ 61 | public function jsonSerialize(): array 62 | { 63 | return [ 64 | 'draw' => (int) $this->draw, 65 | 'recordsTotal' => (int) $this->recordsTotal, 66 | 'recordsFiltered' => (int) $this->recordsFiltered, 67 | 'data' => $this->data, 68 | ]; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /tests/ColumnTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | 18 | /** 19 | * @coversDefaultClass \DataTables\Column 20 | * 21 | * @internal 22 | */ 23 | final class ColumnTest extends TestCase 24 | { 25 | /** 26 | * @covers ::__construct 27 | */ 28 | public function testConstructor(): void 29 | { 30 | $data = bin2hex(random_bytes(10)); 31 | $name = bin2hex(random_bytes(10)); 32 | $searchable = true; 33 | $orderable = true; 34 | $value = bin2hex(random_bytes(10)); 35 | $regex = true; 36 | 37 | $object = new Column($data, $name, $searchable, $orderable, new Search($value, $regex)); 38 | 39 | self::assertSame($data, $object->data); 40 | self::assertSame($name, $object->name); 41 | self::assertSame($searchable, $object->searchable); 42 | self::assertSame($orderable, $object->orderable); 43 | self::assertSame($value, $object->search->value); 44 | self::assertSame($regex, $object->search->regex); 45 | } 46 | 47 | /** 48 | * @covers ::jsonSerialize 49 | */ 50 | public function testJsonSerializable(): void 51 | { 52 | $data = bin2hex(random_bytes(10)); 53 | $name = bin2hex(random_bytes(10)); 54 | $searchable = true; 55 | $orderable = true; 56 | $value = bin2hex(random_bytes(10)); 57 | $regex = true; 58 | 59 | $expected = json_encode([ 60 | 'data' => $data, 61 | 'name' => $name, 62 | 'searchable' => $searchable, 63 | 'orderable' => $orderable, 64 | 'search' => [ 65 | 'value' => $value, 66 | 'regex' => $regex, 67 | ], 68 | ]); 69 | 70 | $object = new Column($data, $name, $searchable, $orderable, new Search($value, $regex)); 71 | 72 | self::assertSame($expected, json_encode($object)); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/DataTableQuery.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | /** 17 | * A draw query from DataTables plugin. 18 | * 19 | * @see https://www.datatables.net/manual/server-side 20 | * 21 | * @property int $start Index of first row to return, zero-based 22 | * @property int $length Total number of rows to return (-1 to return all rows) 23 | * @property Search $search Global search value 24 | * @property Order[] $order Columns ordering (zero-based column index and direction) 25 | * @property Column[] $columns Columns information (searchable, orderable, search value, etc) 26 | * @property array $customData Custom data from DataTables 27 | */ 28 | class DataTableQuery extends ValueObject implements \JsonSerializable 29 | { 30 | protected $start; 31 | protected $length; 32 | protected $search; 33 | protected $order; 34 | protected $columns; 35 | protected $customData; 36 | 37 | /** 38 | * Initializing constructor. 39 | */ 40 | public function __construct(Parameters $params) 41 | { 42 | $this->start = (int) $params->start; 43 | $this->length = (int) $params->length; 44 | 45 | $this->search = new Search( 46 | $params->search['value'], 47 | 'true' === $params->search['regex'] 48 | ); 49 | 50 | $this->order = array_map(function (array $order): Order { 51 | return new Order( 52 | (int) $order['column'], 53 | $order['dir'] 54 | ); 55 | }, $params->order); 56 | 57 | $this->columns = array_map(function (array $column): Column { 58 | return new Column( 59 | $column['data'], 60 | $column['name'], 61 | 'true' === $column['searchable'], 62 | 'true' === $column['orderable'], 63 | new Search($column['search']['value'], 'true' === $column['search']['regex']) 64 | ); 65 | }, $params->columns); 66 | 67 | $this->customData = $params->customData; 68 | } 69 | 70 | /** 71 | * {@inheritdoc} 72 | */ 73 | public function jsonSerialize(): array 74 | { 75 | $callback = function (\JsonSerializable $item): array { 76 | return $item->jsonSerialize(); 77 | }; 78 | 79 | return [ 80 | 'start' => $this->start, 81 | 'length' => $this->length, 82 | 'search' => $this->search->jsonSerialize(), 83 | 'order' => array_map($callback, $this->order), 84 | 'columns' => array_map($callback, $this->columns), 85 | ]; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/Parameters.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Symfony\Component\Validator\Constraints as Assert; 17 | 18 | /** 19 | * Parameters received from DataTables plugin. 20 | * 21 | * @see https://www.datatables.net/manual/server-side 22 | * 23 | * @property int $draw Draw counter 24 | * @property int $start Index of first row to return, zero-based 25 | * @property int $length Total number of rows to return (-1 to return all rows) 26 | * @property array $search Global search value 27 | * @property array $order Columns ordering (zero-based column index and direction) 28 | * @property array $columns Columns information (searchable, orderable, search value, etc) 29 | * @property array $customData Custom data from DataTables 30 | */ 31 | class Parameters 32 | { 33 | /** 34 | * @Assert\NotNull 35 | * @Assert\GreaterThanOrEqual(value="0") 36 | */ 37 | public $draw = 0; 38 | 39 | /** 40 | * @Assert\NotNull 41 | * @Assert\GreaterThanOrEqual(value="0") 42 | */ 43 | public $start = 0; 44 | 45 | /** 46 | * @Assert\NotNull 47 | * @Assert\GreaterThanOrEqual(value="-1") 48 | */ 49 | public $length = -1; 50 | 51 | /** 52 | * @Assert\NotNull 53 | * @Assert\Collection( 54 | * fields={ 55 | * "value": { 56 | * @Assert\Length(max="100") 57 | * }, 58 | * "regex": { 59 | * @Assert\Choice(choices={"false", "true"}, strict=true) 60 | * } 61 | * }, 62 | * allowExtraFields=false, 63 | * allowMissingFields=false 64 | * ) 65 | */ 66 | public $search = []; 67 | 68 | /** 69 | * @Assert\NotNull 70 | * @Assert\Type(type="array") 71 | * @Assert\All({ 72 | * @Assert\Collection( 73 | * fields={ 74 | * "column": { 75 | * @Assert\GreaterThanOrEqual(value="0") 76 | * }, 77 | * "dir": { 78 | * @Assert\Choice(choices={"asc", "desc"}, strict=true) 79 | * } 80 | * }, 81 | * allowExtraFields=false, 82 | * allowMissingFields=false 83 | * ) 84 | * }) 85 | */ 86 | public $order = []; 87 | 88 | /** 89 | * @Assert\NotNull 90 | * @Assert\Type(type="array") 91 | * @Assert\All({ 92 | * @Assert\Collection( 93 | * fields={ 94 | * "data": { 95 | * }, 96 | * "name": { 97 | * @Assert\Length(max="100") 98 | * }, 99 | * "searchable": { 100 | * @Assert\Choice(choices={"false", "true"}, strict=true) 101 | * }, 102 | * "orderable": { 103 | * @Assert\Choice(choices={"false", "true"}, strict=true) 104 | * }, 105 | * "search": { 106 | * @Assert\Collection( 107 | * fields={ 108 | * "value": { 109 | * @Assert\Length(max="100") 110 | * }, 111 | * "regex": { 112 | * @Assert\Choice(choices={"false", "true"}, strict=true) 113 | * } 114 | * }, 115 | * allowExtraFields=false, 116 | * allowMissingFields=false 117 | * ) 118 | * } 119 | * }, 120 | * allowExtraFields=false, 121 | * allowMissingFields=false 122 | * ) 123 | * }) 124 | */ 125 | public $columns = []; 126 | 127 | /** 128 | * @Assert\Type(type="array") 129 | */ 130 | public $customData = []; 131 | } 132 | -------------------------------------------------------------------------------- /tests/DataTableQueryTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | use Symfony\Component\HttpFoundation\Request; 18 | 19 | /** 20 | * @coversDefaultClass \DataTables\DataTableQuery 21 | * 22 | * @internal 23 | */ 24 | final class DataTableQueryTest extends TestCase 25 | { 26 | /** @var Parameters */ 27 | protected $parameters; 28 | 29 | protected function setUp(): void 30 | { 31 | parent::setUp(); 32 | 33 | $request = new Request([ 34 | 'draw' => mt_rand(), 35 | 'start' => '20', 36 | 'length' => '10', 37 | 'search' => ['value' => 'symfony', 'regex' => 'false'], 38 | 'order' => [ 39 | ['column' => '1', 'dir' => 'desc'], 40 | ['column' => '0', 'dir' => 'asc'], 41 | ], 42 | 'columns' => [ 43 | ['data' => '0', 'name' => '#1', 'searchable' => 'true', 'orderable' => 'false', 'search' => ['value' => 'first', 'regex' => 'false']], 44 | ['data' => '1', 'name' => '#2', 'searchable' => 'false', 'orderable' => 'true', 'search' => ['value' => 'second', 'regex' => 'true']], 45 | ], 46 | ]); 47 | 48 | $this->parameters = new Parameters(); 49 | 50 | $this->parameters->draw = $request->get('draw'); 51 | $this->parameters->start = $request->get('start'); 52 | $this->parameters->length = $request->get('length'); 53 | $this->parameters->search = $request->get('search'); 54 | $this->parameters->order = $request->get('order'); 55 | $this->parameters->columns = $request->get('columns'); 56 | } 57 | 58 | /** 59 | * @covers ::__construct 60 | */ 61 | public function testSuccess(): void 62 | { 63 | $query = new DataTableQuery($this->parameters); 64 | 65 | self::assertSame(20, $query->start); 66 | self::assertSame(10, $query->length); 67 | 68 | self::assertSame('symfony', $query->search->value); 69 | self::assertFalse($query->search->regex); 70 | 71 | self::assertCount(2, $query->order); 72 | self::assertSame(1, $query->order[0]->column); 73 | self::assertSame(0, $query->order[1]->column); 74 | self::assertSame(Order::DESC, $query->order[0]->dir); 75 | self::assertSame(Order::ASC, $query->order[1]->dir); 76 | 77 | self::assertCount(2, $query->columns); 78 | self::assertSame('0', $query->columns[0]->data); 79 | self::assertSame('1', $query->columns[1]->data); 80 | self::assertSame('#1', $query->columns[0]->name); 81 | self::assertSame('#2', $query->columns[1]->name); 82 | self::assertTrue($query->columns[0]->searchable); 83 | self::assertFalse($query->columns[1]->searchable); 84 | self::assertFalse($query->columns[0]->orderable); 85 | self::assertTrue($query->columns[1]->orderable); 86 | self::assertSame('first', $query->columns[0]->search->value); 87 | self::assertSame('second', $query->columns[1]->search->value); 88 | self::assertFalse($query->columns[0]->search->regex); 89 | self::assertTrue($query->columns[1]->search->regex); 90 | } 91 | 92 | /** 93 | * @covers ::jsonSerialize 94 | */ 95 | public function testJsonSerializable(): void 96 | { 97 | $expected = json_encode([ 98 | 'start' => 20, 99 | 'length' => 10, 100 | 'search' => ['value' => 'symfony', 'regex' => false], 101 | 'order' => [ 102 | ['column' => 1, 'dir' => 'desc'], 103 | ['column' => 0, 'dir' => 'asc'], 104 | ], 105 | 'columns' => [ 106 | ['data' => '0', 'name' => '#1', 'searchable' => true, 'orderable' => false, 'search' => ['value' => 'first', 'regex' => false]], 107 | ['data' => '1', 'name' => '#2', 'searchable' => false, 'orderable' => true, 'search' => ['value' => 'second', 'regex' => true]], 108 | ], 109 | ]); 110 | 111 | $query = new DataTableQuery($this->parameters); 112 | 113 | self::assertSame($expected, json_encode($query)); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/DataTables.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use Psr\Log\LoggerInterface; 17 | use Symfony\Component\HttpFoundation\Request; 18 | use Symfony\Component\Validator\Validator\ValidatorInterface; 19 | 20 | /** 21 | * DataTables lookup service. 22 | */ 23 | class DataTables implements DataTablesInterface 24 | { 25 | protected $logger; 26 | protected $validator; 27 | 28 | /** @var DataTableHandlerInterface[] List of registered DataTable services */ 29 | protected $services = []; 30 | 31 | /** 32 | * @codeCoverageIgnore Dependency Injection constructor. 33 | */ 34 | public function __construct(LoggerInterface $logger, ValidatorInterface $validator) 35 | { 36 | $this->logger = $logger; 37 | $this->validator = $validator; 38 | } 39 | 40 | /** 41 | * Registers specified DataTable handler. 42 | * 43 | * @param DataTableHandlerInterface $service Service of the DataTable handler 44 | * @param null|string $id DataTable ID 45 | */ 46 | public function addService(DataTableHandlerInterface $service, string $id = null) 47 | { 48 | $service_id = $id ?? $service::ID; 49 | 50 | if (null !== $service_id) { 51 | $this->services[$service_id] = $service; 52 | } 53 | } 54 | 55 | /** 56 | * {@inheritdoc} 57 | */ 58 | public function handle(Request $request, string $id, array $context = []): DataTableResults 59 | { 60 | $this->logger->debug('Handle DataTable request', [$id]); 61 | 62 | // Retrieve sent parameters. 63 | $params = new Parameters(); 64 | 65 | $keyParams = [ 66 | 'draw', 67 | 'start', 68 | 'length', 69 | 'search', 70 | 'order', 71 | 'columns', 72 | ]; 73 | 74 | $params->draw = $request->get('draw'); 75 | $params->start = $request->get('start'); 76 | $params->length = $request->get('length'); 77 | $params->search = $request->get('search'); 78 | $params->order = $request->get('order') ?? []; 79 | $params->columns = $request->get('columns') ?? []; 80 | 81 | $allParams = $request->isMethod(Request::METHOD_POST) 82 | ? $request->request->all() 83 | : $request->query->all(); 84 | 85 | $params->customData = array_diff_key($allParams, array_flip($keyParams)); 86 | 87 | // Validate sent parameters. 88 | $violations = $this->validator->validate($params); 89 | 90 | if (count($violations)) { 91 | $message = $violations->get(0)->getMessage(); 92 | $this->logger->error($message, ['request']); 93 | 94 | throw new DataTableException($message); 95 | } 96 | 97 | // Check for valid handler is registered. 98 | if (!array_key_exists($id, $this->services)) { 99 | $message = 'Unknown DataTable ID.'; 100 | $this->logger->error($message, [$id]); 101 | 102 | throw new DataTableException($message); 103 | } 104 | 105 | // Convert sent parameters into data model. 106 | $query = new DataTableQuery($params); 107 | 108 | // Pass the data model to the handler. 109 | $result = null; 110 | 111 | $timer_started = microtime(true); 112 | 113 | try { 114 | $result = $this->services[$id]->handle($query, $context); 115 | } catch (\Exception $e) { 116 | $this->logger->error($e->getMessage(), [$this->services[$id]]); 117 | 118 | throw new DataTableException($e->getMessage()); 119 | } finally { 120 | $timer_stopped = microtime(true); 121 | $this->logger->debug('DataTable processing time', [$timer_stopped - $timer_started, $this->services[$id]]); 122 | } 123 | 124 | // Validate results returned from handler. 125 | $violations = $this->validator->validate($result); 126 | 127 | if (count($violations)) { 128 | $message = $violations->get(0)->getMessage(); 129 | $this->logger->error($message, ['response']); 130 | 131 | throw new DataTableException($message); 132 | } 133 | 134 | $reflection = new \ReflectionProperty(DataTableResults::class, 'draw'); 135 | $reflection->setAccessible(true); 136 | $reflection->setValue($result, $params->draw); 137 | 138 | return $result; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /tests/DataTablesTest.php: -------------------------------------------------------------------------------- 1 | . 11 | // 12 | //---------------------------------------------------------------------- 13 | 14 | namespace DataTables; 15 | 16 | use PHPUnit\Framework\TestCase; 17 | use Psr\Log\NullLogger; 18 | use Symfony\Component\DependencyInjection\ContainerBuilder; 19 | use Symfony\Component\HttpFoundation\Request; 20 | use Symfony\Component\Validator\Validation; 21 | 22 | /** 23 | * @coversDefaultClass \DataTables\DataTables 24 | * 25 | * @internal 26 | */ 27 | final class DataTablesTest extends TestCase 28 | { 29 | /** @var DataTablesInterface */ 30 | protected $datatables; 31 | 32 | protected function setUp(): void 33 | { 34 | $container = new ContainerBuilder(); 35 | $logger = new NullLogger(); 36 | 37 | $validator = Validation::createValidatorBuilder() 38 | ->addDefaultDoctrineAnnotationReader() 39 | ->enableAnnotationMapping() 40 | ->getValidator() 41 | ; 42 | 43 | $container->set('logger', $logger); 44 | $container->set('validator', $validator); 45 | 46 | self::assertFalse($container->has('datatables')); 47 | 48 | $bundle = new DataTablesBundle(); 49 | $bundle->build($container); 50 | 51 | $extension = $bundle->getContainerExtension(); 52 | $extension->load([], $container); 53 | 54 | self::assertTrue($container->has('datatables')); 55 | 56 | $this->datatables = $container->get('datatables'); 57 | 58 | $this->datatables->addService(new Handler\SuccessfulTestDataTable(), 'testSuccess'); 59 | $this->datatables->addService(new Handler\AutoloadedTestDataTable()); 60 | $this->datatables->addService(new Handler\CustomDataTestDataTable(), 'testCustomData'); 61 | $this->datatables->addService(new Handler\ExceptionTestDataTable(), 'testException'); 62 | $this->datatables->addService(new Handler\InvalidResultsTestDataTable(), 'testInvalid'); 63 | } 64 | 65 | /** 66 | * @covers ::handle 67 | */ 68 | public function testSuccess(): void 69 | { 70 | $draw = mt_rand(); 71 | 72 | $request = new Request([ 73 | 'draw' => $draw, 74 | 'start' => 0, 75 | 'length' => 10, 76 | 'search' => ['value' => null, 'regex' => 'false'], 77 | 'order' => [], 78 | 'columns' => [], 79 | ]); 80 | 81 | $expected = [ 82 | 'draw' => $draw, 83 | 'recordsTotal' => 100, 84 | 'recordsFiltered' => 20, 85 | 'data' => [], 86 | ]; 87 | 88 | $results = $this->datatables->handle($request, 'testSuccess', ['test' => 20]); 89 | 90 | self::assertSame(json_encode($expected), json_encode($results)); 91 | } 92 | 93 | /** 94 | * @covers ::handle 95 | */ 96 | public function testDefaults(): void 97 | { 98 | $draw = mt_rand(); 99 | 100 | $request = new Request([ 101 | 'draw' => $draw, 102 | 'start' => 0, 103 | 'length' => 10, 104 | 'search' => ['value' => null, 'regex' => 'false'], 105 | 'order' => null, 106 | 'columns' => null, 107 | ]); 108 | 109 | $expected = [ 110 | 'draw' => $draw, 111 | 'recordsTotal' => 100, 112 | 'recordsFiltered' => 10, 113 | 'data' => [], 114 | ]; 115 | 116 | $results = $this->datatables->handle($request, 'testSuccess'); 117 | 118 | self::assertSame(json_encode($expected), json_encode($results)); 119 | } 120 | 121 | /** 122 | * @covers ::handle 123 | */ 124 | public function testAutoloaded(): void 125 | { 126 | $draw = mt_rand(); 127 | 128 | $request = new Request([ 129 | 'draw' => $draw, 130 | 'start' => 0, 131 | 'length' => 10, 132 | 'search' => ['value' => null, 'regex' => 'false'], 133 | 'order' => [], 134 | 'columns' => [], 135 | ]); 136 | 137 | $expected = [ 138 | 'draw' => $draw, 139 | 'recordsTotal' => 200, 140 | 'recordsFiltered' => 20, 141 | 'data' => [], 142 | ]; 143 | 144 | $results = $this->datatables->handle($request, 'testAuto'); 145 | 146 | self::assertSame(json_encode($expected), json_encode($results)); 147 | } 148 | 149 | /** 150 | * @covers ::handle 151 | */ 152 | public function testCustomData(): void 153 | { 154 | $draw = mt_rand(); 155 | 156 | $request = new Request([ 157 | 'draw' => $draw, 158 | 'firstName' => 'Anna', 159 | 'lastName' => 'Rodygina', 160 | 'start' => 0, 161 | 'length' => 10, 162 | 'search' => ['value' => null, 'regex' => 'false'], 163 | 'order' => [], 164 | 'columns' => [], 165 | ]); 166 | 167 | $expected = [ 168 | 'draw' => $draw, 169 | 'recordsTotal' => 100, 170 | 'recordsFiltered' => 10, 171 | 'data' => [ 172 | 'firstName' => 'Anna', 173 | 'lastName' => 'Rodygina', 174 | ], 175 | ]; 176 | 177 | $results = $this->datatables->handle($request, 'testCustomData'); 178 | 179 | self::assertSame(json_encode($expected), json_encode($results)); 180 | } 181 | 182 | /** 183 | * @covers ::handle 184 | */ 185 | public function testPost(): void 186 | { 187 | $draw = mt_rand(); 188 | 189 | $request = new Request([], [ 190 | 'draw' => $draw, 191 | 'firstName' => 'Anna', 192 | 'lastName' => 'Rodygina', 193 | 'start' => 0, 194 | 'length' => 10, 195 | 'search' => ['value' => null, 'regex' => 'false'], 196 | 'order' => [], 197 | 'columns' => [], 198 | ]); 199 | 200 | $request->setMethod(Request::METHOD_POST); 201 | 202 | $expected = [ 203 | 'draw' => $draw, 204 | 'recordsTotal' => 100, 205 | 'recordsFiltered' => 10, 206 | 'data' => [ 207 | 'firstName' => 'Anna', 208 | 'lastName' => 'Rodygina', 209 | ], 210 | ]; 211 | 212 | $results = $this->datatables->handle($request, 'testCustomData'); 213 | 214 | self::assertSame(json_encode($expected), json_encode($results)); 215 | } 216 | 217 | /** 218 | * @covers ::handle 219 | */ 220 | public function testException(): void 221 | { 222 | $this->expectException(DataTableException::class); 223 | $this->expectExceptionMessage('Something gone wrong.'); 224 | 225 | $request = new Request([ 226 | 'draw' => mt_rand(), 227 | 'start' => 0, 228 | 'length' => 10, 229 | 'search' => ['value' => null, 'regex' => 'false'], 230 | 'order' => [], 231 | 'columns' => [], 232 | ]); 233 | 234 | $this->datatables->handle($request, 'testException'); 235 | } 236 | 237 | /** 238 | * @covers ::handle 239 | */ 240 | public function testBadQuery(): void 241 | { 242 | $this->expectException(DataTableException::class); 243 | $this->expectExceptionMessage('This value should not be null.'); 244 | 245 | $request = new Request([ 246 | 'start' => 0, 247 | 'length' => 10, 248 | 'search' => ['value' => null, 'regex' => 'false'], 249 | 'order' => [], 250 | 'columns' => [], 251 | ]); 252 | 253 | $this->datatables->handle($request, 'testSuccess'); 254 | } 255 | 256 | /** 257 | * @covers ::handle 258 | */ 259 | public function testUnknownService(): void 260 | { 261 | $this->expectException(DataTableException::class); 262 | $this->expectExceptionMessage('Unknown DataTable ID.'); 263 | 264 | $request = new Request([ 265 | 'draw' => mt_rand(), 266 | 'start' => 0, 267 | 'length' => 10, 268 | 'search' => ['value' => null, 'regex' => 'false'], 269 | 'order' => [], 270 | 'columns' => [], 271 | ]); 272 | 273 | $this->datatables->handle($request, 'testUnknown'); 274 | } 275 | 276 | /** 277 | * @covers ::handle 278 | */ 279 | public function testInvalidResults(): void 280 | { 281 | $this->expectException(DataTableException::class); 282 | $this->expectExceptionMessage('This value should not be null.'); 283 | 284 | $request = new Request([ 285 | 'draw' => mt_rand(), 286 | 'start' => 0, 287 | 'length' => 10, 288 | 'search' => ['value' => null, 'regex' => 'false'], 289 | 'order' => [], 290 | 'columns' => [], 291 | ]); 292 | 293 | $this->datatables->handle($request, 'testInvalid'); 294 | } 295 | } 296 | --------------------------------------------------------------------------------