Skip to content
Merged

Wip #132

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 56 additions & 31 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
@@ -1,46 +1,71 @@
name: PHPunit
name: PHPUnit

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
workflow_dispatch:

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: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-

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

# Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit"
# Docs: https://getcomposer.org/doc/articles/scripts.md

# - name: Run test suite
# run: composer run-script test
- name: PHPUnit (graychen)
# You may pin to the exact commit or the version.
# uses: Graychen/phpunit-action@026f8104f1a6b5bc646df2d495bc8b34080c3e03
uses: Graychen/phpunit-action@v1.0.0
with:
# Configuration file location
config: phpunit.xml
# Шаг 1: Клонирование репозитория
- name: Checkout code
uses: actions/checkout@v3

# Шаг 2: Настройка PHP и расширений
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: xdebug

# Шаг 3: Валидация composer.json и composer.lock
- name: Validate composer.json and composer.lock
run: composer validate --strict

# Шаг 4: Кэширование зависимостей Composer
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v3
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-

# Шаг 5: Установка зависимостей
- name: Install dependencies
run: composer install --prefer-dist --no-progress

# Шаг 6: Загрузка PHPUnit PHAR
- name: Download PHPUnit PHAR
run: |
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
mv phpunit.phar /usr/local/bin/phpunit

# Шаг 7: Проверка версии PHPUnit
- name: Check PHPUnit version
run: phpunit --version

# Шаг 8: Запуск тестов с генерацией отчета о покрытии
- name: Run PHPUnit tests with coverage
run: |
mkdir -p build/logs
phpunit --configuration phpunit.xml --coverage-clover build/logs/clover.xml --debug
env:
XDEBUG_MODE: coverage

# Шаг 9: Отправка данных о покрытии в Coveralls
- name: Send coverage to Coveralls
uses: coverallsapp/github-action@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: build/logs/clover.xml
213 changes: 58 additions & 155 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,66 @@
[![PHPunit](https://github.com/Jagepard/Rudra-Router/actions/workflows/php.yml/badge.svg)](https://github.com/Jagepard/Rudra-Router/actions/workflows/php.yml)
[![Code Climate](https://codeclimate.com/github/Jagepard/Rudra-Router/badges/gpa.svg)](https://codeclimate.com/github/Jagepard/Rudra-Router)
[![Maintainability](https://qlty.sh/badges/d9252114-5cc4-405e-bbf7-6419ec50266f/maintainability.svg)](https://qlty.sh/gh/Jagepard/projects/Rudra-Router)
[![CodeFactor](https://www.codefactor.io/repository/github/jagepard/rudra-router/badge)](https://www.codefactor.io/repository/github/jagepard/rudra-router)
[![Coverage Status](https://coveralls.io/repos/github/Jagepard/Rudra-Router/badge.svg?branch=master)](https://coveralls.io/github/Jagepard/Rudra-Router?branch=master)
-----

# Rudra-Router

#### Устанавливаем маршрут callback/:name для http метода GET
_выполняет лямбда-функцию_
#### Basic installation / Базовая установка
```php
use Rudra\Router\Router;
use Rudra\Container\Rudra;

$router = new Router(Rudra::run());
```
#### Installation for facade use / Установка для использования фасада
```php
use Rudra\Container\Facades\Rudra;
use Rudra\Router\RouterFacade as Router;
use Rudra\Container\Interfaces\RudraInterface;

Rudra::binding()->set([RudraInterface::class => Rudra::run()]);
```

#### Setting the route / Устанавливаем маршрут callback/:name
```php
$router->get('callback/:name', function ($name) {
echo "Hello $name!";
});
```
_Для вызова через Фасад Rudra-Container_
_with Regex_
```php
use Rudra\Router\RouterFacade as Router;

Router::get('callback/:name', function ($name) {
$router->get('callback/:[\d]{1,3}', function ($name) {
echo "Hello $name!";
});
```
_вызывает MainController::read_
_To call through the Facade / Для вызова через Фасад_
```php
$router->get('read/:id', [MainController::class, 'read']);
Router::get('callback/:name', function ($name) {
echo "Hello $name!";
});
```
_вызывает MainController::read при помощи добавления аннотаций к MainController_
_with Regex_
```php
/**
* @Routing(url = ''read/:id')
*/
public function read($id)
Router::get('callback/:[\d]{1,3}', function ($name) {
echo "Hello $name!";
});
```
_вызывает MainController::read_ и добавляет middleware с ключами before или after соответственно_
_call / вызывает MainController::read_
```php
$router->get('read/page', [MainController::class, 'read'], ['before' => [Middleware::class]);
$router->get('read/:id', [MainController::class, 'read']);
```
_в аннотациях_
_To call through the Facade / Для вызова через Фасад_
```php
/**
* @Routing(url = 'read/page')
* @Middleware(name = 'App\Middleware\Middleware')
*/
public function read()
Router::get('read/:id', [MainController::class, 'read']);
```
_Для сбора аннотаций необходимо передать массив классов в которых есть аннотации в annotationCollector_
_call MainController::read with middleware_
```php
$router->annotationCollector([
\App\Controllers\MainController::class,
\App\Controllers\SecondController::class,
]);
$router->get('read/page', [MainController::class, 'read'], ['before' => [Middleware::class]);
```
_To call through the Facade / Для вызова через Фасад_
```php
Router::annotationCollector([
\App\Controllers\MainController::class,
\App\Controllers\SecondController::class,
]);
Router::get('read/page', [MainController::class, 'read'], ['before' => [Middleware::class]);
```
_С параметрами для middleware_
```php
Expand All @@ -63,163 +69,60 @@ $router->get('', [MainController::class, 'read'], [
'after' => [FirstMidddleware::class, [SecondMidddleware::class, ['int' => 456, new \stdClass]]]
]);
```
_в аннотациях_
```php
/**
* @Routing(url = '')
* @Middleware(name = 'App\Middleware\FirstMidddleware')
* @Middleware(name = 'App\Middleware\SecondMidddleware', params = {int : '456'})
* @AfterMiddleware(name = 'App\Middleware\FirstMidddleware')
* @AfterMiddleware(name = 'App\Middleware\SecondMidddleware', params = {int : '456'})
*/
public function read()
```
_При передаче параметров в middleware необходимо добавлять параметр "array $params"_
```php
public function __invoke(array $params, array $middlewares)
```
_Если параметры не передаются, то:_
```php
public function __invoke(array $middlewares)
```
_Следующие вызовы без параметров равны_
```php
'before' => [FirstMidddleware::class, SecondMidddleware::class]],
'before' => [[FirstMidddleware::class], [SecondMidddleware::class]]
```
#### Устанавливаем маршрут create/:id для http метода POST
_вызывает MainController::create_
_call / вызывает MainController::create_
```php
$router->post('create/:id', [MainController::class, 'create']);
```
_в аннотациях_
```php
/**
* @Routing(url = 'create/:id', method = 'POST')
*/
public function create($id)
```
#### Устанавливаем маршрут update/:id для http метода PUT
_вызывает MainController::update_
_call / вызывает MainController::update_
```php
$router->put('update/:id', [MainController::class, 'update']);
```
_в аннотациях_
```php
/**
* @Routing(url = 'update/:id', method = 'PUT')
*/
public function update($id)
```
#### Устанавливаем маршрут update/:id для http метода PATCH
_вызывает MainController::update_
_call / вызывает MainController::update_
```php
$router->patch('update/:id', [MainController::class, 'update']);
```
_в аннотациях_
```php
/**
* @Routing(url = 'update/:id', method = 'PATCH')
*/
public function update($id)
```
#### Устанавливаем маршрут delete/:id для http метода DELETE
_вызывает MainController::delete_
_call / вызывает MainController::delete_
```php
$router->delete('delete/:id', [MainController::class, 'delete']);
```
_в аннотациях_
```php
/**
* @Routing(url = 'delete/:id', method = 'DELETE')
*/
public function delete($id)
```
#### Устанавливаем маршрут any/:id для http методов GET|POST|PUT|PATCH|DELETE
_вызывает MainController::any_
_call / вызывает MainController::any 'GET|POST|PUT|PATCH|DELETE'_
```php
$router->any('any/:id', [MainController::class, 'any']);
```
_в аннотациях_
```php
/**
* @Routing(url = 'any/:id', method = 'GET|POST|PUT|PATCH|DELETE')
*/
public function any($id)
```
#### Устанавливаем ресурс для маршрута api/:id, методы GET|POST|PUT|DELETE
_вызывает MainController::read для GET_
_call / вызывает MainController::read для GET_

_вызывает MainController::create для POST_
_call / вызывает MainController::create для POST_

_вызывает MainController::update для PUT_
_call / вызывает MainController::update для PUT_

_вызывает MainController::delete для DELETE_
_call / вызывает MainController::delete для DELETE_
```php
$router->resource('api/:id', MainController::class);
```
Изменить методы контроллера по умолчанию можно передав массив с вашими именами
Изменить методы контроллера по умолчанию можно передав массив с вашими именами\
You can change the default controller methods by passing an array with your names
```php
$router->resource('api/:id', MainController::class, ['actionIndex', 'actionAdd', 'actionUpdate', 'actionDrop']);
```
##### Вариант объявления маршрута методом set
#### Устанавливаем маршрут /test/:id для http методов DELETE|PUT
_выполняет лямбда-функцию_
```php
$router->set(['/test/page', 'POST|PUT', function () {
echo 'Hello world!';
}
]);
```
_вызывает MainController::actionIndex_
#### A variant of declaring a route using the set method / Вариант объявления маршрута методом set
_call / вызывает MainController::actionIndex_
```php
$router->set(['/test/:id', 'DELETE|PUT', [MainController::class, 'actionIndex'], [
'before' => [First::class, Second::class],
'after' => [[First::class], [Second::class]]
]]);
```
_Пример Middleware_
_Exemple / Пример Middleware_
```php
<?php

namespace App\Middleware;

use Rudra\Router\Router;
use Rudra\Router\MiddlewareInterface;

class FirstMiddleware extends Router implements MiddlewareInterface
{
public function __invoke(array $middlewares)
{
$this->next($middlewares);
}

public function next(array $middlewares): void
{
$this->handleMiddleware($middlewares);
}
}
```
_Пример Middleware с параметрами с использованием Фасада_
```php
<?php

namespace App\Middleware;

use Rudra\Router\MiddlewareInterface;
use Rudra\Router\RouterFacade as Router;

class SecondMiddleware implements MiddlewareInterface
/**
* Handles requests as a middleware using __invoke().
*/
class SomeMiddleware
{
public function __invoke(array $middlewares, array $params)
{
var_dump($params);
$this->next($middlewares);
}

public function next(array $middlewares): void
public function __invoke($params, $next)
{
Router::handleMiddleware($middlewares);
// Logic here
$next();
}
}
```
Loading
Loading