Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: mepihindeveloper/php-headers
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: v1.0.1
Choose a base ref
...
head repository: mepihindeveloper/php-headers
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: stable
Choose a head ref
  • 10 commits
  • 21 files changed
  • 1 contributor

Commits on Mar 18, 2021

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    a7782db View commit details
  2. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    8c63d93 View commit details
  3. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    56330cd View commit details

Commits on Mar 23, 2021

  1. Copy the full SHA
    eb684dd View commit details
  2. Copy the full SHA
    d0ebd35 View commit details
  3. Copy the full SHA
    1f59ad8 View commit details

Commits on Jan 18, 2022

  1. Copy the full SHA
    6c3f69e View commit details
  2. Copy the full SHA
    d6b6733 View commit details
  3. Merge pull request #1

    Тесты и небольшие исправления
    mepihindeveloper authored Jan 18, 2022

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
    Copy the full SHA
    f635089 View commit details
  4. Copy the full SHA
    6aeec95 View commit details
61 changes: 61 additions & 0 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: build

on:
push:
branches: [ stable, development ]
pull_request:
branches: [ stable, development ]

jobs:
build:
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
max-parallel: 2
fail-fast: false
matrix:
php: [7.4, 8.0]
experimental: [false]

steps:
- uses: actions/checkout@v2

- name: Setup PHP Action
uses: shivammathur/setup-php@2.16.0
with:
php-version: ${{ matrix.php }}
coverage: xdebug

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

- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
- name: Install dependencies with Composer
uses: ramsey/composer-install@v1

- name: Run unit tests
run: php vendor/bin/codecept run unit

- name: Run Codecept coverage
run: php vendor/bin/codecept run --coverage --coverage-xml --coverage-phpunit

- name: Download artifacts
uses: actions/download-artifact@v2

- name: Codecov
uses: codecov/codecov-action@v2.1.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
directory: ./tests/_output
files: ./tests/_output/coverage.xml
flags: unittests
verbose: true
fail_ci_if_error: true
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# php-headers

![release](https://img.shields.io/github/v/release/mepihindeveloper/php-headers?label=version)
[![Packagist Version](https://img.shields.io/packagist/v/mepihindeveloper/php-headers)](https://packagist.org/packages/mepihindeveloper/php-headers)
[![PHP Version Require](http://poser.pugx.org/mepihindeveloper/php-headers/require/php)](https://packagist.org/packages/mepihindeveloper/php-headers)
![license](https://img.shields.io/github/license/mepihindeveloper/php-headers)

![build](https://github.com/mepihindeveloper/php-headers/actions/workflows/php.yml/badge.svg?branch=stable)
[![codecov](https://codecov.io/gh/mepihindeveloper/php-headers/branch/stable/graph/badge.svg?token=36PP7VKHKG)](https://codecov.io/gh/mepihindeveloper/php-headers)


Компонент для работы с заголовками в PHP

# Структура
@@ -19,20 +28,21 @@ src/

| Метод | Аргументы | Возвращаемые данные | Исключения | Описание |
|---------------------|-----------------------------|---------------------|--------------------------|-----------------------------------------------------------------------------|
| set(array $params) | Заголовок(и) [key => value] | void | | Устанавливает заголовок(и) |
| add(array $params) | Заголовок(и) [key => value] | void | | Добавляет заголовок. Если заголовок уже существует, то он будет перезаписан |
| remove(string $key) | Заголовок | void | | Удаляет заголовок |
| removeAll | | void | | Удаляет все заголовки |
| has(string $key) | Заголовок | bool | | Проверяет наличие заголовка. Проверка идет на наличие ключа и значения |
| get(string $key) | Заголовок | string | InvalidArgumentException | Получает значение заголовка |
| getAll | | | | Получает все заголовки |
| getIsApache | | bool | | Возвращает, является ли сервер Apache |

# Контакты

Вы можете связаться со мной в социальной сети ВКонтакте: [ВКонтакте: Максим Епихин](https://vk.com/maximepihin)

Если удобно писать на почту, то можете воспользоваться этим адресом: mepihindeveloper@gmail.com

Мой канал на YouTube, который посвящен разработке веб и игровых проектов: [YouTube: Максим Епихин](https://www.youtube.com/channel/UCKusRcoHUy6T4sei-rVzCqQ)
Мой канал на YouTube, который посвящен разработке веб и игровых
проектов: [YouTube: Максим Епихин](https://www.youtube.com/channel/UCKusRcoHUy6T4sei-rVzCqQ)

Поддержать меня можно переводом на Яндекс.Деньги: [Денежный перевод](https://yoomoney.ru/to/410012382226565)
16 changes: 16 additions & 0 deletions codeception.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
paths:
tests: tests
output: tests/_output
data: tests/_data
support: tests/_support
envs: tests/_envs
actor_suffix: Tester
extensions:
enabled:
- Codeception\Extension\RunFailed
coverage:
enabled: true
include:
- src/*
exclude:
- src/interfaces/*
57 changes: 31 additions & 26 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
{
"name": "mepihindeveloper/php-headers",
"description": "Component for working with headers",
"type": "library",
"license": "MIT",
"keywords": [
"component",
"class",
"php",
"headers"
],
"authors": [
{
"name": "mepihindeveloper",
"email": "mepihindeveloper@gmail.com"
}
],
"require": {
"php": "^7.4|^8.0"
},
"autoload": {
"psr-4": {
"mepihindeveloper\\components\\": "src/"
}
},
"minimum-stability": "dev",
"prefer-stable": true
"name": "mepihindeveloper/php-headers",
"description": "Component for working with headers",
"type": "library",
"license": "MIT",
"keywords": [
"component",
"class",
"php",
"headers"
],
"authors": [
{
"name": "mepihindeveloper",
"email": "mepihindeveloper@gmail.com"
}
],
"require": {
"php": ">=7.4"
},
"autoload": {
"psr-4": {
"mepihindeveloper\\components\\": "src/"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"require-dev": {
"codeception/codeception": "^4.1",
"codeception/module-phpbrowser": "^1.0.0",
"codeception/module-asserts": "^1.0.0"
}
}
91 changes: 36 additions & 55 deletions src/Headers.php
Original file line number Diff line number Diff line change
@@ -12,41 +12,51 @@
*
* Реализует управление заголовками запроса
*/
class Headers implements HeadersInterface
{
class Headers implements HeadersInterface {

public const APACHE = 'Apache';

/**
* @var array Заголовки
*/
private array $headers;
/**
* @var bool Является ли сервер Apache
*/
private bool $isApache;

public function __construct()
{
public function __construct() {
$this->isApache = array_key_exists('SERVER_SOFTWARE', $_SERVER) && $_SERVER['SERVER_SOFTWARE'] === self::APACHE;
$this->headers = $this->getAllHeaders();
}

/**
* Возвращает, является ли сервер Apache
*
* @return bool
*/
public function getIsApache():bool {
return $this->isApache;
}

/**
* Получает все заголовки методами apache и nginx
*
* @return array
*/
private function getAllHeaders(): array
{
if (function_exists('getallheaders')) {
public function getAllHeaders(): array {
if ($this->isApache && function_exists('getallheaders')) {
return getallheaders() !== false ? getallheaders() : [];
}

if (!is_array($_SERVER))
{

if (!is_array($_SERVER)) {
return [];
}

$headers = [];

foreach ($_SERVER as $name => $value)
{
if (strpos($name, 'HTTP_') === 0)
{
foreach ($_SERVER as $name => $value) {
if (strpos($name, 'HTTP_') === 0) {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
@@ -57,48 +67,34 @@ private function getAllHeaders(): array
/**
* @inheritDoc
*/
public function set(array $params): void
{
$this->getAll();

foreach ($params as $header => $value)
{
$this->headers[$header] = $value;
}

$this->add($params);
public function getAll(): array {
return $this->headers;
}

/**
* @inheritDoc
*/
public function add(array $params): void
{
foreach ($params as $header => $value)
{
public function add(array $params): void {
foreach ($params as $header => $value) {
$headerExists = array_key_exists($header, $this->headers);
$this->headers[$header] = $value;

header("{$header}: {$value}", $headerExists);
header("$header: $value", $headerExists);
}
}

/**
* @inheritDoc
*/
public function remove(string $key): void
{
$this->getAll();

public function remove(string $key): void {
unset($this->headers[$key]);
header_remove($key);
}

/**
* @inheritDoc
*/
public function removeAll(): void
{
public function removeAll(): void {
$this->headers = [];

header_remove();
@@ -107,21 +103,9 @@ public function removeAll(): void
/**
* @inheritDoc
*/
public function has(string $key): bool
{
$this->getAll();

return array_key_exists($key, $this->headers);
}

/**
* @inheritDoc
*/
public function get(string $key): string
{
if (!$this->has($key))
{
throw new InvalidArgumentException("Заголоков {$key} отсутсвует.");
public function get(string $key): string {
if (!$this->has($key)) {
throw new InvalidArgumentException("Заголовок {$key} отсутствует.");
}

return $this->headers[$key];
@@ -130,10 +114,7 @@ public function get(string $key): string
/**
* @inheritDoc
*/
public function getAll(): array
{
$this->headers = !empty($this->headers) ? $this->headers : $this->getAllHeaders();

return $this->headers;
public function has(string $key): bool {
return array_key_exists($key, $this->headers);
}
}
9 changes: 0 additions & 9 deletions src/interfaces/HeadersInterface.php
Original file line number Diff line number Diff line change
@@ -13,15 +13,6 @@
*/
interface HeadersInterface {

/**
* Устанавливает заголовок(и)
*
* @param array $params Заголовок(и) [key => value]
*
* @return void
*/
public function set(array $params): void;

/**
* Добавляет заголовок. Если заголовок уже существует, то он будет перезаписан.
*
Empty file added tests/_data/.gitkeep
Empty file.
2 changes: 2 additions & 0 deletions tests/_output/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*
!.gitignore
26 changes: 26 additions & 0 deletions tests/_support/AcceptanceTester.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php


/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method void pause()
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;

/**
* Define custom actions here
*/
}
Loading