Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improves lib's separation of responsibilities and using. #33

Merged
merged 1 commit into from
Dec 19, 2024
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/auto-assign.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
pull-requests: write
steps:
- name: Assign issues
uses: gustavofreze/auto-assign@1.0.0
uses: gustavofreze/auto-assign@1.1.4
with:
assignees: '${{ secrets.ASSIGNEES }}'
github_token: '${{ secrets.GITHUB_TOKEN }}'
Expand Down
32 changes: 13 additions & 19 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,55 +1,49 @@
name: CI

on:
push:
pull_request:

permissions:
contents: read

env:
PHP_VERSION: '8.3'

jobs:
auto-review:
name: Auto review
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Use PHP 8.2
- name: Configure PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
php-version: ${{ env.PHP_VERSION }}

- name: Install dependencies
run: composer update --no-progress --optimize-autoloader

- name: Run phpcs
run: composer phpcs

- name: Run phpmd
run: composer phpmd
- name: Run review
run: composer review

tests:
name: Tests
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Use PHP 8.2
- name: Use PHP ${{ env.PHP_VERSION }}
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
php-version: ${{ env.PHP_VERSION }}

- name: Install dependencies
run: composer update --no-progress --optimize-autoloader

- name: Run unit tests
env:
XDEBUG_MODE: coverage
run: composer test

- name: Run mutation tests
run: composer test-mutation
- name: Run tests
run: composer tests
19 changes: 16 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
DOCKER_RUN = docker run --rm -it --net=host -v ${PWD}:/app -w /app gustavofreze/php:8.2
ifeq ($(OS),Windows_NT)
PWD := $(shell cd)
else
PWD := $(shell pwd -L)
endif

ARCH := $(shell uname -m)
PLATFORM :=

ifeq ($(ARCH),arm64)
PLATFORM := --platform=linux/amd64
endif

DOCKER_RUN = docker run ${PLATFORM} --rm -it --net=host -v ${PWD}:/app -w /app gustavofreze/php:8.3

.PHONY: configure test test-file test-no-coverage review show-reports clean

Expand All @@ -9,7 +22,7 @@ test:
@${DOCKER_RUN} composer tests

test-file:
@${DOCKER_RUN} composer tests-file-no-coverage ${FILE}
@${DOCKER_RUN} composer test-file ${FILE}

test-no-coverage:
@${DOCKER_RUN} composer tests-no-coverage
Expand All @@ -22,4 +35,4 @@ show-reports:

clean:
@sudo chown -R ${USER}:${USER} ${PWD}
@rm -rf report vendor .phpunit.cache
@rm -rf report vendor .phpunit.cache .lock
136 changes: 95 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@
* [Overview](#overview)
* [Installation](#installation)
* [How to use](#how-to-use)
* [Using the status code](#status_code)
* [Creating a response](#response)
* [License](#license)
* [Contributing](#contributing)

<div id='overview'></div>

## Overview

Common implementations for HTTP protocol.
Common implementations for HTTP protocol. The library exposes concrete implementations that follow the PSR standards,
specifically designed to operate with [PSR-7](https://www.php-fig.org/psr/psr-7)
and [PSR-15](https://www.php-fig.org/psr/psr-15), providing solutions for building HTTP responses, requests, and other
HTTP-related components.

<div id='installation'></div>

Expand All @@ -26,46 +31,95 @@ composer require tiny-blocks/http

## How to use

The library exposes concrete implementations for the HTTP protocol, such as status codes, methods, etc.

### Using the HttpCode

The library exposes a concrete implementation through the `HttpCode` enum. You can get the status codes, and their
corresponding messages.

```php
$httpCode = HttpCode::CREATED;

$httpCode->name; # CREATED
$httpCode->value; # 201
$httpCode->message(); # 201 Created
```

### Using the HttpMethod

The library exposes a concrete implementation via the `HttpMethod` enum. You can get a set of HTTP methods.

```php
$method = HttpMethod::GET;

$method->name; # GET
$method->value; # GET
```

### Using the HttpResponse

The library exposes a concrete implementation for HTTP responses via the `HttpResponse` class. Responses are of the
[ResponseInterface](https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php) type, according to
the specifications defined in [PSR-7](https://www.php-fig.org/psr/psr-7).

```php
$data = new Xyz(value: 10);
$response = HttpResponse::ok(data: $data);

$response->getStatusCode(); # 200
$response->getReasonPhrase(); # 200 OK
$response->getBody()->getContents(); # {"value":10}
```
The library exposes interfaces like `Headers` and concrete implementations like `Response`, `ContentType`, and others,
which facilitate construction.

<div id='status_code'></div>

### Using the status code

The library exposes a concrete implementation through the `Code` enum. You can retrieve the status codes, their
corresponding messages, and check for various status code ranges using the methods provided.

- **Get message**: Returns the [HTTP status message](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages)
associated with the enum's code.

```php
use TinyBlocks\Http\Code;

Code::OK->message(); # 200 OK
Code::IM_A_TEAPOT->message(); # 418 I'm a teapot
Code::INTERNAL_SERVER_ERROR->message(); # 500 Internal Server Error
```

- **Check if the code is valid**: Determines if the given code is a valid HTTP status code represented by the enum.

```php
use TinyBlocks\Http\Code;

Code::isValidCode(code: 200); # true
Code::isValidCode(code: 999); # false
```

- **Check if the code is an error**: Determines if the given code is in the error range (**4xx** or **5xx**).

```php
use TinyBlocks\Http\Code;

Code::isErrorCode(code: 500); # true
Code::isErrorCode(code: 200); # false
```

- **Check if the code is a success**: Determines if the given code is in the success range (**2xx**).

```php
use TinyBlocks\Http\Code;

Code::isSuccessCode(code: 500); # false
Code::isSuccessCode(code: 200); # true
```

<div id='response'></div>

### Creating a response

The library provides an easy and flexible way to create HTTP responses, allowing you to specify the status code,
headers, and body. You can use the `Response` class to generate responses, and the result will always be a
`ResponseInterface` from the PSR, ensuring compatibility with any framework that adheres
to the [PSR-7](https://www.php-fig.org/psr/psr-7) standard.

- **Creating a response with a body**: To create an HTTP response, you can pass any type of data as the body.
Optionally, you can also specify one or more headers. If no headers are provided, the response will default to
`application/json` content type.

```php
use TinyBlocks\Http\Response;

Response::ok(body: ['message' => 'Resource created successfully.']);
```

- **Creating a response with a body and custom headers**: You can also add custom headers to the response. For instance,
if you want to specify a custom content type or any other header, you can pass the headers as additional arguments.

```php
use TinyBlocks\Http\Response;
use TinyBlocks\Http\ContentType;
use TinyBlocks\Http\CacheControl;
use TinyBlocks\Http\ResponseCacheDirectives;

$body = 'This is a plain text response';

$contentType = ContentType::textPlain();

$cacheControl = CacheControl::fromResponseDirectives(
maxAge: ResponseCacheDirectives::maxAge(maxAgeInWholeSeconds: 10000),
staleIfError: ResponseCacheDirectives::staleIfError()
);

Response::ok($body, $contentType, $cacheControl)
->withHeader(name: 'X-ID', value: 100)
->withHeader(name: 'X-NAME', value: 'Xpto');
```

<div id='license'></div>

Expand Down
35 changes: 18 additions & 17 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
"keywords": [
"psr",
"http",
"psr-7",
"psr-15",
"request",
"response",
"http-code",
"tiny-blocks",
"http-status",
"http-methods",
"http-response"
"http-methods"
],
"authors": [
{
Expand Down Expand Up @@ -42,43 +45,41 @@
}
},
"require": {
"php": "^8.2",
"tiny-blocks/serializer": "^3",
"php": "^8.3",
"psr/http-message": "^1.1",
"tiny-blocks/serializer": "^3",
"ext-mbstring": "*"
},
"require-dev": {
"slim/psr7": "^1.7",
"slim/slim": "^4.14",
"phpmd/phpmd": "^2.15",
"phpunit/phpunit": "^11",
"phpstan/phpstan": "^1",
"infection/infection": "^0.29",
"squizlabs/php_codesniffer": "^3.10"
"phpunit/phpunit": "^11",
"infection/infection": "^0",
"squizlabs/php_codesniffer": "^3.11"
},
"suggest": {
"ext-mbstring": "Provides multibyte-specific string functions that help us deal with multibyte encodings in PHP."
},
"scripts": {
"test": "phpunit --configuration phpunit.xml tests",
"phpcs": "phpcs --standard=PSR12 --extensions=php ./src",
"phpmd": "phpmd ./src text phpmd.xml --suffixes php --exclude /src/HttpCode.php --exclude /src/Internal/Response --ignore-violations-on-exit",
"phpmd": "phpmd ./src text phpmd.xml --suffixes php --ignore-violations-on-exit",
"phpstan": "phpstan analyse -c phpstan.neon.dist --quiet --no-progress",
"test": "phpunit --log-junit=report/coverage/junit.xml --coverage-xml=report/coverage/coverage-xml --coverage-html=report/coverage/coverage-html tests",
"test-mutation": "infection --only-covered --logger-html=report/coverage/mutation-report.html --coverage=report/coverage --min-msi=100 --min-covered-msi=100 --threads=4",
"test-no-coverage": "phpunit --no-coverage",
"test-mutation-no-coverage": "infection --only-covered --min-msi=100 --threads=4",
"test-file": "phpunit --configuration phpunit.xml --no-coverage --filter",
"mutation-test": "infection --only-covered --threads=max --logger-html=report/coverage/mutation-report.html --coverage=report/coverage",
"test-no-coverage": "phpunit --configuration phpunit.xml --no-coverage tests",
"review": [
"@phpcs",
"@phpmd",
"@phpstan"
],
"tests": [
"@test",
"@test-mutation"
"@mutation-test"
],
"tests-no-coverage": [
"@test-no-coverage",
"@test-mutation-no-coverage"
],
"tests-file-no-coverage": [
"@test-no-coverage"
]
}
Expand Down
26 changes: 12 additions & 14 deletions infection.json.dist
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
{
"timeout": 10,
"testFramework": "phpunit",
"logs": {
"text": "report/infection/logs/infection-text.log",
"summary": "report/infection/logs/infection-summary.log"
},
"tmpDir": "report/infection/",
"minMsi": 100,
"timeout": 30,
"source": {
"directories": [
"src"
]
},
"logs": {
"text": "report/infection/logs/infection-text.log",
"summary": "report/infection/logs/infection-summary.log"
},
"mutators": {
"@default": true,
"CastInt": false,
"CastString": false,
"MatchArmRemoval": false,
"MethodCallRemoval": false
},
"phpUnit": {
"configDir": "",
"customPath": "./vendor/bin/phpunit"
}
},
"mutators": {
"@default": true
},
"minCoveredMsi": 100,
"testFramework": "phpunit"
}
1 change: 0 additions & 1 deletion phpmd.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,4 @@
<rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/>
<rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/>
<rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/>
<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>
</ruleset>
Loading
Loading