Skip to content

Commit

Permalink
init 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
soulaimaneyahya committed Nov 9, 2023
0 parents commit 23634d6
Show file tree
Hide file tree
Showing 12 changed files with 351 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Tests

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

permissions:
contents: read

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Validate composer.json and composer.lock
run: composer validate --strict

- name: Install dependencies
run: composer install --prefer-dist --no-interaction --no-progress

- name: Validate PHP PSR
run: composer run-script php-psr

- name: Run test suite
run: composer run-script test
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/vendor/
/.phpunit.result.cache
/phpunit.xml
/composer.lock
.idea/
.TODO
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Multividas Inc

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.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<div align="center">

<img width="150" height="150" src="./assets/query-filters.svg" alt="Query Option package logo"/>

# Query Filters

[![Tests](https://github.com/multividas/query-filters/actions/workflows/tests.yml/badge.svg)](https://github.com/multividas/query-filters/actions/workflows/tests.yml)
[![Total Downloads](https://img.shields.io/packagist/dt/multividas/query-filters.svg?style=flat-square)](https://packagist.org/packages/multividas/query-filters)
[![License](https://img.shields.io/github/license/multividas/query-filters?style=flat-square)](https://github.com/multividas/query-filters/blob/master/LICENSE.md)

</div>

Composer package to simplify the process of filtering and sorting queries.

---

### Run PHPUnit tests

```sh
composer test
```

---

Need helps? Reach us

> Multividas.com Ⓜ️
> Email: contact@multividas.com
🌌 🚀
1 change: 1 addition & 0 deletions assets/query-filters.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
53 changes: 53 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "multividas/query-filters",
"description": "composer package to simplify the process of filtering and sorting queries.",
"keywords": [
"query-filters"
],
"type": "package",
"license": "MIT",
"authors": [
{
"name": "multividas inc",
"email": "contact@multividas.com"
}
],
"autoload": {
"psr-4": {
"Multividas\\QueryFilters\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Multividas\\QueryFilters\\Tests\\": "tests/"
}
},
"scripts": {
"test": "vendor/bin/phpunit tests/Feature",
"php-psr": [
"./vendor/bin/phpcs --standard=PSR2 --encoding=utf-8 --extensions=php src/* tests/*"
]
},
"minimum-stability": "dev",
"require": {
"php": "^7.4 || ^8.0"
},
"require-dev": {
"orchestra/testbench": "dev-develop",
"squizlabs/php_codesniffer": "4.0.x-dev",
"phpunit/phpunit": "9.6.x-dev"
},
"config": {
"optimize-autoloader": true
},
"extra": {
"laravel": {
"providers": [
"Multividas\\QueryFilters\\Providers\\QueryFiltersServiceProvider"
],
"aliases": {
"QueryFilters": "Multividas\\QueryFilters\\Facades\\QueryFilters"
}
}
}
}
20 changes: 20 additions & 0 deletions src/Facades/QueryFilters.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

/**
* (c) 2023 Multividas inc. All rights reserved.
* Unauthorized use prohibited.
* Website: https://www.multividas.com
*/

namespace Multividas\QueryFilters\Facades;

use Illuminate\Support\Facades\Facade;
use Multividas\QueryFilters\Interfaces\QueryFiltersRepositoryInterface;

class QueryFilters extends Facade
{
protected static function getFacadeAccessor(): string
{
return QueryFiltersRepositoryInterface::class;
}
}
19 changes: 19 additions & 0 deletions src/Interfaces/QueryFiltersRepositoryInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/**
* (c) 2023 Multividas inc. All rights reserved.
* Unauthorized use prohibited.
* Website: https://www.multividas.com
*/

namespace Multividas\QueryFilters\Interfaces;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;

interface QueryFiltersRepositoryInterface
{
public function applyFilters(Collection|EloquentCollection|JsonResource $collection): array|JsonResponse;
}
28 changes: 28 additions & 0 deletions src/Providers/QueryFiltersServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/**
* (c) 2023 Multividas inc. All rights reserved.
* Unauthorized use prohibited.
* Website: https://www.multividas.com
*/

namespace Multividas\QueryFilters\Providers;

use Illuminate\Support\ServiceProvider;
use Multividas\QueryFilters\Repositories\QueryFiltersRepository;
use Multividas\QueryFilters\Interfaces\QueryFiltersRepositoryInterface;

class QueryFiltersServiceProvider extends ServiceProvider
{
public function boot(): void
{
//
}

public function register(): void
{
$this->app->bind(QueryFiltersRepositoryInterface::class, function () {
return new QueryFiltersRepository();
});
}
}
142 changes: 142 additions & 0 deletions src/Repositories/QueryFiltersRepository.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

/**
* (c) 2023 Multividas inc. All rights reserved.
* Unauthorized use prohibited.
* Website: https://www.multividas.com
*/

namespace Multividas\QueryFilters\Repositories;

use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

use Illuminate\Http\Resources\Json\JsonResource;
use Multividas\ApiResponser\Traits\ApiResponser;

use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Multividas\QueryFilters\Interfaces\QueryFiltersRepositoryInterface;

class QueryFiltersRepository implements QueryFiltersRepositoryInterface
{
use ApiResponser;

public function applyFilters(Collection|EloquentCollection|JsonResource $collection): array
{
if ($collection instanceof Collection || $collection instanceof EloquentCollection) {
$transformer = $collection->first()?->transformer ?? null;
} elseif ($collection instanceof JsonResource) {
$transformer = $collection->collects ?? null;
}

$collection = $this->filterData($collection, $transformer);
$collection = $this->sortData($collection, $transformer);

$paginatedResult = $this->paginateData($collection);

return [
'data' => $paginatedResult['data'],
'meta' => $paginatedResult['meta'],
];
}

protected function filterData(
Collection|EloquentCollection|JsonResource $collection,
?string $transformer
): Collection|EloquentCollection|JsonResource {
if (isset(request()->query()['filters'])) {
foreach (request()->query()['filters'] as $query) {
if (!is_null($transformer) && is_callable([$transformer, 'originalAttribute'])) {
$queryField = $transformer::originalAttribute($query['field']);
} else {
$queryField = $query['field'];
}

$collection = $collection->where($queryField, $query['value']);
}
}

return $collection;
}

protected function sortData(
Collection|EloquentCollection|JsonResource $collection,
?string $transformer
): Collection|EloquentCollection|JsonResource {
if (request()->has('_sort')) {
if (!is_null($transformer) && is_callable([$transformer, 'originalAttribute'])) {
$sortField = $transformer::originalAttribute(request()->_sort);
} else {
$sortField = request()->_sort;
}

$sortOrder = request()->has('_order') && request()->_order == 'desc' ? true : false;

$collection = $collection->sortBy($sortField, SORT_REGULAR, $sortOrder);
}

return $collection;
}

protected function paginateData(Collection|EloquentCollection|JsonResource $collection): array
{
$rules = [
'per_page' => ['integer', 'min:2', 'max:50'],
];

$validator = \Illuminate\Support\Facades\Validator::make(request()->all(), $rules);

if ($validator->fails()) {
throw new \Illuminate\Validation\ValidationException($validator);
}

$perPage = (int) request()->input('per_page', 10);

$page = LengthAwarePaginator::resolveCurrentPage();
$paginatedCollection = $collection->slice(($page - 1) * $perPage, $perPage)->values();

$paginated = new LengthAwarePaginator(
$paginatedCollection,
$collection->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'query' => request()->query()
]
);

$paginated->appends(request()->all());

$paginationData = [
'total' => $paginated->total(),
'count' => $paginated->count(),
'per_page' => $paginated->perPage(),
'current_page' => $paginated->currentPage(),
'total_pages' => $paginated->lastPage(),
];

$links = [];

if ($paginated->previousPageUrl() !== null) {
$links['prev'] = $paginated->previousPageUrl();
}

if ($paginated->nextPageUrl() !== null) {
$links['next'] = $paginated->nextPageUrl();
}

$links = array_filter($links, fn ($url) => $url !== null);

if (!empty($links)) {
$paginationData['links'] = $links;
}

$meta = $paginated->total() > $perPage ? ['pagination' => $paginationData] : [];

return [
'data' => $paginatedCollection,
'meta' => $meta,
];
}
}
Empty file added tests/Feature/.gitkeep
Empty file.
Empty file added tests/Unit/.gitkeep
Empty file.

0 comments on commit 23634d6

Please sign in to comment.