diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bc885d1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2016 Artem Beliankin + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..aec22f0 --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +# Telegram Bot Pagination + +- [Installation](#installation) + - [Composer](#composer) + - [Configuration](#configuration) + - [Service Provider](#service-provider) +- [Usage](#usage) + - [Test Data](#test-data) + - [How To Use](#how-to-use) + - [Result](#result) +- [License](#license) + +## Installation + +### Composer +```bash +composer require "lartie/telegram-bot-pagination:^1.0.0" +``` + +### Service Provider + +You must install this service provider. +```php +// config/app.php +'providers' => [ + ... + LArtie\TelegramBotPagination\TelegramBotPaginationServiceProvider::class, + ... +]; +``` + +## Usage + +### Test Data +```php +$items = range(1, 100); +$command = 'testCommand'; // optional. Default: pagination +$selectedPage = 10; // optional. Default: 1 +``` + +### How To Use +```php + +$cqPagination = new CallbackQueryPagination($items, $command); +$cqPagination->setMaxButtons(6); +$cqPagination->setWrapSelectedButton('< #VALUE# >'); + +$pagination = $cqPagination->pagination($selectedPage); //$cqPagination->setSelectedPage($selectedPage); + +``` + +### Result +```php +if (!empty($paginate['keyboard'])) { + $paginate['keyboard'][0]['callback_data']; // testCommand?currentPage10=&nextPage=1 + $paginate['keyboard'][1]['callback_data']; // testCommand?currentPage10=&nextPage=9 + ... + + $response = [ + 'reply_markup' => json_encode([ + 'inline_keyboard' => [ + $paginate['keyboard'], + ], + ]), + ]; +} +``` + +## Code Quality + +Run the PHPUnit tests with PHPUnit. + + phpunit tests/ + + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..dba6a13 --- /dev/null +++ b/composer.json @@ -0,0 +1,36 @@ +{ + "name": "lartie/telegram-bot-pagination", + "description": "Telegram Bot Pagination ", + "keywords": ["laravel", "telegram api", "telegram", "pagination", "telegram-callback", "telegram bot"], + "type": "library", + "homepage": "https://github.com/lartie/telegram-bot-pagination", + "license": "MIT", + "authors": [ + { + "name": "Artie", + "email": "log.wil.log@gmail.com", + "homepage": "https://github.com/lartie" + } + ], + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8 || ^5.0", + "phpspec/prophecy": "^1.5" + }, + "autoload": { + "psr-4": { + "LArtie\\TelegramBotPagination\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "LArtie\\TelegramBotPagination\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "phpunit" + } +} + diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..412c8d3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,25 @@ + + + + + ./tests + + + + + ./src + + + \ No newline at end of file diff --git a/src/Contract/CallbackQueryPaginationContract.php b/src/Contract/CallbackQueryPaginationContract.php new file mode 100644 index 0000000..dbb1bba --- /dev/null +++ b/src/Contract/CallbackQueryPaginationContract.php @@ -0,0 +1,54 @@ +#VALUE#<, <#VALUE#>, |#VALUE#| etc... + * + * @param string $wrapSelectedButton + * @return CallbackQueryPagination + */ + public function setWrapSelectedButton(string $wrapSelectedButton = '« #VALUE# »') : CallbackQueryPagination; + + /** + * @param string $command + * @return CallbackQueryPagination + */ + public function setCommand(string $command = 'pagination'): CallbackQueryPagination; + + /** + * @param int $selectedPage + * @return CallbackQueryPagination + */ + public function setSelectedPage(int $selectedPage): CallbackQueryPagination; + + /** + * CallbackQueryPaginationContract constructor. + * + * @param array $items + * @param string $command + * @param int $selectedPage + * @param int $limit + */ + public function __construct(array $items, string $command, int $selectedPage, int $limit); + + /** + * @param int $selectedPage + * @return array + */ + public function paginate(int $selectedPage = null) : array; +} \ No newline at end of file diff --git a/src/Core/CallbackQueryPagination.php b/src/Core/CallbackQueryPagination.php new file mode 100644 index 0000000..0da0651 --- /dev/null +++ b/src/Core/CallbackQueryPagination.php @@ -0,0 +1,263 @@ + 'integer|between:5,8', + ]); + + if ($validator->fails()) { + throw new CallbackQueryPaginationException($validator->errors()->first()); + } + $this->maxButtons = $maxButtons; + return $this; + } + + /** + * @inheritdoc + * @throws CallbackQueryPaginationException + */ + public function setWrapSelectedButton(string $wrapSelectedButton = '« #VALUE# »') : CallbackQueryPagination + { + /** @var \Illuminate\Validation\Validator $validator */ + $validator = Validator::make(compact('wrapSelectedButton'), [ + 'wrapSelectedButton' => 'regex:/#VALUE#/', + ]); + + if ($validator->fails()) { + throw new CallbackQueryPaginationException($validator->errors()->first()); + } + $this->wrapSelectedButton = $wrapSelectedButton; + return $this; + } + + /** + * @inheritdoc + */ + public function setCommand(string $command = 'pagination'): CallbackQueryPagination + { + $this->command = $command; + return $this; + } + + /** + * @inheritdoc + * @throws CallbackQueryPaginationException + */ + public function setSelectedPage(int $selectedPage): CallbackQueryPagination + { + /** @var \Illuminate\Validation\Validator $validator */ + $validator = Validator::make( + compact('selectedPage'), + ['selectedPage' => 'integer|between:1,' . $this->numberOfPages], + ['between' => 'The $selectedPage must be between 1 - $numberOfPages'] + ); + + if ($validator->fails()) { + throw new CallbackQueryPaginationException($validator->errors()->first()); + } + $this->selectedPage = $selectedPage; + return $this; + } + + /** + * TelegramBotPagination constructor. + * + * @inheritdoc + * @throws CallbackQueryPaginationException + */ + public function __construct(array $items, string $command = 'pagination', int $selectedPage = 1, int $limit = 3) + { + $this->numberOfPages = $this->countTheNumberOfPage(count($items), $limit); + + $this->setSelectedPage($selectedPage); + + $this->items = $items; + $this->limit = $limit; + $this->command = $command; + } + + /** + * @inheritdoc + * @throws CallbackQueryPaginationException + */ + public function paginate(int $selectedPage = null) : array + { + if ($selectedPage !== null) { + $this->setSelectedPage($selectedPage); + } + return [ + 'items' => $this->getPreparedItems(), + 'keyboard' => $this->generateKeyboard(), + ]; + } + + /** + * @return array + */ + protected function generateKeyboard() : array + { + $buttons = []; + + if ($this->numberOfPages > $this->maxButtons) { + + $buttons[] = $this->generateButton($this->firstPage); + + $range = $this->generateRange(); + + for ($i = $range['from']; $i < $range['to']; $i++) { + $buttons[] = $this->generateButton($i); + } + + $buttons[] = $this->generateButton($this->numberOfPages); + + } else { + for ($i = 1; $i <= $this->numberOfPages; $i++) { + $buttons[] = $this->generateButton($i); + } + } + return $buttons; + } + + /** + * @return array + */ + protected function generateRange() : array + { + $numberOfIntermediateButtons = $this->maxButtons - 2; + + if ($this->selectedPage == $this->firstPage) { + $from = 2; + $to = $from + $numberOfIntermediateButtons; + } else if ($this->selectedPage == $this->numberOfPages) { + $from = $this->numberOfPages - $numberOfIntermediateButtons; + $to = $this->numberOfPages; + } else { + if (($this->selectedPage + $numberOfIntermediateButtons) > $this->numberOfPages) { + $from = $this->numberOfPages - $numberOfIntermediateButtons; + $to = $this->numberOfPages; + } else if (($this->selectedPage - 2) < $this->firstPage) { + $from = $this->selectedPage; + $to = $this->selectedPage + $numberOfIntermediateButtons; + } else { + $from = $this->selectedPage - 1; + $to = $this->selectedPage + 2; + } + } + return compact('from', 'to'); + } + + /** + * @param int $nextPage + * @return array + */ + protected function generateButton(int $nextPage) : array + { + $label = "$nextPage"; + $callbackData = $this->generateCallbackData($nextPage); + + if ($nextPage === $this->selectedPage) { + $label = str_replace('#VALUE#', $label, $this->wrapSelectedButton); + } + return [ + 'text' => $label, + 'callback_data' => $callbackData, + ]; + } + + /** + * @param int $nextPage + * @return string + */ + protected function generateCallbackData(int $nextPage) : string + { + return "$this->command?currentPage=$this->selectedPage&nextPage=$nextPage"; + } + + /** + * @return array + */ + protected function getPreparedItems() : array + { + $offset = $this->getOffset(); + + return array_slice($this->items, $offset, $this->limit); + } + + /** + * @return int + */ + protected function getOffset() : int + { + return ($this->limit * $this->selectedPage) - $this->limit; + } + + /** + * @param $itemsLength + * @param $limit + * @return int + */ + protected function countTheNumberOfPage($itemsLength, $limit) : int + { + $numberOfPages = ceil($itemsLength/$limit); + + return (int)$numberOfPages; + } +} \ No newline at end of file diff --git a/src/Exceptions/CallbackQueryPaginationException.php b/src/Exceptions/CallbackQueryPaginationException.php new file mode 100644 index 0000000..e0decac --- /dev/null +++ b/src/Exceptions/CallbackQueryPaginationException.php @@ -0,0 +1,13 @@ +items = range(1, 100); + $this->command = 'testCommand'; + $this->selectedPage = random_int(1, 15); + } + + public function test_valid_constructor() + { + $cbq = new CallbackQueryPagination($this->items, $this->command, $this->selectedPage, $this->limit); + + $data = $cbq->paginate(); + + $this->assertCount($this->limit, $data['items']); + $this->assertArrayHasKey('keyboard', $data); + $this->assertArrayHasKey(0, $data['keyboard']); + $this->assertArrayHasKey('text', $data['keyboard'][0]); + $this->assertStringStartsWith($this->command, $data['keyboard'][0]['callback_data']); + } + + /** + * @expectedException \LArtie\TelegramBotPagination\Exceptions\CallbackQueryPaginationException + */ + public function test_invalid_constructor() + { + $cbq = new CallbackQueryPagination($this->items, $this->command, 10000, $this->limit); + $cbq->paginate(); + } + + public function test_valid_paginate() + { + $cbq = new CallbackQueryPagination($this->items, $this->command, $this->selectedPage, $this->limit); + + $length = (int)ceil(count($this->items)/$this->limit); + + for ($i = 1; $i < $length; $i++) { + $cbq->paginate($i); + } + } + + /** + * @expectedException \LArtie\TelegramBotPagination\Exceptions\CallbackQueryPaginationException + */ + public function test_invalid_paginate() + { + $cbq = new CallbackQueryPagination($this->items, $this->command, $this->selectedPage, $this->limit); + + $length = (int)ceil(count($this->items)/$this->limit) + 1; + + for ($i = $length; $i < $length * 2; $i++) { + $cbq->paginate($i); + } + } + + /** + * @expectedException \LArtie\TelegramBotPagination\Exceptions\CallbackQueryPaginationException + */ + public function test_invalid_max_buttons() + { + $cbq = new CallbackQueryPagination(range(1, 240)); + $cbq->setMaxButtons(2); + $cbq->paginate(); + } + + /** + * @expectedException \LArtie\TelegramBotPagination\Exceptions\CallbackQueryPaginationException + */ + public function test_invalid_selected_page() + { + $cbq = new CallbackQueryPagination(range(1, 240)); + $cbq->setSelectedPage(-5); + $cbq->paginate(); + } + + /** + * @expectedException \LArtie\TelegramBotPagination\Exceptions\CallbackQueryPaginationException + */ + public function test_invalid_wrap_selected_button() + { + $cbq = new CallbackQueryPagination(range(1, 240)); + $cbq->setWrapSelectedButton('$sdlfk$'); + $cbq->paginate(); + } +}