diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index e619056..3b1e273 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,2 +1 @@ - github: [Josantonius] \ No newline at end of file diff --git a/.github/lang/es-ES/README.md b/.github/lang/es-ES/README.md index 2e25a23..e322da1 100644 --- a/.github/lang/es-ES/README.md +++ b/.github/lang/es-ES/README.md @@ -4,7 +4,7 @@ [![License](https://poser.pugx.org/josantonius/session/license)](LICENSE) [![Total Downloads](https://poser.pugx.org/josantonius/session/downloads)](https://packagist.org/packages/josantonius/session) [![CI](https://github.com/josantonius/php-session/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/josantonius/php-session/actions/workflows/ci.yml) -[![CodeCov](https://codecov.io/gh/josantonius/php-session/branch/master/graph/badge.svg)](https://codecov.io/gh/josantonius/php-session) +[![CodeCov](https://codecov.io/gh/josantonius/php-session/main/master/graph/badge.svg)](https://codecov.io/gh/josantonius/php-session) [![PSR1](https://img.shields.io/badge/PSR-1-f57046.svg)](https://www.php-fig.org/psr/psr-1/) [![PSR4](https://img.shields.io/badge/PSR-4-9b59b6.svg)](https://www.php-fig.org/psr/psr-4/) [![PSR12](https://img.shields.io/badge/PSR-12-1abc9c.svg)](https://www.php-fig.org/psr/psr-12/) @@ -13,20 +13,17 @@ Biblioteca PHP para manejo de sesiones. -> La versión 1.x se considera obsoleta y sin soporte. -> En esta versión (2.x) la biblioteca fue completamente reestructurada. -> Se recomienda revisar la documentación de esta versión y hacer los cambios necesarios -> antes de empezar a utilizarla, ya que no es compatible con la versión 1.x. - --- - [Requisitos](#requisitos) - [Instalación](#instalación) -- [Métodos disponibles](#métodos-disponibles) -- [Cómo empezar](#cómo-empezar) +- [Clases disponibles](#clases-disponibles) + - [Clase Session](#clase-session) + - [Fachada Session](#fachada-session) +- [Excepciones utilizadas](#excepciones-utilizadas) - [Uso](#uso) - [Tests](#tests) -- [Tareas pendientes](#-tareas-pendientes) +- [Tareas pendientes](#tareas-pendientes) - [Registro de Cambios](#registro-de-cambios) - [Contribuir](#contribuir) - [Patrocinar](#patrocinar) @@ -36,7 +33,9 @@ Biblioteca PHP para manejo de sesiones. ## Requisitos -Esta biblioteca es compatible con las versiones de PHP: 8.0 | 8.1. +- Sistema operativo: Linux | Windows. + +- Versiones de PHP: 8.0 | 8.1 | 8.2 | 8.3. ## Instalación @@ -61,202 +60,327 @@ También puedes **clonar el repositorio** completo con Git: git clone https://github.com/josantonius/php-session.git ``` -## Métodos disponibles +## Clases disponibles -Métodos disponibles en esta biblioteca: +### Clase Session -### Iniciar la sesión +`Josantonius\Session\Session` + +Iniciar la sesión: ```php -$session->start(array $options = []); +/** + * @throws HeadersSentException si los _headers_ ya se enviaron. + * @throws SessionStartedException si la sesión ya está iniciada. + * @throws WrongSessionOptionException si hay algún fallo con las opciones. + * + * @see https://php.net/session.configuration para ver la lista de opciones disponibles. + */ +public function start(array $options = []): bool; ``` -**@see** -para ver la lista de las `$opciones` disponibles y sus valores por defecto - -**@throws** `SessionException` Si los _headers_ ya se enviaron +Comprobar si la sesión fue iniciada: -**@throws** `SessionException` Si la sesión ya está iniciada +```php +public function isStarted(): bool; +``` -**@throws** `SessionException` Si hay algún fallo con las opciones +Establecer un atributo por su nombre: -**@Return** `bool` +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function set(string $name, mixed $value): void; +``` -### Comprobar si la sesión está iniciada +Obtener un atributo por su nombre: ```php -$session->isStarted(); +/** + * Opcionalmente define un valor por defecto cuando el atributo no existe. + */ +public function get(string $name, mixed $default = null): mixed; ``` -**@Return** `bool` - -### Establecer un atributo por su nombre +Obtener todos los atributos: ```php -$session->set(string $name, mixed $value = null); +public function all(): array; ``` -**@throws** `SessionException` Si la sesión no está iniciada - -**@Return** `void` +Comprobar si un atributo existe en la sesión: -### Obtener un atributo por su nombre +```php +public function has(string $name): bool; +``` -Opcionalmente define un valor por defecto cuando el atributo no existe. +Establecer múltiples atributos de una vez: ```php -$session->get(string $name, mixed $default = null); +/** + * Si los atributos existen se sustituyen, si no existen se crean. + * + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function replace(array $data): void; ``` -**@Return** `mixed` Valor - -### Obtener todos los atributos +Eliminar un atributo por su nombre y devolver su valor: ```php -$session->all(); +/** + * Opcionalmente define un valor por defecto cuando el atributo no existe. + * + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function pull(string $name, mixed $default = null): mixed; ``` -**@Return** `array` Contenido de la $_SESSION - -### Comprobar si un atributo existe en la sesión +Eliminar un atributo por su nombre: ```php -$session->has(string $name); +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function remove(string $name): void; ``` -**@Return** `bool` +Liberar todas las variables de la sesión: -### Establecer múltiples atributos de una vez +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function clear(): void; +``` -Si los atributos existen se sustituyen, si no existen se crean. +Obtiene el ID de la sesión: ```php -$session->replace(array $data); +public function getId(): string; ``` -**@throws** `SessionException` Si la sesión no está iniciada +Establecer el ID de la sesión: -**@Return** `void` +```php +/** + * @throws SessionStartedException si la sesión ya está iniciada. + */ +public function setId(string $sessionId): void; +``` -### Eliminar un atributo por su nombre y devolver su valor +Actualizar el ID de la sesión actual con uno recién generado: -Opcionalmente define un valor por defecto cuando el atributo no existe. +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function regenerateId(bool $deleteOldSession = false): bool; +``` + +Obtener el nombre de la sesión: ```php -$session->pull(string $name, mixed $default = null); +public function getName(): string; ``` -**@throws** `SessionException` Si la sesión no está iniciada +Establecer el nombre de la sesión: -**@Return** `mixed` Valor +```php +/** + * @throws SessionStartedException si la sesión ya está iniciada. + */ +public function setName(string $name): void; +``` -### Eliminar un atributo por su nombre +Eliminar la sesión: ```php -$session->remove(string $name); +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public function destroy(): bool; ``` -**@throws** `SessionException` Si la sesión no está iniciada +### Fachada Session -**@Return** `void` +`Josantonius\Session\Facades\Session` -### Liberar todas las variables de la sesión +Iniciar la sesión: ```php -$session->clear(); +/** + * @throws HeadersSentException si los _headers_ ya se enviaron. + * @throws SessionStartedException si la sesión ya está iniciada. + * @throws WrongSessionOptionException si hay algún fallo con las opciones. + * + * @see https://php.net/session.configuration para ver la lista de opciones disponibles. + */ +public static function start(array $options = []): bool; ``` -**@throws** `SessionException` Si la sesión no está iniciada +Comprobar si la sesión fue iniciada: -**@Return** `void` +```php +public static function isStarted(): bool; +``` -### Obtiene el ID de la sesión +Establecer un atributo por su nombre: ```php -$session->getId(); +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function set(string $name, mixed $value): void; ``` -**@Return** `string` ID de la sesión - -### Establecer el ID de la sesión +Obtener un atributo por su nombre: ```php -$session->setId(string $sessionId); +/** + * Opcionalmente define un valor por defecto cuando el atributo no existe. + */ +public static function get(string $name, mixed $default = null): mixed; ``` -**@throws** `SessionException` Si la sesión ya está iniciada +Obtener todos los atributos: -**@Return** `void` +```php +public static function all(): array; +``` -### Actualizar el ID de la sesión actual con uno recién generado +Comprobar si un atributo existe en la sesión: ```php -$session->regenerateId(bool $deleteOldSession = false); +public static function has(string $name): bool; ``` -**@throws** `SessionException` Si la sesión no está iniciada +Establecer múltiples atributos de una vez: -**@Return** `bool` +```php +/** + * Si los atributos existen se sustituyen, si no existen se crean. + * + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function replace(array $data): void; +``` -### Obtener el nombre de la sesión +Eliminar un atributo por su nombre y devolver su valor: ```php -$session->getName(); +/** + * Opcionalmente define un valor por defecto cuando el atributo no existe. + * + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function pull(string $name, mixed $default = null): mixed; ``` -**@Return** `string` Nombre de la sesión +Eliminar un atributo por su nombre: -### Establecer el nombre de la sesión +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function remove(string $name): void; +``` + +Liberar todas las variables de la sesión: ```php -$session->setName(string $name); +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function clear(): void; ``` -**@throws** `SessionException` Si la sesión ya está iniciada +Obtiene el ID de la sesión: -**@Return** `void` +```php +public static function getId(): string; +``` -### Eliminar la sesión +Establecer el ID de la sesión: ```php -$session->destroy(); +/** + * @throws SessionStartedException si la sesión ya está iniciada. + */ +public static function setId(string $sessionId): void; ``` -**@throws** `SessionException` Si la sesión no está iniciada +Actualizar el ID de la sesión actual con uno recién generado: -**@Return** `bool` +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function regenerateId(bool $deleteOldSession = false): bool; +``` -## Cómo empezar +Obtener el nombre de la sesión: -Para utilizar esta biblioteca con **Composer**: +```php +public static function getName(): string; +``` + +Establecer el nombre de la sesión: ```php -use Josantonius\Session\Session; +/** + * @throws SessionStartedException si la sesión ya está iniciada. + */ +public static function setName(string $name): void; +``` -$session = new Session(); +Eliminar la sesión: + +```php +/** + * @throws SessionNotStartedException si la sesión no está iniciada. + */ +public static function destroy(): bool; ``` -O puedes utilizar la fachada para acceder a los métodos de manera estática: +## Excepciones utilizadas ```php -use Josantonius\Session\Facades\Session; +use Josantonius\Session\Exceptions\HeadersSentException; +use Josantonius\Session\Exceptions\SessionException; +use Josantonius\Session\Exceptions\SessionNotStartedException; +use Josantonius\Session\Exceptions\SessionStartedException; +use Josantonius\Session\Exceptions\WrongSessionOptionException; ``` ## Uso -Ejemplo de uso para esta biblioteca: +Ejemplos de uso para esta biblioteca: -### - Iniciar la sesión - -Sin establecer opciones: +### Iniciar la sesión sin establecer opciones ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->start(); ``` -Estableciendo opciones: +```php +use Josantonius\Session\Facades\Session; + +Session::start(); +``` + +### Iniciar la sesión estableciendo opciones ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->start([ // 'cache_expire' => 180, // 'cache_limiter' => 'nocache', @@ -287,243 +411,306 @@ $session->start([ ]); ``` -Utilizando la fachada: - ```php -Session::start(); -``` +use Josantonius\Session\Facades\Session; -### - Comprobar si la sesión está iniciada +Session::start([ + 'cookie_httponly' => true, +]); +``` -Utilizando el objeto de sesión: +### Comprobar si la sesión fue iniciada ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->isStarted(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::isStarted(); ``` -### - Establecer un atributo por su nombre - -Utilizando el objeto de sesión: +### Establecer un atributo por su nombre ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->set('foo', 'bar'); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::set('foo', 'bar'); ``` -### - Obtener un atributo por su nombre - -Sin valor por defecto si el atributo no existe: +### Obtener un atributo por su nombre sin establecer valor por defecto ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->get('foo'); // null si el atributo no existe ``` -Con valor por defecto si el atributo no existe: - ```php -$session->get('foo', false); // false si el atributo no existe +use Josantonius\Session\Facades\Session; + +Session::get('foo'); // null si el atributo no existe ``` -Utilizando la fachada: +### Obtener un atributo por su nombre estableciendo valor por defecto ```php -Session::get('foo'); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->get('foo', false); // false si el atributo no existe ``` -### - Obtener todos los atributos +```php +use Josantonius\Session\Facades\Session; -Utilizando el objeto de sesión: +Session::get('foo', false); // false si el atributo no existe +``` + +### Obtener todos los atributos ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->all(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::all(); ``` -### - Comprobar si un atributo existe en la sesión - -Utilizando el objeto de sesión: +### Comprobar si un atributo existe en la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->has('foo'); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::has('foo'); ``` -### - Establecer múltiples atributos de una vez - -Utilizando el objeto de sesión: +### Establecer múltiples atributos de una vez ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->replace(['foo' => 'bar', 'bar' => 'foo']); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::replace(['foo' => 'bar', 'bar' => 'foo']); ``` -### - Eliminar un atributo por su nombre y devolver su valor - -Sin valor por defecto si el atributo no existe: +### Elimina un atributo y devuelve su valor o el valor por defecto si no existe ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->pull('foo'); // null si el atributo no existe ``` -Con valor por defecto si el atributo no existe: - ```php -$session->pull('foo', false); // false si el atributo no existe +use Josantonius\Session\Facades\Session; + +Session::pull('foo'); // null si el atributo no existe ``` -Utilizando la fachada: +### Elimina un atributo y devuelve su valor o el valor personalizado si no existe ```php -Session::pull('foo'); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->pull('foo', false); // false si el atributo no existe ``` -### - Eliminar un atributo por su nombre +```php +use Josantonius\Session\Facades\Session; + +Session::pull('foo', false); // false si el atributo no existe +``` -Utilizando el objeto de sesión: +### Eliminar un atributo por su nombre ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->remove('foo'); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::remove('foo'); ``` -### - Liberar todas las variables de la sesión - -Utilizando el objeto de sesión: +### Liberar todas las variables de la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->clear(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::clear(); ``` -### - Obtiene el ID de la sesión - -Utilizando el objeto de sesión: +### Obtiene el ID de la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->getId(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::getId(); ``` -### - Establecer el ID de la sesión - -Utilizando el objeto de sesión: +### Establecer el ID de la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->setId('foo'); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::setId('foo'); ``` -### - Actualizar el ID de la sesión actual con uno recién generado - -Regenerar el ID sin borrar la sesión anterior: +### Actualizar el ID de la sesión actual con uno recién generado ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->regenerateId(); ``` -Regenerar el ID borrando la sesión anterior: - ```php -$session->regenerateId(true); +use Josantonius\Session\Facades\Session; + +Session::regenerateId(); ``` -Utilizando la fachada: +### Actualizar el ID de la sesión actual por otro y eliminar la sesión anterior ```php -Session::regenerateId(); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->regenerateId(true); ``` -### - Obtener el nombre de la sesión +```php +use Josantonius\Session\Facades\Session; + +Session::regenerateId(true); +``` -Utilizando el objeto de sesión: +### Obtener el nombre de la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->getName(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::getName(); ``` -### - Establecer el nombre de la sesión - -Utilizando el objeto de sesión: +### Establecer el nombre de la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->setName('foo'); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::setName('foo'); ``` -### - Eliminar la sesión - -Utilizando el objeto de sesión: +### Eliminar la sesión ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->destroy(); ``` -Utilizando la fachada: - ```php +use Josantonius\Session\Facades\Session; + Session::destroy(); ``` ## Tests -Para ejecutar las [pruebas](tests) necesitarás [Composer](http://getcomposer.org/download/) y seguir los siguientes pasos: +Para ejecutar las [pruebas](tests) necesitarás [Composer](http://getcomposer.org/download/) +y seguir los siguientes pasos: ```console git clone https://github.com/josantonius/php-session.git @@ -549,7 +736,8 @@ Ejecutar pruebas de estándares de código con [PHPCS](https://github.com/squizl composer phpcs ``` -Ejecutar pruebas con [PHP Mess Detector](https://phpmd.org/) para detectar inconsistencias en el estilo de codificación: +Ejecutar pruebas con [PHP Mess Detector](https://phpmd.org/) +para detectar inconsistencias en el estilo de codificación: ```console composer phpmd @@ -561,17 +749,17 @@ Ejecutar todas las pruebas anteriores: composer tests ``` -## ☑ Tareas pendientes +## Tareas pendientes -- [ ] Añadir nueva funcionalidad. -- [ ] Mejorar pruebas. -- [ ] Mejorar documentación. -- [ ] Mejorar la traducción al inglés en el archivo README. -- [ ] Refactorizar código para las reglas de estilo de código deshabilitadas. -Ver [phpmd.xml](phpmd.xml) y [phpcs.xml](phpcs.xml). -- [ ] Mostrar un ejemplo de renovación de la duración de la sesión. -- [ ] Funcionalidad para activar/desactivar excepciones? -- [ ] Funcionalidad para añadir prefijos en los atributos de sesión? +- [ ] Añadir nueva funcionalidad +- [ ] Mejorar pruebas +- [ ] Mejorar documentación +- [ ] Mejorar la traducción al inglés en el archivo README +- [ ] Refactorizar código para las reglas de estilo de código deshabilitadas +(ver [phpmd.xml](phpmd.xml) y [phpcs.xml](phpcs.xml)) +- [ ] Mostrar un ejemplo de renovación de la duración de la sesión +- [ ] ¿Funcionalidad para activar/desactivar excepciones? +- [ ] ¿Funcionalidad para añadir prefijos en los atributos de sesión? ## Registro de Cambios @@ -583,7 +771,7 @@ Los cambios detallados de cada versión se documentan en las Por favor, asegúrate de leer la [Guía de contribución](CONTRIBUTING.md) antes de hacer un _pull request_, comenzar una discusión o reportar un _issue_. -¡Gracias por [colaborar](https://github.com/josantonius/php-json/graphs/contributors)! :heart: +¡Gracias por [colaborar](https://github.com/josantonius/php-session/graphs/contributors)! :heart: ## Patrocinar diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 93e8597..1318904 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: - name: 'Setup PHP' uses: 'shivammathur/setup-php@v2' with: - php-version: '8.1' + php-version: '8.3' coverage: 'none' tools: 'composer:v2, composer-normalize' @@ -43,10 +43,12 @@ jobs: name: 'PHPUnit (PHP ${{ matrix.php }} - ${{ matrix.system }})' strategy: matrix: - system: ['ubuntu-latest'] + system: ['ubuntu-latest', 'windows-latest'] php: - '8.0' - '8.1' + - '8.2' + - '8.3' steps: - name: Checkout Code uses: actions/checkout@v3 @@ -76,7 +78,7 @@ jobs: - name: 'Setup PHP' uses: 'shivammathur/setup-php@v2' with: - php-version: '8.1' + php-version: '8.3' tools: 'composer:v2' - name: 'Install dependencies' diff --git a/CHANGELOG.md b/CHANGELOG.md index a159c46..1180163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,75 @@ # CHANGELOG +## [v2.0.9](https://github.com/josantonius/php-session/releases/tag/v2.0.9) (2024-05-20) + +* Tests for PHP 8.3 have been added. + +## [v2.0.8](https://github.com/josantonius/php-session/releases/tag/v2.0.8) (2022-09-29) + +* The notation type in the test function names has been changed from camel to snake case for readability. + +* Functions were added to document the methods and avoid confusion. + +* Disabled the ´CamelCaseMethodName´ rule in ´phpmd.xml´ to avoid warnings about function names in tests. + +* The alignment of the asterisks in the comments has been fixed. + +* Tests for Windows have been added. + +* Tests for PHP 8.2 have been added. + +## [v2.0.7](https://github.com/josantonius/php-session/releases/tag/v2.0.7) (2022-08-11) + +* Improved documentation. + +## [v2.0.6](https://github.com/josantonius/php-session/releases/tag/v2.0.6) (2022-08-07) + +* The error handler was removed as it could override a previously created error handler or be +easily overridden by another error handler. + +* Functions were added to perform what was done from the error handler. + +* `Josantonius\Session\Exceptions\SessionException` was deprecated and +will be removed in the next version. + +* It is recommended to use the new exceptions added to catch exceptions: + + * `Josantonius\Session\Exceptions\HeadersSentException`; + * `Josantonius\Session\Exceptions\SessionNotStartedException`; + * `Josantonius\Session\Exceptions\SessionNotStartedException`; + * `Josantonius\Session\Exceptions\SessionStartedException`; + * `Josantonius\Session\Exceptions\WrongSessionOptionException`; + +* Documents and comments on these changes were updated. + +* There have been no major changes from the previous version. + +## [v2.0.5](https://github.com/josantonius/php-session/releases/tag/v2.0.5) (2022-07-31) + +* Fix documentation on available methods in `README.md`. + +* Removed the warning about version 1.x in the `README.md` files. + +* Fix exception comment. + +* The namespaces in the test classes were sorted. + +* Added return value in the test classes. + +* Changed the PHPUnit version from `9.0` to `9.5`. + +* Fixed blank line at the beginning of the file in `FUNDING.yml`. + +## [v2.0.4](https://github.com/josantonius/php-session/releases/tag/v2.0.4) (2022-07-13) + +* Changes in documentation. + +## [v2.0.3](https://github.com/josantonius/php-session/releases/tag/v2.0.3) (2022-07-13) + +* Changes in documentation. + +* Deleted `Josantonius\Session\Session->errorHandler()` method. + ## [v2.0.2](https://github.com/josantonius/php-session/releases/tag/v2.0.2) (2022-06-30) * Fix readme namespace. Fixes [#13](https://github.com/josantonius/php-session/issues/13). diff --git a/README.md b/README.md index 9eeae17..fbc47cd 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![License](https://poser.pugx.org/josantonius/session/license)](LICENSE) [![Total Downloads](https://poser.pugx.org/josantonius/session/downloads)](https://packagist.org/packages/josantonius/session) [![CI](https://github.com/josantonius/php-session/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/josantonius/php-session/actions/workflows/ci.yml) -[![CodeCov](https://codecov.io/gh/josantonius/php-session/branch/master/graph/badge.svg)](https://codecov.io/gh/josantonius/php-session) +[![CodeCov](https://codecov.io/gh/josantonius/php-session/branch/main/graph/badge.svg)](https://codecov.io/gh/josantonius/php-session) [![PSR1](https://img.shields.io/badge/PSR-1-f57046.svg)](https://www.php-fig.org/psr/psr-1/) [![PSR4](https://img.shields.io/badge/PSR-4-9b59b6.svg)](https://www.php-fig.org/psr/psr-4/) [![PSR12](https://img.shields.io/badge/PSR-12-1abc9c.svg)](https://www.php-fig.org/psr/psr-12/) @@ -13,30 +13,29 @@ PHP library for handling sessions. -> Version 1.x is considered as deprecated and unsupported. -> In this version (2.x) the library was completely restructured. -> It is recommended to review the documentation for this version and make the necessary changes -> before starting to use it, as it not be compatible with version 1.x. - --- - [Requirements](#requirements) - [Installation](#installation) -- [Available Methods](#available-methods) -- [Quick Start](#quick-start) +- [Available Classes](#available-classes) + - [Session Class](#session-class) + - [Session Facade](#session-facade) +- [Exceptions Used](#exceptions-used) - [Usage](#usage) - [Tests](#tests) - [TODO](#todo) - [Changelog](#changelog) - [Contribution](#contribution) -- [Sponsor](#Sponsor) +- [Sponsor](#sponsor) - [License](#license) --- ## Requirements -This library is compatible with the PHP versions: 8.0 | 8.1. +- Operating System: Linux | Windows. + +- PHP versions: 8.0 | 8.1 | 8.2 | 8.3. ## Installation @@ -61,202 +60,327 @@ You can also **clone the complete repository** with Git: git clone https://github.com/josantonius/php-session.git ``` -## Available Methods +## Available Classes -Available methods in this library: +### Session Class -### Starts the session +`Josantonius\Session\Session` + +Starts the session: ```php -$session->start(array $options = []); +/** + * @throws HeadersSentException if headers already sent. + * @throws SessionStartedException if session already started. + * @throws WrongSessionOptionException if setting options failed. + * + * @see https://php.net/session.configuration for List of available $options. + */ +public function start(array $options = []): bool; ``` -**@see** -for List of available `$options` and their default values - -**@throws** `SessionException` If headers already sent +Check if the session is started: -**@throws** `SessionException` If session already started +```php +public function isStarted(): bool; +``` -**@throws** `SessionException` If setting options failed +Sets an attribute by name: -**@Return** `bool` +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public function set(string $name, mixed $value): void; +``` -### Check if the session is started +Gets an attribute by name: ```php -$session->isStarted(); +/** + * Optionally defines a default value when the attribute does not exist. + */ +public function get(string $name, mixed $default = null): mixed; ``` -**@Return** `bool` - -### Sets an attribute by name +Gets all attributes: ```php -$session->set(string $name, mixed $value = null); +public function all(): array; ``` -**@throws** `SessionException` If session is unstarted +Check if an attribute exists in the session: -**@Return** `void` - -### Gets an attribute by name +```php +public function has(string $name): bool; +``` -Optionally defines a default value when the attribute does not exist. +Sets several attributes at once: ```php -$session->get(string $name, mixed $default = null); +/** + * If attributes exist they are replaced, if they do not exist they are created. + * + * @throws SessionNotStartedException if session was not started. + */ +public function replace(array $data): void; ``` -**@Return** `mixed` Value - -### Gets all attributes +Deletes an attribute by name and returns its value: ```php -$session->all(); +/** + * Optionally defines a default value when the attribute does not exist. + * + * @throws SessionNotStartedException if session was not started. + */ +public function pull(string $name, mixed $default = null): mixed; ``` -**@Return** `array` $_SESSION content - -### Check if an attribute exists in the session +Deletes an attribute by name: ```php -$session->has(string $name); +/** + * @throws SessionNotStartedException if session was not started. + */ +public function remove(string $name): void; ``` -**@Return** `bool` +Free all session variables: -### Sets several attributes at once +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public function clear(): void; +``` -If attributes exist they are replaced, if they do not exist they are created. +Gets the session ID: ```php -$session->replace(array $data); +public function getId(): string; ``` -**@throws** `SessionException` If session is unstarted +Sets the session ID: -**@Return** `void` +```php +/** + * @throws SessionStartedException if session already started. + */ +public function setId(string $sessionId): void; +``` + +Update the current session ID with a newly generated one: -### Deletes an attribute by name and returns its value +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public function regenerateId(bool $deleteOldSession = false): bool; +``` -Optionally defines a default value when the attribute does not exist. +Gets the session name: ```php -$session->pull(string $name, mixed $default = null); +public function getName(): string; ``` -**@throws** `SessionException` If session is unstarted +Sets the session name: -**@Return** `mixed` Attribute value +```php +/** + * @throws SessionStartedException if session already started. + */ +public function setName(string $name): void; +``` -### Deletes an attribute by name +Destroys the session: ```php -$session->remove(string $name); +/** + * @throws SessionNotStartedException if session was not started. + */ +public function destroy(): bool; ``` -**@throws** `SessionException` If session is unstarted +### Session Facade -**@Return** `void` +`Josantonius\Session\Facades\Session` -### Free all session variables +Starts the session: ```php -$session->clear(); +/** + * @throws HeadersSentException if headers already sent. + * @throws SessionStartedException if session already started. + * @throws WrongSessionOptionException if setting options failed. + * + * @see https://php.net/session.configuration for List of available $options. + */ +public static function start(array $options = []): bool; ``` -**@throws** `SessionException` If session is unstarted +Check if the session is started: -**@Return** `void` +```php +public static function isStarted(): bool; +``` -### Gets the session ID +Sets an attribute by name: ```php -$session->getId(); +/** + * @throws SessionNotStartedException if session was not started. + */ +public static function set(string $name, mixed $value): void; ``` -**@Return** `string` Session ID - -### Sets the session ID +Gets an attribute by name: ```php -$session->setId(string $sessionId); +/** + * Optionally defines a default value when the attribute does not exist. + */ +public static function get(string $name, mixed $default = null): mixed; ``` -**@throws** `SessionException` If session already started +Gets all attributes: -**@Return** `void` +```php +public static function all(): array; +``` -### Update the current session id with a newly generated one +Check if an attribute exists in the session: ```php -$session->regenerateId(bool $deleteOldSession = false); +public static function has(string $name): bool; ``` -**@throws** `SessionException` If session is unstarted +Sets several attributes at once: -**@Return** `bool` +```php +/** + * If attributes exist they are replaced, if they do not exist they are created. + * + * @throws SessionNotStartedException if session was not started. + */ +public static function replace(array $data): void; +``` -### Gets the session name +Deletes an attribute by name and returns its value: ```php -$session->getName(); +/** + * Optionally defines a default value when the attribute does not exist. + * + * @throws SessionNotStartedException if session was not started. + */ +public static function pull(string $name, mixed $default = null): mixed; ``` -**@Return** `string` Session name +Deletes an attribute by name: -### Sets the session name +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public static function remove(string $name): void; +``` + +Free all session variables: ```php -$session->setName(string $name); +/** + * @throws SessionNotStartedException if session was not started. + */ +public static function clear(): void; ``` -**@throws** `SessionException` If session already started +Gets the session ID: -**@Return** `void` +```php +public static function getId(): string; +``` -### Destroys the session +Sets the session ID: ```php -$session->destroy(); +/** + * @throws SessionStartedException if session already started. + */ +public static function setId(string $sessionId): void; ``` -**@throws** `SessionException` If session is unstarted +Update the current session ID with a newly generated one: -**@Return** `bool` +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public static function regenerateId(bool $deleteOldSession = false): bool; +``` -## Quick Start +Gets the session name: -To use this library with **Composer**: +```php +public static function getName(): string; +``` + +Sets the session name: ```php -use Josantonius\Session\Session; +/** + * @throws SessionStartedException if session already started. + */ +public static function setName(string $name): void; +``` -$session = new Session(); +Destroys the session: + +```php +/** + * @throws SessionNotStartedException if session was not started. + */ +public static function destroy(): bool; ``` -Or instead you can use a facade to access the methods statically: +## Exceptions Used ```php -use Josantonius\Session\Facades\Session; +use Josantonius\Session\Exceptions\HeadersSentException; +use Josantonius\Session\Exceptions\SessionException; +use Josantonius\Session\Exceptions\SessionNotStartedException; +use Josantonius\Session\Exceptions\SessionStartedException; +use Josantonius\Session\Exceptions\WrongSessionOptionException; ``` ## Usage Example of use for this library: -### - Starts the session - -Without setting options: +### Starts the session without setting options ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->start(); ``` -Setting options: +```php +use Josantonius\Session\Facades\Session; + +Session::start(); +``` + +### Starts the session setting options ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->start([ // 'cache_expire' => 180, // 'cache_limiter' => 'nocache', @@ -287,243 +411,306 @@ $session->start([ ]); ``` -Using the facade: - ```php -Session::start(); -``` +use Josantonius\Session\Facades\Session; -### - Check if the session is started +Session::start([ + 'cookie_httponly' => true, +]); +``` -Using session object: +### Check if the session is started ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->isStarted(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::isStarted(); ``` -### - Sets an attribute by name - -Using session object: +### Sets an attribute by name ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->set('foo', 'bar'); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::set('foo', 'bar'); ``` -### - Gets an attribute by name - -Without default value if attribute does not exist: +### Gets an attribute by name without setting a default value ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->get('foo'); // null if attribute does not exist ``` -With default value if attribute does not exist: - ```php -$session->get('foo', false); // false if attribute does not exist +use Josantonius\Session\Facades\Session; + +Session::get('foo'); // null if attribute does not exist ``` -Using the facade: +### Gets an attribute by name setting a default value ```php -Session::get('foo'); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->get('foo', false); // false if attribute does not exist ``` -### - Gets all attributes +```php +use Josantonius\Session\Facades\Session; -Using session object: +Session::get('foo', false); // false if attribute does not exist +``` + +### Gets all attributes ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->all(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::all(); ``` -### - Check if an attribute exists in the session - -Using session object: +### Check if an attribute exists in the session ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->has('foo'); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::has('foo'); ``` -### - Sets several attributes at once - -Using session object: +### Sets several attributes at once ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->replace(['foo' => 'bar', 'bar' => 'foo']); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::replace(['foo' => 'bar', 'bar' => 'foo']); ``` -### - Deletes an attribute by name and returns its value - -Without default value if attribute does not exist: +### Deletes an attribute and returns its value or the default value if not exist ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->pull('foo'); // null if attribute does not exist ``` -With default value if attribute does not exist: - ```php -$session->pull('foo', false); // false if attribute does not exist +use Josantonius\Session\Facades\Session; + +Session::pull('foo'); // null if attribute does not exist ``` -Using the facade: +### Deletes an attribute and returns its value or the custom value if not exist ```php -Session::pull('foo'); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->pull('foo', false); // false if attribute does not exist ``` -### - Deletes an attribute by name +```php +use Josantonius\Session\Facades\Session; + +Session::pull('foo', false); // false if attribute does not exist +``` -Using session object: +### Deletes an attribute by name ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->remove('foo'); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::remove('foo'); ``` -### - Free all session variables - -Using session object: +### Free all session variables ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->clear(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::clear(); ``` -### - Gets the session ID - -Using session object: +### Gets the session ID ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->getId(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::getId(); ``` -### - Sets the session ID - -Using session object: +### Sets the session ID ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->setId('foo'); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::setId('foo'); ``` -### - Update the current session id with a newly generated one - -Regenerate ID without deleting the old session: +### Update the current session ID with a newly generated one ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->regenerateId(); ``` -Regenerate ID by deleting the old session: - ```php -$session->regenerateId(true); +use Josantonius\Session\Facades\Session; + +Session::regenerateId(); ``` -Using the facade: +### Update the current session ID with a newly generated one deleting the old session ```php -Session::regenerateId(); +use Josantonius\Session\Session; + +$session = new Session(); + +$session->regenerateId(true); ``` -### - Gets the session name +```php +use Josantonius\Session\Facades\Session; + +Session::regenerateId(true); +``` -Using session object: +### Gets the session name ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->getName(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::getName(); ``` -### - Sets the session name - -Using session object: +### Sets the session name ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->setName('foo'); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::setName('foo'); ``` -### - Destroys the session - -Using session object: +### Destroys the session ```php +use Josantonius\Session\Session; + +$session = new Session(); + $session->destroy(); ``` -Using the facade: - ```php +use Josantonius\Session\Facades\Session; + Session::destroy(); ``` ## Tests -To run [tests](tests) you just need [composer](http://getcomposer.org/download/) and to execute the following: +To run [tests](tests) you just need [composer](http://getcomposer.org/download/) +and to execute the following: ```console git clone https://github.com/josantonius/php-session.git @@ -567,7 +754,7 @@ composer tests - [ ] Improve tests - [ ] Improve documentation - [ ] Improve English translation in the README file -- [ ] Refactor code for disabled code style rules. See [phpmd.xml](phpmd.xml) and [phpcs.xml](phpcs.xml) +- [ ] Refactor code for disabled code style rules (see phpmd.xml and phpcs.xml) - [ ] Show an example of renewing the session lifetime - [ ] Feature to enable/disable exceptions? - [ ] Feature to add prefixes in session attributes? diff --git a/composer.json b/composer.json index 2e92a9e..084abb6 100644 --- a/composer.json +++ b/composer.json @@ -4,8 +4,8 @@ "license": "MIT", "type": "library", "keywords": [ - "Session", - "PHP" + "session", + "php" ], "authors": [ { @@ -25,7 +25,7 @@ }, "require-dev": { "phpmd/phpmd": "^2.12", - "phpunit/phpunit": "^9.0", + "phpunit/phpunit": "^9.5", "squizlabs/php_codesniffer": "^3.7" }, "minimum-stability": "stable", @@ -55,7 +55,7 @@ "htmlCoverage": "vendor/bin/phpunit --coverage-html coverage", "phpcs": "vendor/bin/phpcs --standard=phpcs.xml $(find . -name '*.php');", "phpmd": "vendor/bin/phpmd src,tests text ./phpmd.xml", - "phpunit": "vendor/bin/phpunit --colors=always;", + "phpunit": "vendor/bin/phpunit", "tests": [ "clear", "@phpmd", diff --git a/phpcs.xml b/phpcs.xml index 74970b1..97e64cc 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -38,8 +38,8 @@ - - + + @@ -130,7 +130,7 @@ - + diff --git a/phpmd.xml b/phpmd.xml index b67437f..899a33d 100644 --- a/phpmd.xml +++ b/phpmd.xml @@ -1,10 +1,8 @@ Coding standard. @@ -34,7 +32,7 @@ - + @@ -67,5 +65,5 @@ - + \ No newline at end of file diff --git a/phpunit.xml b/phpunit.xml index 41e45c9..53c5592 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,5 +1,5 @@ - + src diff --git a/src/Exceptions/HeadersSentException.php b/src/Exceptions/HeadersSentException.php new file mode 100644 index 0000000..553d6b2 --- /dev/null +++ b/src/Exceptions/HeadersSentException.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Josantonius\Session\Exceptions; + +class HeadersSentException extends SessionException +{ + public function __construct(string $file, int $line) + { + parent::__construct(sprintf( + 'Session->start(): The headers have already been sent in "%s" at line %d.', + $file, + $line + )); + } +} diff --git a/src/Exceptions/SessionException.php b/src/Exceptions/SessionException.php index 314470a..1eaa7e0 100644 --- a/src/Exceptions/SessionException.php +++ b/src/Exceptions/SessionException.php @@ -12,14 +12,10 @@ namespace Josantonius\Session\Exceptions; /** - * You can use an exception and error handler with this library. + * Session exception manager. * - * @link https://github.com/josantonius/php-error-handler + * @deprecated since version v2.0.6 */ class SessionException extends \Exception { - public function __construct(string $message = 'Unknown error') - { - parent::__construct(rtrim($message, '.') . '.'); - } } diff --git a/src/Exceptions/SessionNotStartedException.php b/src/Exceptions/SessionNotStartedException.php new file mode 100644 index 0000000..4e9012d --- /dev/null +++ b/src/Exceptions/SessionNotStartedException.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Josantonius\Session\Exceptions; + +class SessionNotStartedException extends SessionException +{ + public function __construct(string $methodName) + { + parent::__construct( + 'Session->' . $methodName . '(): Changing $_SESSION when no started session.' + ); + } +} diff --git a/src/Exceptions/SessionStartedException.php b/src/Exceptions/SessionStartedException.php new file mode 100644 index 0000000..de4e868 --- /dev/null +++ b/src/Exceptions/SessionStartedException.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Josantonius\Session\Exceptions; + +class SessionStartedException extends SessionException +{ + public function __construct(string $methodName) + { + parent::__construct('Session->' . $methodName . '(): The session has already started.'); + } +} diff --git a/src/Exceptions/WrongSessionOptionException.php b/src/Exceptions/WrongSessionOptionException.php new file mode 100644 index 0000000..ae9069b --- /dev/null +++ b/src/Exceptions/WrongSessionOptionException.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Josantonius\Session\Exceptions; + +class WrongSessionOptionException extends SessionException +{ + public function __construct(string $name) + { + parent::__construct("Session->start(): Setting option '$name' failed."); + } +} diff --git a/src/Facades/Session.php b/src/Facades/Session.php index 1052ce5..2311d66 100644 --- a/src/Facades/Session.php +++ b/src/Facades/Session.php @@ -13,8 +13,11 @@ namespace Josantonius\Session\Facades; -use Josantonius\Session\Exceptions\SessionException; use Josantonius\Session\Session as SessionInstance; +use Josantonius\Session\Exceptions\HeadersSentException; +use Josantonius\Session\Exceptions\SessionStartedException; +use Josantonius\Session\Exceptions\SessionNotStartedException; +use Josantonius\Session\Exceptions\WrongSessionOptionException; /** * Session handler. @@ -62,9 +65,9 @@ private static function getInstance() * * @see https://php.net/session.configuration * - * @throws SessionException if headers already sent - * @throws SessionException if session already started - * @throws SessionException If setting options failed + * @throws HeadersSentException if headers already sent. + * @throws SessionStartedException if session already started. + * @throws WrongSessionOptionException If setting options failed. */ public static function start(array $options = []): bool { @@ -80,7 +83,7 @@ public static function all(): array } /** - * Check if an attribute exists in the session. + * Checks if an attribute exists in the session. */ public static function has(string $name): bool { @@ -89,6 +92,7 @@ public static function has(string $name): bool /** * Gets an attribute by name. + * * Optionally defines a default value when the attribute does not exist. */ public static function get(string $name, mixed $default = null): mixed @@ -97,9 +101,9 @@ public static function get(string $name, mixed $default = null): mixed } /** - * Sets an attribute by name + * Sets an attribute by name. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function set(string $name, mixed $value): void { @@ -108,9 +112,10 @@ public static function set(string $name, mixed $value): void /** * Sets several attributes at once. + * * If attributes exist they are replaced, if they do not exist they are created. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function replace(array $data): void { @@ -119,9 +124,10 @@ public static function replace(array $data): void /** * Deletes an attribute by name and returns its value. + * * Optionally defines a default value when the attribute does not exist. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function pull(string $name, mixed $default = null): mixed { @@ -131,7 +137,7 @@ public static function pull(string $name, mixed $default = null): mixed /** * Deletes an attribute by name. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function remove(string $name): void { @@ -141,7 +147,7 @@ public static function remove(string $name): void /** * Free all session variables. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function clear(): void { @@ -159,7 +165,7 @@ public static function getId(): string /** * Sets the session ID. * - * @throws SessionException if session already started + * @throws SessionStartedException if session already started. */ public static function setId(string $sessionId): void { @@ -167,9 +173,9 @@ public static function setId(string $sessionId): void } /** - * Update the current session id with a newly generated one. + * Updates the current session id with a newly generated one. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function regenerateId(bool $deleteOldSession = false): bool { @@ -187,7 +193,7 @@ public static function getName(): string /** * Sets the session name. * - * @throws SessionException if session already started + * @throws SessionStartedException if session already started. */ public static function setName(string $name): void { @@ -197,7 +203,7 @@ public static function setName(string $name): void /** * Destroys the session. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public static function destroy(): bool { @@ -205,7 +211,7 @@ public static function destroy(): bool } /** - * Check if the session is started. + * Checks if the session is started. */ public static function isStarted(): bool { diff --git a/src/Session.php b/src/Session.php index 36f9298..465a0f9 100644 --- a/src/Session.php +++ b/src/Session.php @@ -13,18 +13,16 @@ namespace Josantonius\Session; -use Josantonius\Session\Exceptions\SessionException; +use Josantonius\Session\Exceptions\HeadersSentException; +use Josantonius\Session\Exceptions\SessionStartedException; +use Josantonius\Session\Exceptions\SessionNotStartedException; +use Josantonius\Session\Exceptions\WrongSessionOptionException; /** * Session handler. */ class Session { - public function __construct() - { - set_error_handler([$this, 'errorHandler']); - } - /** * Starts the session. * @@ -59,12 +57,16 @@ public function __construct() * * @see https://php.net/session.configuration * - * @throws SessionException if headers already sent - * @throws SessionException if session already started - * @throws SessionException If setting options failed + * @throws HeadersSentException if headers already sent. + * @throws SessionStartedException if session already started. + * @throws WrongSessionOptionException If setting options failed. */ public function start(array $options = []): bool { + $this->throwExceptionIfHeadersWereSent(); + $this->throwExceptionIfSessionWasStarted(); + $this->throwExceptionIfHasWrongOptions($options); + return session_start($options); } @@ -77,7 +79,7 @@ public function all(): array } /** - * Check if an attribute exists in the session. + * Checks if an attribute exists in the session. */ public function has(string $name): bool { @@ -86,6 +88,7 @@ public function has(string $name): bool /** * Gets an attribute by name. + * * Optionally defines a default value when the attribute does not exist. */ public function get(string $name, mixed $default = null): mixed @@ -96,37 +99,39 @@ public function get(string $name, mixed $default = null): mixed /** * Sets an attribute by name. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function set(string $name, mixed $value): void { - $this->failIfSessionWasNotStarted(); + $this->throwExceptionIfSessionWasNotStarted(); $_SESSION[$name] = $value; } /** * Sets several attributes at once. + * * If attributes exist they are replaced, if they do not exist they are created. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function replace(array $data): void { - $this->failIfSessionWasNotStarted(); + $this->throwExceptionIfSessionWasNotStarted(); $_SESSION = array_merge($_SESSION, $data); } /** * Deletes an attribute by name and returns its value. + * * Optionally defines a default value when the attribute does not exist. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function pull(string $name, mixed $default = null): mixed { - $this->failIfSessionWasNotStarted(); + $this->throwExceptionIfSessionWasNotStarted(); $value = $_SESSION[$name] ?? $default; @@ -138,11 +143,11 @@ public function pull(string $name, mixed $default = null): mixed /** * Deletes an attribute by name. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function remove(string $name): void { - $this->failIfSessionWasNotStarted(); + $this->throwExceptionIfSessionWasNotStarted(); unset($_SESSION[$name]); } @@ -150,11 +155,11 @@ public function remove(string $name): void /** * Free all session variables. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function clear(): void { - $this->failIfSessionWasNotStarted(); + $this->throwExceptionIfSessionWasNotStarted(); session_unset(); } @@ -170,20 +175,24 @@ public function getId(): string /** * Sets the session ID. * - * @throws SessionException if session already started + * @throws SessionStartedException if session already started. */ public function setId(string $sessionId): void { + $this->throwExceptionIfSessionWasStarted(); + session_id($sessionId); } /** - * Update the current session id with a newly generated one. + * Updates the current session id with a newly generated one. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function regenerateId(bool $deleteOldSession = false): bool { + $this->throwExceptionIfSessionWasNotStarted(); + return session_regenerate_id($deleteOldSession); } @@ -200,25 +209,29 @@ public function getName(): string /** * Sets the session name. * - * @throws SessionException if session already started + * @throws SessionStartedException if session already started. */ public function setName(string $name): void { + $this->throwExceptionIfSessionWasStarted(); + session_name($name); } /** * Destroys the session. * - * @throws SessionException if session is unstarted + * @throws SessionNotStartedException if session was not started. */ public function destroy(): bool { + $this->throwExceptionIfSessionWasNotStarted(); + return session_destroy(); } /** - * Check if the session is started. + * Checks if the session is started. */ public function isStarted(): bool { @@ -226,29 +239,62 @@ public function isStarted(): bool } /** - * Session error handler. + * Throw exception if the session have wrong options. * - * @throws SessionException + * @throws WrongSessionOptionException If setting options failed. */ - public function errorHandler(int $severity, string $message, string $file): void + private function throwExceptionIfHasWrongOptions(array $options): void { - if ($file === __FILE__) { - throw new SessionException($message); + $validOptions = array_flip([ + 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly', + 'cookie_lifetime', 'cookie_path', 'cookie_samesite', 'cookie_secure', + 'gc_divisor', 'gc_maxlifetime', 'gc_probability', 'lazy_write', + 'name', 'read_and_close', 'referer_check', 'save_handler', + 'save_path', 'serialize_handler', 'sid_bits_per_character', 'sid_length', + 'trans_sid_hosts', 'trans_sid_tags', 'use_cookies', 'use_only_cookies', + 'use_strict_mode', 'use_trans_sid', + ]); + + foreach (array_keys($options) as $key) { + if (!isset($validOptions[$key])) { + throw new WrongSessionOptionException($key); + } } } /** - * Show warning if the session is not started. + * Throw exception if headers have already been sent. + * + * @throws HeadersSentException if headers already sent. */ - private function failIfSessionWasNotStarted(): void + private function throwExceptionIfHeadersWereSent(): void { - if (!$this->isStarted()) { - $method = debug_backtrace()[1]['function'] ?? 'unknown'; + $headersWereSent = (bool) ini_get('session.use_cookies') && headers_sent($file, $line); - trigger_error( - 'Session->' . $method . '(): Changing $_SESSION when no started session.', - E_USER_WARNING - ); - } + $headersWereSent && throw new HeadersSentException($file, $line); + } + + /** + * Throw exception if the session has already been started. + * + * @throws SessionStartedException if session already started. + */ + private function throwExceptionIfSessionWasStarted(): void + { + $methodName = debug_backtrace()[1]['function'] ?? 'unknown'; + + $this->isStarted() && throw new SessionStartedException($methodName); + } + + /** + * Throw exception if the session was not started. + * + * @throws SessionNotStartedException if session was not started. + */ + private function throwExceptionIfSessionWasNotStarted(): void + { + $methodName = debug_backtrace()[1]['function'] ?? 'unknown'; + + !$this->isStarted() && throw new SessionNotStartedException($methodName); } } diff --git a/tests/AllMethodTest.php b/tests/AllMethodTest.php index e64c088..e4fd043 100644 --- a/tests/AllMethodTest.php +++ b/tests/AllMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class AllMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldGetAllAttributes() + public function test_should_get_all_attributes(): void { $this->session->start(); @@ -41,7 +43,7 @@ public function testShouldGetAllAttributes() /** * @runInSeparateProcess */ - public function testShouldGetAllAttributesDefinedOutsideLibrary() + public function test_should_get_all_attributes_defined_outside_library(): void { session_start(); @@ -53,7 +55,7 @@ public function testShouldGetAllAttributesDefinedOutsideLibrary() /** * @runInSeparateProcess */ - public function testShouldReturnEmptyArrayWhenUnstartedSession() + public function test_should_return_empty_array_when_unstarted_session(): void { $this->assertIsArray($this->session->all()); } @@ -61,7 +63,7 @@ public function testShouldReturnEmptyArrayWhenUnstartedSession() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/ClearMethodTest.php b/tests/ClearMethodTest.php index 0a8e68e..eb837f6 100644 --- a/tests/ClearMethodTest.php +++ b/tests/ClearMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class ClearMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldClearSession() + public function test_should_clear_session(): void { $this->session->start(); @@ -44,7 +46,7 @@ public function testShouldClearSession() /** * @runInSeparateProcess */ - public function testShouldClearSessionWhenNativeSessionWasStarted() + public function test_should_clear_session_when_native_session_was_started(): void { session_start(); @@ -58,9 +60,9 @@ public function testShouldClearSessionWhenNativeSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->clear(); } @@ -68,7 +70,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/DestroyMethodTest.php b/tests/DestroyMethodTest.php index 4d14f69..bdd5f5a 100644 --- a/tests/DestroyMethodTest.php +++ b/tests/DestroyMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class DestroyMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldDestroySession() + public function test_should_destroy_session(): void { $this->session->start(); @@ -44,7 +46,7 @@ public function testShouldDestroySession() /** * @runInSeparateProcess */ - public function testShouldDestroySessionWhenNativeSessionWasStarted() + public function test_should_destroy_session_when_native_session_was_started(): void { session_start(); @@ -58,9 +60,9 @@ public function testShouldDestroySessionWhenNativeSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->destroy(); } @@ -68,7 +70,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/GetIdMethodTest.php b/tests/GetIdMethodTest.php index 774a97b..9de0e0b 100644 --- a/tests/GetIdMethodTest.php +++ b/tests/GetIdMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class GetIdMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldGetSessionId() + public function test_should_get_session_id(): void { $this->session->start(); @@ -39,7 +41,7 @@ public function testShouldGetSessionId() /** * @runInSeparateProcess */ - public function testShouldGetSessionIdIfNativeSessionWasStarted() + public function test_should_get_session_id_if_native_session_was_started(): void { session_start(); @@ -49,7 +51,7 @@ public function testShouldGetSessionIdIfNativeSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldReturnEmptyStringIfSessionIsUnstarted() + public function test_should_return_empty_string_if_session_is_unstarted(): void { $this->assertEquals('', $this->session->getId()); } @@ -57,7 +59,7 @@ public function testShouldReturnEmptyStringIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/GetMethodTest.php b/tests/GetMethodTest.php index 02390b5..ce098a4 100644 --- a/tests/GetMethodTest.php +++ b/tests/GetMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class GetMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldGetAttributeIfExists() + public function test_should_get_attribute_if_exists(): void { $this->session->start(); @@ -41,7 +43,7 @@ public function testShouldGetAttributeIfExists() /** * @runInSeparateProcess */ - public function testShouldGetDefaultValueIfNotExists() + public function test_should_get_default_value_if_not_exists(): void { $this->session->start(); @@ -51,7 +53,7 @@ public function testShouldGetDefaultValueIfNotExists() /** * @runInSeparateProcess */ - public function testShouldGetCustomDefaultValueIfNotExists() + public function test_should_get_custom_default_value_if_not_exists(): void { $this->session->start(); @@ -61,7 +63,7 @@ public function testShouldGetCustomDefaultValueIfNotExists() /** * @runInSeparateProcess */ - public function testShouldGetAttributeDefinedOutsideLibrary() + public function test_should_get_attribute_defined_outside_library(): void { session_start(); @@ -73,7 +75,7 @@ public function testShouldGetAttributeDefinedOutsideLibrary() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/GetNameMethodTest.php b/tests/GetNameMethodTest.php index 0e73184..88a558d 100644 --- a/tests/GetNameMethodTest.php +++ b/tests/GetNameMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class GetNameMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldGetSessionName() + public function test_should_get_session_name(): void { $this->session->start(); @@ -39,7 +41,7 @@ public function testShouldGetSessionName() /** * @runInSeparateProcess */ - public function testShouldGetSessionNameIfNativeSessionWasStarted() + public function test_should_get_session_name_if_native_session_was_started(): void { session_start(); @@ -49,7 +51,7 @@ public function testShouldGetSessionNameIfNativeSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldReturnEmptyStringIfSessionIsUnstarted() + public function test_should_return_empty_string_if_session_is_unstarted(): void { $this->assertEquals('PHPSESSID', $this->session->getName()); } @@ -57,7 +59,7 @@ public function testShouldReturnEmptyStringIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/HasMethodTest.php b/tests/HasMethodTest.php index dafdd3f..7c211f7 100644 --- a/tests/HasMethodTest.php +++ b/tests/HasMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class HasMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldCheckIfAttributeExists() + public function test_should_check_if_attribute_exists(): void { $this->session->start(); @@ -43,7 +45,7 @@ public function testShouldCheckIfAttributeExists() /** * @runInSeparateProcess */ - public function testShouldCheckAttributeDefinedOutsideLibrary() + public function test_should_check_attribute_defined_outside_library(): void { session_start(); @@ -55,7 +57,7 @@ public function testShouldCheckAttributeDefinedOutsideLibrary() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/IsStartedMethodTest.php b/tests/IsStartedMethodTest.php index 5aebc8b..f027a77 100644 --- a/tests/IsStartedMethodTest.php +++ b/tests/IsStartedMethodTest.php @@ -7,13 +7,15 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class IsActiveMethodTest extends TestCase { @@ -29,7 +31,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldCheckIfSessionIsActive() + public function test_should_check_if_session_is_active(): void { $this->assertFalse($this->session->isStarted()); @@ -41,7 +43,7 @@ public function testShouldCheckIfSessionIsActive() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/PullMethodTest.php b/tests/PullMethodTest.php index 919fe75..1a88e0c 100644 --- a/tests/PullMethodTest.php +++ b/tests/PullMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; +use Josantonius\Session\Exceptions\SessionNotStartedException; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; class PullMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldPullAttributeAndReturnTheValueIfExists() + public function test_should_pull_attribute_and_return_the_value_if_exists(): void { $this->session->start(); @@ -44,7 +46,7 @@ public function testShouldPullAttributeAndReturnTheValueIfExists() /** * @runInSeparateProcess */ - public function testShouldReturnDefaultValueIfAttributeNotExists() + public function test_should_return_default_value_if_attribute_not_exists(): void { $this->session->start(); @@ -54,7 +56,7 @@ public function testShouldReturnDefaultValueIfAttributeNotExists() /** * @runInSeparateProcess */ - public function testShouldReturnCustomDefaultValueIfAttributeNotExists() + public function test_should_return_custom_default_value_if_attribute_not_exists(): void { $this->session->start(); @@ -64,9 +66,9 @@ public function testShouldReturnCustomDefaultValueIfAttributeNotExists() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted() { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->pull('foo'); } @@ -74,7 +76,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/RegenerateIdMethodTest.php b/tests/RegenerateIdMethodTest.php index 6a41cbf..d5e621c 100644 --- a/tests/RegenerateIdMethodTest.php +++ b/tests/RegenerateIdMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class RegenerateIdMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldRegenerateSessionIdWithoutDeletingOldSession() + public function test_should_regenerate_session_id_without_deleting_old_session(): void { $this->session->start(); @@ -44,7 +46,7 @@ public function testShouldRegenerateSessionIdWithoutDeletingOldSession() /** * @runInSeparateProcess */ - public function testShouldRegenerateSessionIdDeletingOldSession() + public function test_should_regenerate_session_id_deleting_old_session(): void { $this->session->start(); @@ -58,9 +60,9 @@ public function testShouldRegenerateSessionIdDeletingOldSession() /** * @runInSeparateProcess */ - public function testShouldFailWhenRegenerateIdIfSessionIsUnstarted() + public function test_should_fail_when_regenerate_id_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->regenerateId(); } @@ -68,7 +70,7 @@ public function testShouldFailWhenRegenerateIdIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/RemoveMethodTest.php b/tests/RemoveMethodTest.php index 0c39b86..76aeed3 100644 --- a/tests/RemoveMethodTest.php +++ b/tests/RemoveMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class RemoveMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldRemoveAttributeIfExist() + public function test_should_remove_attribute_if_exist(): void { $this->session->start(); @@ -44,7 +46,7 @@ public function testShouldRemoveAttributeIfExist() /** * @runInSeparateProcess */ - public function testShouldRemoveAttributeEvenIfNotExist() + public function test_should_remove_attribute_even_if_not_exist(): void { $this->session->start(); @@ -56,9 +58,9 @@ public function testShouldRemoveAttributeEvenIfNotExist() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->remove('foo'); } @@ -66,7 +68,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/ReplaceMethodTest.php b/tests/ReplaceMethodTest.php index 72a4c27..f02a505 100644 --- a/tests/ReplaceMethodTest.php +++ b/tests/ReplaceMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class ReplaceMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldAddAttributesIfNotExist() + public function test_should_add_attributes_if_not_exist(): void { $this->session->start(); @@ -47,7 +49,7 @@ public function testShouldAddAttributesIfNotExist() /** * @runInSeparateProcess */ - public function testShouldReplaceAttributesIfExist() + public function test_should_replace_attributes_if_exist(): void { $this->session->start(); @@ -65,9 +67,9 @@ public function testShouldReplaceAttributesIfExist() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->replace(['foo' => 'val']); } @@ -75,7 +77,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/SetIdMethodTest.php b/tests/SetIdMethodTest.php index 002074f..359d629 100644 --- a/tests/SetIdMethodTest.php +++ b/tests/SetIdMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionStartedException; class SetIdMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldSetSessionId() + public function test_should_set_session_id(): void { $this->session->setId('foo'); @@ -42,11 +44,11 @@ public function testShouldSetSessionId() /** * @runInSeparateProcess */ - public function testShouldFailWhenSessionIsStarted() + public function test_should_fail_when_session_is_started(): void { $this->session->start(); - $this->expectException(SessionException::class); + $this->expectException(SessionStartedException::class); $this->session->setId('foo'); } @@ -54,7 +56,7 @@ public function testShouldFailWhenSessionIsStarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/SetMethodTest.php b/tests/SetMethodTest.php index 8d9e448..838cd9f 100644 --- a/tests/SetMethodTest.php +++ b/tests/SetMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionNotStartedException; class SetMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldSetAttributeIfSessionWasStarted() + public function test_should_set_attribute_if_session_was_started(): void { $this->session->start(); @@ -42,7 +44,7 @@ public function testShouldSetAttributeIfSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldSetAttributeIfNativeSessionWasStarted() + public function test_should_set_attribute_if_native_session_was_started(): void { session_start(); @@ -54,9 +56,9 @@ public function testShouldSetAttributeIfNativeSessionWasStarted() /** * @runInSeparateProcess */ - public function testShouldFailIfSessionIsUnstarted() + public function test_should_fail_if_session_is_unstarted(): void { - $this->expectException(SessionException::class); + $this->expectException(SessionNotStartedException::class); $this->session->set('foo', 'bar'); } @@ -64,7 +66,7 @@ public function testShouldFailIfSessionIsUnstarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/SetNameMethodTest.php b/tests/SetNameMethodTest.php index ce67b21..3d9f2b5 100644 --- a/tests/SetNameMethodTest.php +++ b/tests/SetNameMethodTest.php @@ -7,14 +7,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionStartedException; class SetNameMethodTest extends TestCase { @@ -30,7 +32,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldSetSessionName() + public function test_should_set_session_name(): void { $this->session->setName('foo'); @@ -42,11 +44,11 @@ public function testShouldSetSessionName() /** * @runInSeparateProcess */ - public function testShouldFailWhenSessionIsStarted() + public function test_should_fail_when_session_is_started(): void { $this->session->start(); - $this->expectException(SessionException::class); + $this->expectException(SessionStartedException::class); $this->session->setName('foo'); } @@ -54,7 +56,7 @@ public function testShouldFailWhenSessionIsStarted() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade(); diff --git a/tests/StartMethodTest.php b/tests/StartMethodTest.php index 50b248d..e7e53d9 100644 --- a/tests/StartMethodTest.php +++ b/tests/StartMethodTest.php @@ -7,14 +7,18 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. + * + * @phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ namespace Josantonius\Session\Tests; -use Josantonius\Session\Exceptions\SessionException; +use PHPUnit\Framework\TestCase; use Josantonius\Session\Session; +use Josantonius\Session\Exceptions\HeadersSentException; use Josantonius\Session\Facades\Session as SessionFacade; -use PHPUnit\Framework\TestCase; +use Josantonius\Session\Exceptions\SessionStartedException; +use Josantonius\Session\Exceptions\WrongSessionOptionException; class StartMethodTest extends TestCase { @@ -30,7 +34,7 @@ public function setUp(): void /** * @runInSeparateProcess */ - public function testShouldStartSession() + public function test_should_start_session(): void { $this->assertTrue($this->session->start()); @@ -42,7 +46,7 @@ public function testShouldStartSession() /** * @runInSeparateProcess */ - public function testShouldAcceptOptions() + public function test_should_accept_options(): void { $this->session->start(['cookie_lifetime' => 8000]); @@ -52,9 +56,9 @@ public function testShouldAcceptOptions() /** * @runInSeparateProcess */ - public function testShouldFailWithWrongOptions() + public function test_should_fail_with_wrong_options(): void { - $this->expectException(SessionException::class); + $this->expectException(WrongSessionOptionException::class); $this->session->start(['foo' => 'bar']); } @@ -62,18 +66,18 @@ public function testShouldFailWithWrongOptions() /** * @runInSeparateProcess */ - public function testShouldFailWhenSessionIsAlreadyActive() + public function test_should_fail_when_session_is_already_active(): void { $this->session->start(); - $this->expectException(SessionException::class); + $this->expectException(SessionStartedException::class); $this->session->start(); } - public function testShouldFailWhenHeadersSent() + public function test_should_fail_when_headers_sent(): void { - $this->expectException(SessionException::class); + $this->expectException(HeadersSentException::class); $this->session->start(); } @@ -81,7 +85,7 @@ public function testShouldFailWhenHeadersSent() /** * @runInSeparateProcess */ - public function testShouldBeAvailableFromTheFacade() + public function test_should_be_available_from_the_facade(): void { $facade = new SessionFacade();