diff --git a/.editorconfig b/.editorconfig
deleted file mode 100644
index 8b7b10e..0000000
--- a/.editorconfig
+++ /dev/null
@@ -1,18 +0,0 @@
-# This file is for unifying the coding style for different editors and IDEs.
-# More information at http://editorconfig.org
-
-root = true
-
-[*]
-charset = utf-8
-indent_size = 4
-indent_style = space
-end_of_line = lf
-insert_final_newline = true
-trim_trailing_whitespace = true
-
-[Dockerfile]
-indent_size = 2
-
-[*.md]
-trim_trailing_whitespace = false
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 685e7c0..dffe727 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,24 +1,37 @@
name: test
on:
- push:
- pull_request:
+ push:
+ pull_request:
jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - name: Checkout
- uses: actions/checkout@v2
- - name: Pull
- run: docker-compose pull --quiet
- - name: Build
- run: docker-compose build
- - name: Test
- run: docker-compose run lib composer ci
- - name: Upload coverage
- uses: codecov/codecov-action@v1.3.2
- if: success()
- with:
- token: ${{ secrets.CODECOV_TOKEN }}
- file: ./coverage/clover.xml
+ test:
+ runs-on: ${{ matrix.os }}
+
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ php-version:
+ - '7.4'
+ - '8.0'
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+
+ - name: Pull
+ run: docker-compose pull --quiet
+
+ - name: Build
+ run: docker-compose build --build-arg PHPVERSION=${{ matrix.php-version }}
+
+ - name: Test
+ run: docker-compose run lib composer ci
+
+ - name: Upload coverage
+ uses: codecov/codecov-action@v1.3.2
+ if: success()
+ with:
+ file: ./coverage/clover.xml
diff --git a/.php_cs b/.php_cs
index dbabcc6..ba9ca34 100644
--- a/.php_cs
+++ b/.php_cs
@@ -1,6 +1,7 @@
in(__DIR__ . '/src')
+ ->in(__DIR__ . '/tests')
;
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
diff --git a/Dockerfile b/Dockerfile
index 22211cb..4156968 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -15,7 +15,7 @@ WORKDIR /app
COPY composer.json .
COPY composer.lock .
RUN composer validate
-RUN composer install --no-interaction --no-progress --no-suggest
+RUN composer install --no-interaction --no-progress
COPY . .
diff --git a/README.md b/README.md
index b9280ab..4154497 100644
--- a/README.md
+++ b/README.md
@@ -90,7 +90,7 @@ Session::useCurrentRedisDriver($redis);
Session::set('key', 'value');
$value = Session::get('key');
```
-With your own driver implementing SessionHandlerInterface
+With your own driver implementing `SessionHandlerInterface` and/or `SessionUpdateTimestampHandlerInterface`
```php
$driver = new MyCustomDriver();
Session::useCustomDriver($driver);
@@ -147,11 +147,15 @@ When flash data is restore, it will be delete in $_SESSION.
#### Static PHP Session Default Driver
* useDefaultDriver(): void
* useDefaultEncryptionDriver(key: string, [method: string|null = null]): void
+* setLengthSessionID(length: int): void
+* getLengthSessionID(): int
#### Static File Driver
* useFileDriver(): void
* useFileEncryptionDriver(key: string, [method: string|null = null]): void
* setPrefixForFile(prefix: string): void
+* setLengthSessionID(length: int): void
+* getLengthSessionID(): int
#### Static Database Driver
* useNewDatabaseDriver(configuration: \Rancoud\Database\Configurator|array): void
@@ -159,16 +163,56 @@ When flash data is restore, it will be delete in $_SESSION.
* useNewDatabaseEncryptionDriver(configuration: \Rancoud\Database\Configurator|array, key: string, [method: string = null]): void
* useCurrentDatabaseEncryptionDriver(databaseInstance: \Rancoud\Database\Database, key: string, [method: string = null]): void
* setUserIdForDatabase(userId: int): void
+* setLengthSessionID(length: int): void
+* getLengthSessionID(): int
#### Static Redis Driver
* useNewRedisDriver(configuration: array|string): void
* useCurrentRedisDriver(redisInstance: \Predis\Client): void
* useNewRedisEncryptionDriver(configuration: array|string, key: string, [method: string = null]): void
* useCurrentRedisEncryptionDriver(redisInstance: \Predis\Client, key: string, [method: string = null]): void
+* setLengthSessionID(length: int): void
+* getLengthSessionID(): int
#### Static Custom Driver
* useCustomDriver(customDriver: \SessionHandlerInterface): void
+## Session options
+List of session options you can change:
+* save_path
+* name
+* save_handler
+* auto_start
+* gc_probability
+* gc_divisor
+* gc_maxlifetime
+* serialize_handler
+* cookie_lifetime
+* cookie_path
+* cookie_domain
+* cookie_secure
+* cookie_httponly
+* cookie_samesite
+* use_strict_mode
+* use_cookies
+* use_only_cookies
+* referer_check
+* cache_limiter
+* cache_expire
+* use_trans_sid
+* trans_sid_tags
+* trans_sid_hosts
+* sid_length
+* sid_bits_per_character
+* upload_progress.enabled
+* upload_progress.cleanup
+* upload_progress.prefix
+* upload_progress.name
+* upload_progress.freq
+* upload_progress.min_freq
+* lazy_write
+* read_and_close
+
## Driver Informations
### Default
Use SessionHandler
diff --git a/composer.json b/composer.json
index fd5ffe6..0a3e8c2 100644
--- a/composer.json
+++ b/composer.json
@@ -15,9 +15,16 @@
"Rancoud\\Session\\": "src"
}
},
+ "autoload-dev": {
+ "psr-4": {
+ "tests\\": "tests"
+ }
+ },
"require": {
"php": ">=7.4.0",
- "ext-openssl": ">=7.4.0"
+ "ext-openssl": "*",
+ "ext-session": "*",
+ "ext-mbstring": "*"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.16",
@@ -36,7 +43,7 @@
"php-cs-fixer fix"
],
"test": [
- "phpdbg -qrr vendor/bin/phpunit --colors --coverage-text --coverage-clover ./coverage/clover.xml"
+ "phpdbg -qrr vendor/bin/phpunit --colors --coverage-html ./coverage --coverage-text --coverage-clover ./coverage/clover.xml"
]
}
}
diff --git a/composer.lock b/composer.lock
index 9c62903..54a9840 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "6a3b3bd182736d3909d92f1c896bf9df",
+ "content-hash": "675c339477b125cdcf72c5029e89f4cb",
"packages": [],
"packages-dev": [
{
@@ -982,16 +982,16 @@
},
{
"name": "phpunit/php-code-coverage",
- "version": "9.2.5",
+ "version": "9.2.6",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
- "reference": "f3e026641cc91909d421802dd3ac7827ebfd97e1"
+ "reference": "f6293e1b30a2354e8428e004689671b83871edde"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f3e026641cc91909d421802dd3ac7827ebfd97e1",
- "reference": "f3e026641cc91909d421802dd3ac7827ebfd97e1",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/f6293e1b30a2354e8428e004689671b83871edde",
+ "reference": "f6293e1b30a2354e8428e004689671b83871edde",
"shasum": ""
},
"require": {
@@ -1047,7 +1047,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.5"
+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.6"
},
"funding": [
{
@@ -1055,7 +1055,7 @@
"type": "github"
}
],
- "time": "2020-11-28T06:44:49+00:00"
+ "time": "2021-03-28T07:26:59+00:00"
},
{
"name": "phpunit/php-file-iterator",
@@ -1617,20 +1617,20 @@
},
{
"name": "rancoud/database",
- "version": "6.0.3",
+ "version": "6.0.4",
"source": {
"type": "git",
"url": "https://github.com/rancoud/Database.git",
- "reference": "71d1563d3fed2db02db3544fbcc1b820c3e9d33e"
+ "reference": "80b46a525d910472bc9e75e82f32a07cd5a284d2"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/rancoud/Database/zipball/71d1563d3fed2db02db3544fbcc1b820c3e9d33e",
- "reference": "71d1563d3fed2db02db3544fbcc1b820c3e9d33e",
+ "url": "https://api.github.com/repos/rancoud/Database/zipball/80b46a525d910472bc9e75e82f32a07cd5a284d2",
+ "reference": "80b46a525d910472bc9e75e82f32a07cd5a284d2",
"shasum": ""
},
"require": {
- "ext-pdo": ">=7.4.0",
+ "ext-pdo": "*",
"php": ">=7.4.0"
},
"require-dev": {
@@ -1638,6 +1638,11 @@
"phpunit/phpunit": "^9.1",
"squizlabs/php_codesniffer": "^3.5"
},
+ "suggest": {
+ "ext-pdo_mysql": "Needed to connect MySQL",
+ "ext-pdo_pgsql": "Needed to connect PostgreSQL",
+ "ext-pdo_sqlite": "Needed to connect SQLite"
+ },
"type": "library",
"autoload": {
"psr-4": {
@@ -1657,9 +1662,9 @@
"description": "Database package",
"support": {
"issues": "https://github.com/rancoud/Database/issues",
- "source": "https://github.com/rancoud/Database/tree/6.0.3"
+ "source": "https://github.com/rancoud/Database/tree/6.0.4"
},
- "time": "2021-02-07T02:04:56+00:00"
+ "time": "2021-04-18T13:21:38+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -4233,7 +4238,9 @@
"prefer-lowest": false,
"platform": {
"php": ">=7.4.0",
- "ext-openssl": ">=7.4.0"
+ "ext-openssl": "*",
+ "ext-session": "*",
+ "ext-mbstring": "*"
},
"platform-dev": [],
"plugin-api-version": "2.0.0"
diff --git a/phpcs.xml b/phpcs.xml
index 747b08f..ffacca2 100644
--- a/phpcs.xml
+++ b/phpcs.xml
@@ -6,6 +6,7 @@
src
+ tests
diff --git a/src/ArrayManager.php b/src/ArrayManager.php
index 03b28e0..68d277c 100644
--- a/src/ArrayManager.php
+++ b/src/ArrayManager.php
@@ -9,18 +9,19 @@
*/
trait ArrayManager
{
- /** @var array */
protected static array $flashData = [];
+ /** @throws SessionException */
abstract protected static function startSessionIfNotHasStarted();
+ /** @throws SessionException */
abstract protected static function startSessionIfNotHasStartedForceWrite();
/**
* @param string $key
* @param mixed $value
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function set(string $key, $value): void
{
@@ -32,7 +33,7 @@ public static function set(string $key, $value): void
/**
* @param string $key
*
- * @throws \Exception
+ * @throws SessionException
*
* @return bool
*/
@@ -47,7 +48,7 @@ public static function has(string $key): bool
* @param string $key
* @param mixed $value
*
- * @throws \Exception
+ * @throws SessionException
*
* @return bool
*/
@@ -61,7 +62,7 @@ public static function hasKeyAndValue(string $key, $value): bool
/**
* @param string $key
*
- * @throws \Exception
+ * @throws SessionException
*
* @return mixed
*/
@@ -75,7 +76,7 @@ public static function get(string $key)
/**
* @param string $key
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function remove(string $key): void
{
@@ -87,7 +88,7 @@ public static function remove(string $key): void
}
/**
- * @throws \Exception
+ * @throws SessionException
*
* @return array
*/
@@ -101,7 +102,7 @@ public static function getAll(): array
/**
* @param string $key
*
- * @throws \Exception
+ * @throws SessionException
*
* @return mixed
*/
@@ -118,8 +119,6 @@ public static function getAndRemove(string $key)
/**
* @param string $key
* @param mixed $value
- *
- * @throws \Exception
*/
public static function setFlash(string $key, $value): void
{
@@ -150,8 +149,6 @@ public static function hasFlashKeyAndValue(string $key, $value): bool
/**
* @param string $key
*
- * @throws \Exception
- *
* @return mixed
*/
public static function getFlash(string $key)
@@ -161,8 +158,6 @@ public static function getFlash(string $key)
/**
* @param string $key
- *
- * @throws \Exception
*/
public static function removeFlash(string $key): void
{
@@ -173,6 +168,8 @@ public static function removeFlash(string $key): void
/**
* @param array $keys
+ *
+ * @throws SessionException
*/
public static function keepFlash(array $keys = []): void
{
diff --git a/src/Database.php b/src/Database.php
index da44307..f1cab27 100644
--- a/src/Database.php
+++ b/src/Database.php
@@ -7,7 +7,7 @@
namespace Rancoud\Session;
use Rancoud\Database\Configurator;
-use Rancoud\Database\Database as Db;
+use Rancoud\Database\Database as DB;
use Rancoud\Database\DatabaseException;
use SessionHandlerInterface;
use SessionUpdateTimestampHandlerInterface;
@@ -17,36 +17,40 @@
*/
class Database implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface
{
- /** @var Db */
- protected Db $db;
+ protected DB $db;
- /** @var int|null */
protected ?int $userId = null;
+ protected int $lengthSessionID = 127;
+
/**
* @param Configurator|array $configuration
*
- * @throws DatabaseException
+ * @throws SessionException
*/
public function setNewDatabase($configuration): void
{
- if ($configuration instanceof Configurator) {
- $this->db = new Db($configuration);
- } else {
- $this->db = new Db(new Configurator($configuration));
+ try {
+ if ($configuration instanceof Configurator) {
+ $this->db = new DB($configuration);
+ } else {
+ $this->db = new DB(new Configurator($configuration));
+ }
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not set database: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
}
}
/**
- * @param Db $database
+ * @param DB $database
*/
- public function setCurrentDatabase($database): void
+ public function setCurrentDatabase(DB $database): void
{
$this->db = $database;
}
/**
- * @param int $userId
+ * @param int|null $userId
*/
public function setUserId(?int $userId): void
{
@@ -54,12 +58,31 @@ public function setUserId(?int $userId): void
}
/**
- * @param string $savePath
- * @param string $sessionName
+ * @param int $length
+ *
+ * @throws SessionException
+ */
+ public function setLengthSessionID(int $length): void
+ {
+ if ($length < 32) {
+ throw new SessionException('could not set length session ID below 32');
+ }
+
+ $this->lengthSessionID = $length;
+ }
+
+ public function getLengthSessionID(): int
+ {
+ return $this->lengthSessionID;
+ }
+
+ /**
+ * @param string $path
+ * @param string $name
*
* @return bool
*/
- public function open($savePath, $sessionName): bool
+ public function open($path, $name): bool
{
return true;
}
@@ -73,130 +96,158 @@ public function close(): bool
}
/**
- * @param string $sessionId
+ * @param string $id
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $sql = 'SELECT content FROM sessions WHERE id = :id';
- $params = ['id' => $sessionId];
+ try {
+ $sql = 'SELECT content FROM sessions WHERE id = :id';
+ $params = ['id' => $id];
- return (string) $this->db->selectVar($sql, $params);
+ return (string) $this->db->selectVar($sql, $params);
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not read session: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ }
}
/**
- * @param string $sessionId
+ * @param string $id
* @param string $data
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
- $sql = 'REPLACE INTO sessions VALUES(:id, :id_user, NOW(), :content)';
- $params = ['id' => $sessionId, 'id_user' => $this->userId, 'content' => $data];
+ try {
+ $sql = 'REPLACE INTO sessions VALUES(:id, :id_user, UTC_TIMESTAMP(), :content)';
+ $params = ['id' => $id, 'id_user' => $this->userId, 'content' => $data];
- $this->db->exec($sql, $params);
+ $this->db->exec($sql, $params);
- return true;
+ return true;
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not update session: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ }
}
/**
- * @param string $sessionId
+ * @param string $id
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return bool
*/
- public function destroy($sessionId): bool
+ public function destroy($id): bool
{
- $sql = 'DELETE FROM sessions WHERE id = :id';
- $params = ['id' => $sessionId];
- $this->db->delete($sql, $params);
-
- return true;
+ try {
+ $sql = 'DELETE FROM sessions WHERE id = :id';
+ $params = ['id' => $id];
+ $this->db->delete($sql, $params);
+
+ return true;
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not delete session: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ }
}
/**
- * @param int $lifetime
+ * @param int $max_lifetime
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return bool
*/
- public function gc($lifetime): bool
+ public function gc($max_lifetime): bool
{
- $sql = 'DELETE FROM sessions WHERE DATE_ADD(last_access, INTERVAL :seconds second) < NOW()';
- $params = ['seconds' => $lifetime];
- $this->db->delete($sql, $params);
-
- return true;
+ try {
+ $sql = 'DELETE FROM sessions WHERE DATE_ADD(last_access, INTERVAL :seconds second) < UTC_TIMESTAMP()';
+ $params = ['seconds' => $max_lifetime];
+ $this->db->delete($sql, $params);
+
+ return true;
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not clean old sessions: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ }
}
/**
* Checks format and id exists, if not session_id will be regenerate.
*
- * @param string $key
+ * @param string $id
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return bool
*/
- public function validateId($key): bool
+ public function validateId($id): bool
{
- if (\preg_match('/^[a-zA-Z0-9-]{127}+$/', $key) !== 1) {
- return false;
+ try {
+ if (\preg_match('/^[a-zA-Z0-9-]{' . $this->lengthSessionID . '}+$/', $id) !== 1) {
+ return false;
+ }
+
+ $sql = 'SELECT COUNT(id) FROM sessions WHERE id=:id';
+ $params = ['id' => $id];
+ $count = $this->db->count($sql, $params);
+
+ return $count === 1;
+ } catch (DatabaseException $e) {
+ throw new SessionException('could not validate id: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
}
-
- $sql = 'SELECT COUNT(id) FROM sessions WHERE id=:id';
- $params = ['id' => $key];
- $count = $this->db->count($sql, $params);
-
- return $count === 1;
}
/**
* Updates the timestamp of a session when its data didn't change.
*
- * @param string $sessionId
- * @param string $sessionData
+ * @param string $id
+ * @param string $data
*
- * @throws DatabaseException
+ * @throws SessionException
*
* @return bool
*/
- public function updateTimestamp($sessionId, $sessionData): bool
+ public function updateTimestamp($id, $data): bool
{
- return $this->write($sessionId, $sessionData);
+ return $this->write($id, $data);
}
/**
- * @throws \Exception
- * @throws DatabaseException
+ * @throws SessionException
*
* @return string
+ * @noinspection PhpMethodNamingConventionInspection
*/
public function create_sid(): string
{
- $string = '';
- $caracters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
-
- $countCaracters = 62;
- for ($i = 0; $i < 127; ++$i) {
- $string .= $caracters[\random_int(0, $countCaracters)];
+ try {
+ $string = '';
+ $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
+
+ $countCharacters = 62;
+ for ($i = 0; $i < $this->lengthSessionID; ++$i) {
+ $string .= $characters[\random_int(0, $countCharacters)];
+ }
+
+ $sql = 'SELECT COUNT(id) FROM sessions WHERE id=:id';
+ $params = ['id' => $string];
+ $count = $this->db->count($sql, $params);
+ if ($count !== 0) {
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the function
+ */
+ return $this->create_sid();
+ // @codeCoverageIgnoreEnd
+ }
+
+ return $string;
+ } catch (\Exception $e) {
+ throw new SessionException('could not create sid: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
}
-
- $sql = 'SELECT COUNT(id) FROM sessions WHERE id=:id';
- $params = ['id' => $string];
- $count = $this->db->count($sql, $params);
- if ($count !== 0) {
- return $this->create_sid();
- }
-
- return $string;
}
}
diff --git a/src/DatabaseEncryption.php b/src/DatabaseEncryption.php
index a7c2655..411f304 100644
--- a/src/DatabaseEncryption.php
+++ b/src/DatabaseEncryption.php
@@ -4,8 +4,6 @@
namespace Rancoud\Session;
-use Rancoud\Database\DatabaseException;
-
/**
* Class DatabaseEncryption.
*/
@@ -14,33 +12,31 @@ class DatabaseEncryption extends Database
use Encryption;
/**
- * @param string $sessionId
+ * @param string $id
*
* @throws SessionException
- * @throws DatabaseException
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $encryptedData = parent::read($sessionId);
+ $encryptedData = parent::read($id);
return $this->decrypt($encryptedData);
}
/**
- * @param string $sessionId
+ * @param string $id
* @param string $data
*
- * @throws DatabaseException
* @throws SessionException
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
$cryptedData = $this->encrypt($data);
- return parent::write($sessionId, $cryptedData);
+ return parent::write($id, $cryptedData);
}
}
diff --git a/src/DefaultEncryption.php b/src/DefaultEncryption.php
index 98cd168..75b9cc2 100644
--- a/src/DefaultEncryption.php
+++ b/src/DefaultEncryption.php
@@ -14,31 +14,31 @@ class DefaultEncryption extends SessionHandler
use Encryption;
/**
- * @param string $sessionId
+ * @param string $id
*
* @throws SessionException
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $encryptedData = parent::read($sessionId);
+ $encryptedData = parent::read($id);
return $this->decrypt($encryptedData);
}
/**
- * @param string $sessionId
+ * @param string $id
* @param string $data
*
* @throws SessionException
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
$cryptedData = $this->encrypt($data);
- return parent::write($sessionId, $cryptedData);
+ return parent::write($id, $cryptedData);
}
}
diff --git a/src/DriverManager.php b/src/DriverManager.php
index c90ca7a..9704a23 100644
--- a/src/DriverManager.php
+++ b/src/DriverManager.php
@@ -4,6 +4,9 @@
namespace Rancoud\Session;
+use Predis\Client as PredisClient;
+use Rancoud\Database\Configurator;
+use Rancoud\Database\Database as DB;
use SessionHandler;
use SessionHandlerInterface;
@@ -12,15 +15,15 @@
*/
abstract class DriverManager
{
- /** @var SessionHandlerInterface */
protected static ?SessionHandlerInterface $driver = null;
+ /** @throws SessionException */
abstract protected static function throwExceptionIfHasStarted();
abstract protected static function getLifetimeForRedis();
/**
- * @throws \Exception
+ * @throws SessionException
*/
protected static function configureDriver(): void
{
@@ -30,7 +33,7 @@ protected static function configureDriver(): void
}
/**
- * @throws \Exception
+ * @throws SessionException
*/
public static function useDefaultDriver(): void
{
@@ -43,7 +46,7 @@ public static function useDefaultDriver(): void
* @param string $key
* @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useDefaultEncryptionDriver(string $key, string $method = null): void
{
@@ -56,7 +59,7 @@ public static function useDefaultEncryptionDriver(string $key, string $method =
}
/**
- * @throws \Exception
+ * @throws SessionException
*/
public static function useFileDriver(): void
{
@@ -69,7 +72,7 @@ public static function useFileDriver(): void
* @param string $key
* @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useFileEncryptionDriver(string $key, string $method = null): void
{
@@ -82,9 +85,9 @@ public static function useFileEncryptionDriver(string $key, string $method = nul
}
/**
- * @param \Rancoud\Database\Configurator|array $configuration
+ * @param Configurator|array $configuration
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useNewDatabaseDriver($configuration): void
{
@@ -97,11 +100,11 @@ public static function useNewDatabaseDriver($configuration): void
}
/**
- * @param \Rancoud\Database\Database $databaseInstance
+ * @param DB $databaseInstance
*
- * @throws \Exception
+ * @throws SessionException
*/
- public static function useCurrentDatabaseDriver($databaseInstance): void
+ public static function useCurrentDatabaseDriver(DB $databaseInstance): void
{
static::throwExceptionIfHasStarted();
@@ -112,13 +115,13 @@ public static function useCurrentDatabaseDriver($databaseInstance): void
}
/**
- * @param \Rancoud\Database\Configurator|array $configuration
- * @param string $key
- * @param string $method
+ * @param Configurator|array $configuration
+ * @param string $key
+ * @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
- public static function useNewDatabaseEncryptionDriver($configuration, string $key, string $method = null): void
+ public static function useNewDatabaseEncryptionDriver($configuration, string $key, ?string $method = null): void
{
static::throwExceptionIfHasStarted();
@@ -130,13 +133,13 @@ public static function useNewDatabaseEncryptionDriver($configuration, string $ke
}
/**
- * @param \Rancoud\Database\Database $databaseInstance
- * @param string $key
- * @param string $method
+ * @param DB $databaseInstance
+ * @param string $key
+ * @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
- public static function useCurrentDatabaseEncryptionDriver($databaseInstance, string $key, string $method = null): void
+ public static function useCurrentDatabaseEncryptionDriver(DB $databaseInstance, string $key, ?string $method = null): void
{
static::throwExceptionIfHasStarted();
@@ -150,7 +153,7 @@ public static function useCurrentDatabaseEncryptionDriver($databaseInstance, str
/**
* @param array|string $configuration
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useNewRedisDriver($configuration): void
{
@@ -164,11 +167,11 @@ public static function useNewRedisDriver($configuration): void
}
/**
- * @param \Predis\Client $redisInstance
+ * @param PredisClient $redisInstance
*
- * @throws \Exception
+ * @throws SessionException
*/
- public static function useCurrentRedisDriver($redisInstance): void
+ public static function useCurrentRedisDriver(PredisClient $redisInstance): void
{
static::throwExceptionIfHasStarted();
@@ -182,9 +185,9 @@ public static function useCurrentRedisDriver($redisInstance): void
/**
* @param array|string $configuration
* @param string $key
- * @param string $method
+ * @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useNewRedisEncryptionDriver($configuration, string $key, string $method = null): void
{
@@ -199,13 +202,13 @@ public static function useNewRedisEncryptionDriver($configuration, string $key,
}
/**
- * @param \Predis\Client $redisInstance
- * @param string $key
- * @param string $method
+ * @param PredisClient $redisInstance
+ * @param string $key
+ * @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
- public static function useCurrentRedisEncryptionDriver($redisInstance, string $key, string $method = null): void
+ public static function useCurrentRedisEncryptionDriver(PredisClient $redisInstance, string $key, string $method = null): void
{
static::throwExceptionIfHasStarted();
@@ -218,13 +221,13 @@ public static function useCurrentRedisEncryptionDriver($redisInstance, string $k
}
/**
- * @param Encryption $driver
- * @param $key
- * @param $method
+ * @param Encryption $driver (use Encryption trait)
+ * @param string $key
+ * @param string|null $method
*
- * @throws \Exception
+ * @throws SessionException
*/
- private static function setKeyAndMethod($driver, $key, $method): void
+ private static function setKeyAndMethod($driver, string $key, ?string $method): void
{
$driver->setKey($key);
if ($method !== null) {
@@ -235,7 +238,7 @@ private static function setKeyAndMethod($driver, $key, $method): void
/**
* @param SessionHandlerInterface $customDriver
*
- * @throws \Exception
+ * @throws SessionException
*/
public static function useCustomDriver(SessionHandlerInterface $customDriver): void
{
@@ -258,6 +261,7 @@ public static function getDriver(): SessionHandlerInterface
public static function setUserIdForDatabase(int $userId): void
{
if (\method_exists(static::$driver, 'setUserId')) {
+ /** @noinspection PhpPossiblePolymorphicInvocationInspection */
static::$driver->setUserId($userId);
}
}
@@ -268,6 +272,7 @@ public static function setUserIdForDatabase(int $userId): void
public static function setPrefixForFile(string $prefix): void
{
if (\method_exists(static::$driver, 'setPrefix')) {
+ /** @noinspection PhpPossiblePolymorphicInvocationInspection */
static::$driver->setPrefix($prefix);
}
}
diff --git a/src/Encryption.php b/src/Encryption.php
index 86b9ca8..f3bee5d 100644
--- a/src/Encryption.php
+++ b/src/Encryption.php
@@ -9,11 +9,9 @@
*/
trait Encryption
{
- /** @var string */
- protected $key;
+ protected ?string $key = null;
- /** @var string */
- protected $method = 'aes-256-cbc';
+ protected string $method = 'aes-256-cbc';
/**
* @param string $key
@@ -31,7 +29,7 @@ public function setKey(string $key): void
public function setMethod(string $method): void
{
if (!\in_array($method, $this->getAvailableMethods(), true)) {
- throw new SessionException(\sprintf('Method unknowed: %s', $method));
+ throw new SessionException(\sprintf('Unknown method: %s', $method));
}
$this->method = $method;
@@ -46,54 +44,43 @@ public function getAvailableMethods(): array
$ciphersAndAliases = \openssl_get_cipher_methods(true);
$cipherAliases = \array_diff($ciphersAndAliases, $ciphers);
- $ciphers = \array_filter($ciphers, function ($n) {
- return \mb_stripos($n, 'ecb') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, 'des') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, 'rc2') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, 'rc4') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, 'md5') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, '-ocb') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, '-ccm') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, '-gcm') === false;
- });
- $ciphers = \array_filter($ciphers, function ($c) {
- return \mb_stripos($c, '-wrap') === false;
+ $ciphers = \array_filter($ciphers, static function ($n) {
+ $excludeMethods = [
+ 'ecb', 'des', 'rc2', 'rc4', 'md5',
+ '-ocb', '-ccm', '-gcm', '-wrap'
+ ];
+ foreach ($excludeMethods as $excludeMethod) {
+ if (\mb_stripos($n, $excludeMethod) !== false) {
+ return false;
+ }
+ }
+
+ return true;
});
- $cipherAliases = \array_filter($cipherAliases, function ($c) {
- return \mb_stripos($c, 'des') === false;
- });
- $cipherAliases = \array_filter($cipherAliases, function ($c) {
- return \mb_stripos($c, 'rc2') === false;
- });
- $cipherAliases = \array_filter($cipherAliases, function ($c) {
- return \mb_stripos($c, '-wrap') === false;
+ $cipherAliases = \array_filter($cipherAliases, static function ($c) {
+ $excludeMethods = [
+ 'des', 'rc2', '-wrap'
+ ];
+ foreach ($excludeMethods as $excludeMethod) {
+ if (\mb_stripos($c, $excludeMethod) !== false) {
+ return false;
+ }
+ }
+
+ return true;
});
$methods = \array_merge($ciphers, $cipherAliases);
- $methods = \array_filter($methods, function ($c) {
- $forbiddenMethods = ['AES-128-CBC-HMAC-SHA1', 'AES-256-CBC-HMAC-SHA1',
- 'aes-128-cbc-hmac-sha1', 'aes-256-cbc-hmac-sha1'];
+ return \array_filter($methods, static function ($c) {
+ $forbiddenMethods = [
+ 'AES-128-CBC-HMAC-SHA1', 'AES-256-CBC-HMAC-SHA1',
+ 'aes-128-cbc-hmac-sha1', 'aes-256-cbc-hmac-sha1'
+ ];
return !\in_array($c, $forbiddenMethods, true);
});
-
- return $methods;
}
/**
@@ -101,9 +88,9 @@ public function getAvailableMethods(): array
*
* @throws SessionException
*
- * @return string|bool
+ * @return string
*/
- public function decrypt(string $data)
+ public function decrypt(string $data): string
{
$this->throwExceptionIfKeyEmpty();
@@ -111,9 +98,18 @@ public function decrypt(string $data)
return '';
}
- list($encrypted_data, $iv) = \explode('::', \base64_decode($data, true), 2);
+ [$encryptedData, $iv] = \explode('::', \base64_decode($data, true), 2);
- return \openssl_decrypt($encrypted_data, $this->method, $this->key, 0, $iv);
+ $dataDecrypted = \openssl_decrypt($encryptedData, $this->method, $this->key, 0, $iv);
+ if ($dataDecrypted === false) {
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the function
+ */
+ throw new SessionException('Could not decrypt with openssl_decrypt');
+ // @codeCoverageIgnoreEnd
+ }
+
+ return $dataDecrypted;
}
/**
@@ -127,11 +123,19 @@ public function encrypt(string $data): string
{
$this->throwExceptionIfKeyEmpty();
- $iv = \openssl_random_pseudo_bytes(\openssl_cipher_iv_length($this->method));
+ /** @noinspection CryptographicallySecureRandomnessInspection */
+ $iv = \openssl_random_pseudo_bytes(\openssl_cipher_iv_length($this->method), $cstrong);
+ if ($iv === false || $cstrong === false) {
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the function
+ */
+ throw new SessionException('IV generation failed');
+ // @codeCoverageIgnoreEnd
+ }
+
$encrypted = \openssl_encrypt($data, $this->method, $this->key, 0, $iv);
- $data = \base64_encode($encrypted . '::' . $iv);
- return $data;
+ return \base64_encode($encrypted . '::' . $iv);
}
/**
diff --git a/src/File.php b/src/File.php
index 0b1dd80..968a6e9 100644
--- a/src/File.php
+++ b/src/File.php
@@ -12,12 +12,12 @@
*/
class File implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface
{
- /** @var string|null */
protected ?string $savePath = null;
- /** @var string */
protected string $prefix = 'sess_';
+ protected int $lengthSessionID = 127;
+
/**
* @param string $prefix
*/
@@ -27,17 +27,42 @@ public function setPrefix(string $prefix): void
}
/**
- * @param string $savePath
- * @param string $sessionName
+ * @param int $length
+ *
+ * @throws SessionException
+ */
+ public function setLengthSessionID(int $length): void
+ {
+ if ($length < 32) {
+ throw new SessionException('could not set length session ID below 32');
+ }
+
+ $this->lengthSessionID = $length;
+ }
+
+ public function getLengthSessionID(): int
+ {
+ return $this->lengthSessionID;
+ }
+
+ /**
+ * @param string $path
+ * @param string $name
+ *
+ * @throws SessionException
*
* @return bool
*/
- public function open($savePath, $sessionName): bool
+ public function open($path, $name): bool
{
- $this->savePath = $savePath;
+ $this->savePath = $path;
if (!\is_dir($this->savePath) && !\mkdir($this->savePath, 0750) && !\is_dir($this->savePath)) {
- throw new \RuntimeException(\sprintf('Directory "%s" was not created', $this->savePath));
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the filesystem
+ */
+ throw new SessionException(\sprintf('Directory "%s" was not created', $this->savePath));
+ // @codeCoverageIgnoreEnd
}
return true;
@@ -52,14 +77,14 @@ public function close(): bool
}
/**
- * @param string $sessionId
+ * @param string $id
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $sessionId;
- if (\file_exists($filename)) {
+ $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $id;
+ if (\file_exists($filename) && \is_file($filename)) {
return (string) \file_get_contents($filename);
}
@@ -67,27 +92,27 @@ public function read($sessionId): string
}
/**
- * @param string $sessionId
+ * @param string $id
* @param string $data
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
- $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $sessionId;
+ $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $id;
- return \file_put_contents($filename, $data) === false ? false : true;
+ return !(\file_put_contents($filename, $data) === false);
}
/**
- * @param string $sessionId
+ * @param string $id
*
* @return bool
*/
- public function destroy($sessionId): bool
+ public function destroy($id): bool
{
- $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $sessionId;
- if (\file_exists($filename)) {
+ $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $id;
+ if (\file_exists($filename) && \is_file($filename)) {
\unlink($filename);
}
@@ -95,15 +120,15 @@ public function destroy($sessionId): bool
}
/**
- * @param int $lifetime
+ * @param int $max_lifetime
*
* @return bool
*/
- public function gc($lifetime): bool
+ public function gc($max_lifetime): bool
{
$pattern = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . '*';
foreach (\glob($pattern) as $file) {
- if (\filemtime($file) + $lifetime < \time() && \file_exists($file)) {
+ if (\file_exists($file) && \is_file($file) && \filemtime($file) + $max_lifetime < \time()) {
\unlink($file);
}
}
@@ -114,17 +139,17 @@ public function gc($lifetime): bool
/**
* Checks format and id exists, if not session_id will be regenerate.
*
- * @param string $key
+ * @param string $id
*
* @return bool
*/
- public function validateId($key): bool
+ public function validateId($id): bool
{
- if (\preg_match('/^[a-zA-Z0-9-]{127}+$/', $key) !== 1) {
+ if (\preg_match('/^[a-zA-Z0-9-]{' . $this->lengthSessionID . '}+$/', $id) !== 1) {
return false;
}
- $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $key;
+ $filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $id;
return \file_exists($filename);
}
@@ -132,34 +157,48 @@ public function validateId($key): bool
/**
* Updates the timestamp of a session when its data didn't change.
*
- * @param string $sessionId
- * @param string $sessionData
+ * @param string $id
+ * @param string $data
*
* @return bool
*/
- public function updateTimestamp($sessionId, $sessionData): bool
+ public function updateTimestamp($id, $data): bool
{
- return $this->write($sessionId, $sessionData);
+ return $this->write($id, $data);
}
/**
- * @throws \Exception
+ * @throws SessionException
*
* @return string
+ * @noinspection PhpMethodNamingConventionInspection
*/
public function create_sid(): string
{
$string = '';
- $caracters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
+ $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
- $countCaracters = 62;
- for ($i = 0; $i < 127; ++$i) {
- $string .= $caracters[\random_int(0, $countCaracters)];
+ try {
+ $countCharacters = 62;
+ for ($i = 0; $i < $this->lengthSessionID; ++$i) {
+ $string .= $characters[\random_int(0, $countCharacters)];
+ }
+ // @codeCoverageIgnoreStart
+ } catch (\Exception $e) {
+ /* If an appropriate source of randomness cannot be found, an Exception will be thrown.
+ * The list of randomness: https://www.php.net/manual/en/function.random-int.php
+ */
+ throw new SessionException('could not create sid: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ // @codeCoverageIgnoreEnd
}
$filename = $this->savePath . \DIRECTORY_SEPARATOR . $this->prefix . $string;
if (\file_exists($filename)) {
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the filesystem
+ */
return $this->create_sid();
+ // @codeCoverageIgnoreEnd
}
return $string;
diff --git a/src/FileEncryption.php b/src/FileEncryption.php
index cabbd93..6f0c195 100644
--- a/src/FileEncryption.php
+++ b/src/FileEncryption.php
@@ -12,31 +12,31 @@ class FileEncryption extends File
use Encryption;
/**
- * @param $sessionId
+ * @param string $id
*
* @throws SessionException
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $encryptedData = parent::read($sessionId);
+ $encryptedData = parent::read($id);
return $this->decrypt($encryptedData);
}
/**
- * @param $sessionId
- * @param $data
+ * @param string $id
+ * @param string $data
*
* @throws SessionException
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
$cryptedData = $this->encrypt($data);
- return parent::write($sessionId, $cryptedData);
+ return parent::write($id, $cryptedData);
}
}
diff --git a/src/Redis.php b/src/Redis.php
index 13f3d6f..3c06e5a 100644
--- a/src/Redis.php
+++ b/src/Redis.php
@@ -13,12 +13,12 @@
*/
class Redis implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface
{
- /** @var Predis */
protected Predis $redis;
- /** @var int */
protected int $lifetime = 1440;
+ protected int $lengthSessionID = 127;
+
/**
* @param string|array $configuration
*/
@@ -30,7 +30,7 @@ public function setNewRedis($configuration): void
/**
* @param Predis $redis
*/
- public function setCurrentRedis($redis): void
+ public function setCurrentRedis(Predis $redis): void
{
$this->redis = $redis;
}
@@ -44,12 +44,31 @@ public function setLifetime(int $lifetime): void
}
/**
- * @param string $savePath
- * @param string $sessionName
+ * @param int $length
+ *
+ * @throws SessionException
+ */
+ public function setLengthSessionID(int $length): void
+ {
+ if ($length < 32) {
+ throw new SessionException('could not set length session ID below 32');
+ }
+
+ $this->lengthSessionID = $length;
+ }
+
+ public function getLengthSessionID(): int
+ {
+ return $this->lengthSessionID;
+ }
+
+ /**
+ * @param string $path
+ * @param string $name
*
* @return bool
*/
- public function open($savePath, $sessionName): bool
+ public function open($path, $name): bool
{
return true;
}
@@ -63,47 +82,47 @@ public function close(): bool
}
/**
- * @param string $sessionId
+ * @param string $id
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- return (string) $this->redis->get($sessionId);
+ return (string) $this->redis->get($id);
}
/**
- * @param string $sessionId
+ * @param string $id
* @param string $data
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
- $this->redis->set($sessionId, $data);
- $this->redis->expireat($sessionId, \time() + $this->lifetime);
+ $this->redis->set($id, $data);
+ $this->redis->expireat($id, \time() + $this->lifetime);
return true;
}
/**
- * @param string $sessionId
+ * @param string $id
*
* @return bool
*/
- public function destroy($sessionId): bool
+ public function destroy($id): bool
{
- $this->redis->del([$sessionId]);
+ $this->redis->del([$id]);
return true;
}
/**
- * @param int $lifetime
+ * @param int $max_lifetime
*
* @return bool
*/
- public function gc($lifetime): bool
+ public function gc($max_lifetime): bool
{
return true;
}
@@ -111,17 +130,17 @@ public function gc($lifetime): bool
/**
* Checks format and id exists, if not session_id will be regenerate.
*
- * @param string $key
+ * @param string $id
*
* @return bool
*/
- public function validateId($key): bool
+ public function validateId($id): bool
{
- if (\preg_match('/^[a-zA-Z0-9-]{127}+$/', $key) !== 1) {
+ if (\preg_match('/^[a-zA-Z0-9-]{' . $this->lengthSessionID . '}+$/', $id) !== 1) {
return false;
}
- $exist = $this->redis->exists($key);
+ $exist = $this->redis->exists($id);
return $exist === 1;
}
@@ -129,34 +148,48 @@ public function validateId($key): bool
/**
* Updates the timestamp of a session when its data didn't change.
*
- * @param string $sessionId
- * @param string $sessionData
+ * @param string $id
+ * @param string $data
*
* @return bool
*/
- public function updateTimestamp($sessionId, $sessionData): bool
+ public function updateTimestamp($id, $data): bool
{
- return $this->write($sessionId, $sessionData);
+ return $this->write($id, $data);
}
/**
- * @throws \Exception
+ * @throws SessionException
*
* @return string
+ * @noinspection PhpMethodNamingConventionInspection
*/
public function create_sid(): string
{
$string = '';
- $caracters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
-
- $countCaracters = 62;
- for ($i = 0; $i < 127; ++$i) {
- $string .= $caracters[\random_int(0, $countCaracters)];
+ $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-';
+
+ try {
+ $countCharacters = 62;
+ for ($i = 0; $i < $this->lengthSessionID; ++$i) {
+ $string .= $characters[\random_int(0, $countCharacters)];
+ }
+ // @codeCoverageIgnoreStart
+ } catch (\Exception $e) {
+ /* If an appropriate source of randomness cannot be found, an Exception will be thrown.
+ * The list of randomness: https://www.php.net/manual/en/function.random-int.php
+ */
+ throw new SessionException('could not create sid: ' . $e->getMessage(), $e->getCode(), $e->getPrevious());
+ // @codeCoverageIgnoreEnd
}
$exist = $this->redis->exists($string);
if ($exist !== 0) {
+ // @codeCoverageIgnoreStart
+ /* Could not reach this statement without mocking the function
+ */
return $this->create_sid();
+ // @codeCoverageIgnoreEnd
}
return $string;
diff --git a/src/RedisEncryption.php b/src/RedisEncryption.php
index cd146ec..05b27bf 100644
--- a/src/RedisEncryption.php
+++ b/src/RedisEncryption.php
@@ -12,31 +12,31 @@ class RedisEncryption extends Redis
use Encryption;
/**
- * @param $sessionId
+ * @param string $id
*
* @throws SessionException
*
* @return string
*/
- public function read($sessionId): string
+ public function read($id): string
{
- $encryptedData = parent::read($sessionId);
+ $encryptedData = parent::read($id);
return $this->decrypt($encryptedData);
}
/**
- * @param $sessionId
- * @param $data
+ * @param string $id
+ * @param string $data
*
* @throws SessionException
*
* @return bool
*/
- public function write($sessionId, $data): bool
+ public function write($id, $data): bool
{
$cryptedData = $this->encrypt($data);
- return parent::write($sessionId, $cryptedData);
+ return parent::write($id, $cryptedData);
}
}
diff --git a/src/Session.php b/src/Session.php
index e299921..f43bc19 100644
--- a/src/Session.php
+++ b/src/Session.php
@@ -4,8 +4,6 @@
namespace Rancoud\Session;
-use Exception;
-
/**
* Class Session.
*/
@@ -13,13 +11,10 @@ class Session extends DriverManager
{
use ArrayManager;
- /** @var bool */
protected static bool $hasStarted = false;
- /** @var bool */
protected static bool $hasChanged = true;
- /** @var array */
protected static array $options = [
'read_and_close' => true,
'cookie_httponly' => '1',
@@ -31,7 +26,7 @@ class Session extends DriverManager
/**
* @param array $options
*
- * @throws Exception
+ * @throws SessionException
*/
public static function start(array $options = []): void
{
@@ -45,7 +40,7 @@ public static function start(array $options = []): void
/**
* @param array $options
*
- * @throws Exception
+ * @throws SessionException
*/
protected static function populateOptions(array $options = []): void
{
@@ -55,7 +50,7 @@ protected static function populateOptions(array $options = []): void
}
/**
- * @throws Exception
+ * @throws SessionException
*/
protected static function setupAndStart(): void
{
@@ -100,13 +95,11 @@ protected static function setupSessionParameters(): void
{
\session_name(static::getOption('name'));
- \session_set_save_handler(static::$driver);
+ \session_set_save_handler(static::$driver, true);
\session_save_path(static::getOption('save_path'));
static::setupCookieParams();
-
- \register_shutdown_function('session_write_close');
}
/**
@@ -197,7 +190,7 @@ protected static function setupCookieParams(): void
}
/**
- * @throws Exception
+ * @throws SessionException
*/
public static function regenerate(): bool
{
@@ -270,11 +263,12 @@ public static function getId(): string
public static function setId(string $id): string
{
static::$hasChanged = true;
+
return \session_id($id);
}
/**
- * @throws Exception
+ * @throws SessionException
*/
public static function gc(): void
{
@@ -284,7 +278,7 @@ public static function gc(): void
}
/**
- * @throws Exception
+ * @throws SessionException
*/
protected static function startSessionIfNotHasStarted(): void
{
@@ -294,7 +288,7 @@ protected static function startSessionIfNotHasStarted(): void
}
/**
- * @throws Exception
+ * @throws SessionException
*/
protected static function startSessionIfNotHasStartedForceWrite(): void
{
@@ -333,7 +327,7 @@ protected static function getLifetimeForRedis(): int
/**
* @param string $key
- * @param $value
+ * @param mixed $value
*
* @throws SessionException
*/
diff --git a/tests/DatabaseEncryptionTest.php b/tests/DatabaseEncryptionTest.php
index 42fb6d9..19ef871 100644
--- a/tests/DatabaseEncryptionTest.php
+++ b/tests/DatabaseEncryptionTest.php
@@ -1,23 +1,22 @@
'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
- static::$db = new \Rancoud\Database\Database($conf);
+ static::$db = new DB($conf);
- $sql = '
+ $sql = <<exec($sql);
- static::$db->truncateTables('sessions');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ SQL;
+
+ static::$db->exec($sql);
+ static::$db->truncateTables('sessions');
}
+ /**
+ * @throws DatabaseException
+ */
protected function setUp(): void
{
- try {
- static::$db->truncateTables('sessions');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ static::$db->truncateTables('sessions');
}
public function testOpen(): void
@@ -76,8 +67,8 @@ public function testOpen(): void
$savePath = '';
$sessionName = '';
- $success = $database->open($savePath, $sessionName);
- static::assertTrue($success);
+
+ static::assertTrue($database->open($savePath, $sessionName));
}
public function testClose(): void
@@ -87,13 +78,12 @@ public function testClose(): void
$database->setCurrentDatabase(static::$db);
- $success = $database->close();
- static::assertTrue($success);
+ static::assertTrue($database->close());
}
/**
* @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testWrite(): void
{
@@ -104,29 +94,23 @@ public function testWrite(): void
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
$row = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row);
- static::assertNotEquals($data, $row['content']);
+ static::assertNotSame($data, $row['content']);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInDatabaseDecrypted = $encryptionTrait->decrypt($row['content']);
- static::assertEquals($data, $dataInDatabaseDecrypted);
+ static::assertSame($data, $dataInDatabaseDecrypted);
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testRead(): void
{
@@ -137,33 +121,24 @@ public function testRead(): void
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $database->write($sessionId, $data);
- $dataOutput = $database->read($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+
+ $database->write($sessionId, $data);
+ $dataOutput = $database->read($sessionId);
+
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
- try {
- $dataOutput = $database->read($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
+ $dataOutput = $database->read($sessionId);
- return;
- }
static::assertEmpty($dataOutput);
static::assertIsString($dataOutput);
}
/**
* @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testDestroy(): void
{
@@ -173,45 +148,25 @@ public function testDestroy(): void
$database->setCurrentDatabase(static::$db);
$sessionId = 'todelete';
- try {
- $success = $database->destroy($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->destroy($sessionId));
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $database->write($sessionId, $data);
$sql = 'SELECT COUNT(id) FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
$isRowExist = (static::$db->count($sql, $params) === 1);
static::assertTrue($isRowExist);
- try {
- $success = $database->destroy($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->destroy($sessionId));
$isRowNotExist = (static::$db->count($sql, $params) === 0);
static::assertTrue($isRowNotExist);
}
/**
* @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testGc(): void
{
@@ -225,34 +180,21 @@ public function testGc(): void
$sql = 'SELECT COUNT(id) FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$isRowExist = (static::$db->count($sql, $params) === 1);
static::assertTrue($isRowExist);
$lifetime = -1000;
- try {
- $success = $database->gc($lifetime);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->gc($lifetime));
$isRowNotExist = (static::$db->count($sql, $params) === 0);
static::assertTrue($isRowNotExist);
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws DatabaseException
+ * @throws SessionException
*/
public function testSetUserId(): void
{
@@ -266,55 +208,28 @@ public function testSetUserId(): void
$userId = 5;
$database->setUserId($userId);
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT id_user FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $userIdInDatabase = static::$db->selectVar($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $userIdInDatabase = (int) static::$db->selectVar($sql, $params);
static::assertNotNull($userIdInDatabase);
- static::assertEquals($userId, $userIdInDatabase);
+ static::assertSame($userId, $userIdInDatabase);
$userId = null;
$database->setUserId($userId);
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT id_user FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $userIdInDatabase = static::$db->selectVar($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $userIdInDatabase = static::$db->selectVar($sql, $params);
static::assertNull($userIdInDatabase);
- static::assertEquals($userId, $userIdInDatabase);
+ static::assertSame($userId, $userIdInDatabase);
}
/**
- * @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testSetNewDatabaseWithArray(): void
{
@@ -329,27 +244,20 @@ public function testSetNewDatabaseWithArray(): void
'database' => 'test_database'
];
- $mysqlHost = getenv('MYSQL_HOST', true);
- $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
$database->setNewDatabase($params);
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
}
/**
* @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testSetNewDatabaseWithConfigurator(): void
{
@@ -364,27 +272,34 @@ public function testSetNewDatabaseWithConfigurator(): void
'database' => 'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
$database->setNewDatabase($conf);
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
+ static::assertTrue($database->write($sessionId, $data));
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testSetNewDatabaseSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not set database: "invalid" settings is not recognized');
- return;
- }
- static::assertTrue($success);
+ $database = new DatabaseEncryption();
+ $database->setKey('randomKey');
+ $database->setNewDatabase([
+ 'invalid' => 'invalid'
+ ]);
}
/**
- * @throws DatabaseException
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testValidateId(): void
{
@@ -396,13 +311,7 @@ public function testValidateId(): void
$endId1 = 'Dj8hh65DlR3tTFI1SGX3mFciDA9rMOa4LlnMr';
$endId2 = 'Dklezfoipvfk0lferijkoefzjklgrvefLlnMr';
- try {
- $database->write($baseId . $endId1, 'a');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $database->write($baseId . $endId1, 'a');
static::assertTrue($database->validateId($baseId . $endId1));
static::assertFalse($database->validateId($baseId . $endId2));
@@ -410,7 +319,8 @@ public function testValidateId(): void
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws DatabaseException
+ * @throws SessionException
*/
public function testUpdateTimestamp(): void
{
@@ -421,70 +331,41 @@ public function testUpdateTimestamp(): void
$sessionId = 'sessionId';
$data = 'azerty';
- $success = false;
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $row1 = static::$db->selectRow($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
-
+ $row1 = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row1);
- static::assertNotEquals($data, $row1['content']);
+ static::assertNotSame($data, $row1['content']);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInDatabaseDecrypted = $encryptionTrait->decrypt($row1['content']);
- static::assertEquals($data, $dataInDatabaseDecrypted);
+ static::assertSame($data, $dataInDatabaseDecrypted);
- sleep(1);
+ \sleep(1);
- try {
- $success = $database->updateTimestamp($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
-
- static::assertTrue($success);
+ static::assertTrue($database->updateTimestamp($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $row2 = static::$db->selectRow($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $row2 = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row2);
- static::assertNotEquals($data, $row2['content']);
+ static::assertNotSame($data, $row2['content']);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInDatabaseDecrypted = $encryptionTrait->decrypt($row2['content']);
- static::assertEquals($data, $dataInDatabaseDecrypted);
+ static::assertSame($data, $dataInDatabaseDecrypted);
static::assertTrue($row1['last_access'] < $row2['last_access']);
}
/**
- * @throws DatabaseException
+ * @throws SessionException
*/
public function testCreateId(): void
{
@@ -494,6 +375,6 @@ public function testCreateId(): void
$string = $database->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
}
}
diff --git a/tests/DatabaseTest.php b/tests/DatabaseTest.php
index 5452818..4889857 100644
--- a/tests/DatabaseTest.php
+++ b/tests/DatabaseTest.php
@@ -1,23 +1,22 @@
'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
-
- static::$db = new \Rancoud\Database\Database($conf);
-
- $sql = '
- CREATE TABLE IF NOT EXISTS `sessions` (
- `id` varchar(128) NOT NULL,
- `id_user` int(10) unsigned DEFAULT NULL,
- `last_access` datetime NOT NULL,
- `content` text NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- ';
- try {
- static::$db->exec($sql);
- static::$db->truncateTables('sessions');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+
+ static::$db = new DB($conf);
+
+ $sql = <<exec($sql);
+ static::$db->truncateTables('sessions');
}
+ /**
+ * @throws DatabaseException
+ */
protected function setUp(): void
{
- try {
- static::$db->truncateTables('sessions');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ static::$db->truncateTables('sessions');
}
public function testOpen(): void
@@ -74,8 +65,8 @@ public function testOpen(): void
$savePath = '';
$sessionName = '';
- $success = $database->open($savePath, $sessionName);
- static::assertTrue($success);
+
+ static::assertTrue($database->open($savePath, $sessionName));
}
public function testClose(): void
@@ -83,12 +74,12 @@ public function testClose(): void
$database = new Database();
$database->setCurrentDatabase(static::$db);
- $success = $database->close();
- static::assertTrue($success);
+ static::assertTrue($database->close());
}
/**
* @throws DatabaseException
+ * @throws SessionException
*/
public function testWrite(): void
{
@@ -97,22 +88,39 @@ public function testWrite(): void
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
$row = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row);
- static::assertEquals($data, $row['content']);
+ static::assertSame($data, $row['content']);
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testWriteSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not update session: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->write('invalid_session_id', '');
}
+ /**
+ * @throws SessionException
+ */
public function testRead(): void
{
$database = new Database();
@@ -120,32 +128,44 @@ public function testRead(): void
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $database->write($sessionId, $data);
- $dataOutput = $database->read($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+
+ $database->write($sessionId, $data);
+ $dataOutput = $database->read($sessionId);
+
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
- try {
- $dataOutput = $database->read($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
+ $dataOutput = $database->read($sessionId);
- return;
- }
static::assertEmpty($dataOutput);
static::assertIsString($dataOutput);
}
+ /**
+ * @throws SessionException
+ */
+ public function testReadSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not read session: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->read('invalid_session_id');
+ }
+
/**
* @throws DatabaseException
+ * @throws SessionException
*/
public function testDestroy(): void
{
@@ -153,44 +173,45 @@ public function testDestroy(): void
$database->setCurrentDatabase(static::$db);
$sessionId = 'todelete';
- try {
- $success = $database->destroy($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->destroy($sessionId));
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $database->write($sessionId, $data);
$sql = 'SELECT COUNT(id) FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
$isRowExist = (static::$db->count($sql, $params) === 1);
static::assertTrue($isRowExist);
- try {
- $success = $database->destroy($sessionId);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
- $isRowNotExist = (static::$db->count($sql, $params) === 0);
+ static::assertTrue($database->destroy($sessionId));
+ $isRowNotExist = static::$db->count($sql, $params) === 0;
static::assertTrue($isRowNotExist);
}
+ /**
+ * @throws SessionException
+ */
+ public function testDestroySessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not delete session: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->destroy('invalid_session_id');
+ }
+
/**
* @throws DatabaseException
+ * @throws SessionException
*/
public function testGc(): void
{
@@ -202,32 +223,42 @@ public function testGc(): void
$sql = 'SELECT COUNT(id) FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$isRowExist = (static::$db->count($sql, $params) === 1);
static::assertTrue($isRowExist);
$lifetime = -1000;
- try {
- $success = $database->gc($lifetime);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->gc($lifetime));
$isRowNotExist = (static::$db->count($sql, $params) === 0);
static::assertTrue($isRowNotExist);
}
+ /**
+ * @throws SessionException
+ */
+ public function testGcSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not clean old sessions: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->gc(-1000);
+ }
+
+ /**
+ * @throws DatabaseException
+ * @throws SessionException
+ */
public function testSetUserId(): void
{
$database = new Database();
@@ -238,54 +269,28 @@ public function testSetUserId(): void
$userId = 5;
$database->setUserId($userId);
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT id_user FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $userIdInDatabase = static::$db->selectVar($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $userIdInDatabase = (int) static::$db->selectVar($sql, $params);
static::assertNotNull($userIdInDatabase);
- static::assertEquals($userId, $userIdInDatabase);
+ static::assertSame($userId, $userIdInDatabase);
$userId = null;
$database->setUserId($userId);
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT id_user FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $userIdInDatabase = static::$db->selectVar($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $userIdInDatabase = static::$db->selectVar($sql, $params);
static::assertNull($userIdInDatabase);
- static::assertEquals($userId, $userIdInDatabase);
+ static::assertSame($userId, $userIdInDatabase);
}
/**
- * @throws DatabaseException
+ * @throws SessionException
*/
public function testSetNewDatabaseWithArray(): void
{
@@ -298,26 +303,20 @@ public function testSetNewDatabaseWithArray(): void
'database' => 'test_database'
];
- $mysqlHost = getenv('MYSQL_HOST', true);
- $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
$database->setNewDatabase($params);
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
}
/**
* @throws DatabaseException
+ * @throws SessionException
*/
public function testSetNewDatabaseWithConfigurator(): void
{
@@ -330,26 +329,34 @@ public function testSetNewDatabaseWithConfigurator(): void
'database' => 'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
$database->setNewDatabase($conf);
$sessionId = 'sessionId';
$data = 'azerty';
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
+ static::assertTrue($database->write($sessionId, $data));
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testSetNewDatabaseSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not set database: "invalid" settings is not recognized');
+
+ $database = new Database();
- return;
- }
- static::assertTrue($success);
+ $database->setNewDatabase([
+ 'invalid' => 'invalid'
+ ]);
}
/**
- * @throws DatabaseException
+ * @throws SessionException
*/
public function testValidateId(): void
{
@@ -360,19 +367,38 @@ public function testValidateId(): void
$endId1 = 'Dj8hh65DlR3tTFI1SGX3mFciDA9rMOa4LlnMr';
$endId2 = 'Dklezfoipvfk0lferijkoefzjklgrvefLlnMr';
- try {
- $database->write($baseId . $endId1, 'a');
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $database->write($baseId . $endId1, 'a');
static::assertTrue($database->validateId($baseId . $endId1));
static::assertFalse($database->validateId($baseId . $endId2));
static::assertFalse($database->validateId('kjlfez/fez'));
}
+ /**
+ * @throws SessionException
+ */
+ public function testValidateIdSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not validate id: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->setLengthSessionID(32);
+ $database->validateId('-------invalid-session-id-------');
+ }
+
+ /**
+ * @throws DatabaseException
+ * @throws SessionException
+ */
public function testUpdateTimestamp(): void
{
$database = new Database();
@@ -381,61 +407,32 @@ public function testUpdateTimestamp(): void
$sessionId = 'sessionId';
$data = 'azerty';
- $success = false;
- try {
- $success = $database->write($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
- static::assertTrue($success);
+ static::assertTrue($database->write($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $row1 = static::$db->selectRow($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
-
+ $row1 = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row1);
- static::assertEquals($data, $row1['content']);
-
- sleep(1);
+ static::assertSame($data, $row1['content']);
- try {
- $success = $database->updateTimestamp($sessionId, $data);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
+ \sleep(1);
- return;
- }
-
- static::assertTrue($success);
+ static::assertTrue($database->updateTimestamp($sessionId, $data));
$sql = 'SELECT * FROM sessions WHERE id = :id';
$params = ['id' => $sessionId];
- try {
- $row2 = static::$db->selectRow($sql, $params);
- } catch (DatabaseException $e) {
- var_dump(static::$db->getErrors());
-
- return;
- }
+ $row2 = static::$db->selectRow($sql, $params);
static::assertNotEmpty($row2);
- static::assertEquals($data, $row2['content']);
+ static::assertSame($data, $row2['content']);
static::assertTrue($row1['last_access'] < $row2['last_access']);
}
/**
- * @throws DatabaseException
+ * @throws SessionException
*/
public function testCreateId(): void
{
@@ -444,6 +441,45 @@ public function testCreateId(): void
$string = $database->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testCreateIdSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not create sid: Error Connecting Database');
+
+ $database = new Database();
+ $database->setNewDatabase([
+ 'driver' => 'mysql',
+ 'host' => 'mariadb',
+ 'user' => 'invalid',
+ 'password' => '',
+ 'database' => 'test_database'
+ ]);
+
+ $database->create_sid();
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testLengthSessionID(): void
+ {
+ $database = new Database();
+ $database->setLengthSessionID(50);
+ static::assertSame(50, $database->getLengthSessionID());
+ }
+
+ public function testLengthSessionIDSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not set length session ID below 32');
+
+ $database = new Database();
+ $database->setLengthSessionID(1);
}
}
diff --git a/tests/DefaultEncryptionTest.php b/tests/DefaultEncryptionTest.php
index d0308f6..758c809 100644
--- a/tests/DefaultEncryptionTest.php
+++ b/tests/DefaultEncryptionTest.php
@@ -4,7 +4,7 @@
declare(strict_types=1);
-namespace Rancoud\Session\Test;
+namespace tests;
use PHPUnit\Framework\TestCase;
use Rancoud\Session\Session;
@@ -16,31 +16,31 @@ class DefaultEncryptionTest extends TestCase
{
protected function setUp(): void
{
- $path = ini_get('session.save_path');
+ $path = \ini_get('session.save_path');
if (empty($path)) {
- $path = DIRECTORY_SEPARATOR . 'tmp';
+ $path = \DIRECTORY_SEPARATOR . 'tmp';
}
- $pattern = $path . DIRECTORY_SEPARATOR . 'sess_*';
- foreach (glob($pattern) as $file) {
- if (file_exists($file)) {
- unlink($file);
+ $pattern = $path . \DIRECTORY_SEPARATOR . 'sess_*';
+ foreach (\glob($pattern) as $file) {
+ if (\file_exists($file)) {
+ \unlink($file);
}
}
}
private function foundSessionFile()
{
- $path = ini_get('session.save_path');
+ $path = \ini_get('session.save_path');
if (empty($path)) {
- $path = DIRECTORY_SEPARATOR . 'tmp';
+ $path = \DIRECTORY_SEPARATOR . 'tmp';
}
- $id = session_id();
+ $id = \session_id();
- $files = scandir($path);
+ $files = \scandir($path);
foreach ($files as $file) {
- if (mb_strpos($file, $id) !== false) {
- return file_get_contents($path . DIRECTORY_SEPARATOR . 'sess_' . $id);
+ if (\mb_strpos($file, $id) !== false) {
+ return \file_get_contents($path . \DIRECTORY_SEPARATOR . 'sess_' . $id);
}
}
@@ -49,6 +49,7 @@ private function foundSessionFile()
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testReadAndWrite(): void
@@ -57,13 +58,13 @@ public function testReadAndWrite(): void
Session::set('a', 'b');
- session_write_close();
+ \session_write_close();
$data = $this->foundSessionFile();
static::assertNotFalse($data);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataDecrypted = $encryptionTrait->decrypt($data);
- static::assertEquals('a|s:1:"b";', $dataDecrypted);
+ static::assertSame('a|s:1:"b";', $dataDecrypted);
}
}
diff --git a/tests/EncryptionTest.php b/tests/EncryptionTest.php
index d3b3be4..9794a75 100644
--- a/tests/EncryptionTest.php
+++ b/tests/EncryptionTest.php
@@ -1,9 +1,10 @@
encrypt($dataToEncrypt);
$finalData = $encryptionTrait->decrypt($encryptedData);
- static::assertEquals($dataToEncrypt, $finalData);
+ static::assertSame($dataToEncrypt, $finalData);
}
public function testAllEncryptionMethods(): void
@@ -39,15 +40,15 @@ public function testAllEncryptionMethods(): void
$encryptedData = $encryptionTrait->encrypt($dataToEncrypt);
$finalData = $encryptionTrait->decrypt($encryptedData);
- static::assertEquals($dataToEncrypt, $finalData, $method . ' fail!');
+ static::assertSame($dataToEncrypt, $finalData, $method . ' fail!');
}
}
public function testExceptionMethod(): void
{
$this->expectException(SessionException::class);
- $this->expectExceptionMessage('Method unknowed: method');
-
+ $this->expectExceptionMessage('Unknown method: method');
+
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setMethod('method');
}
@@ -56,7 +57,7 @@ public function testExceptionEmptyKey(): void
{
$this->expectException(SessionException::class);
$this->expectExceptionMessage('Key has to be a non-empty string');
-
+
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$dataToEncrypt = 'this is something to encrypt';
$encryptionTrait->encrypt($dataToEncrypt);
diff --git a/tests/FileEncryptionTest.php b/tests/FileEncryptionTest.php
index dcb020e..6c3f719 100644
--- a/tests/FileEncryptionTest.php
+++ b/tests/FileEncryptionTest.php
@@ -1,12 +1,14 @@
open($this->getPath(), '');
static::assertTrue($success);
}
+ /**
+ * @throws SessionException
+ */
public function testOpen(): void
{
$fileEncryption = new FileEncryption();
@@ -58,10 +68,10 @@ public function testOpen(): void
$success = $fileEncryption->open($savePath, $sessionName);
static::assertTrue($success);
- $savePathNotCreated = $savePath . DIRECTORY_SEPARATOR . 'tests';
+ $savePathNotCreated = $savePath . \DIRECTORY_SEPARATOR . 'tests';
$success = $fileEncryption->open($savePathNotCreated, $sessionName);
static::assertTrue($success);
- $success = file_exists($savePathNotCreated);
+ $success = \file_exists($savePathNotCreated);
static::assertTrue($success);
}
@@ -74,7 +84,7 @@ public function testClose(): void
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testWrite(): void
{
@@ -88,17 +98,17 @@ public function testWrite(): void
$success = $fileEncryption->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertNotEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertNotSame($data, $dataInFile);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInFileDecrypted = $encryptionTrait->decrypt($dataInFile);
- static::assertEquals($data, $dataInFileDecrypted);
+ static::assertSame($data, $dataInFileDecrypted);
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testRead(): void
{
@@ -115,7 +125,7 @@ public function testRead(): void
$dataOutput = $fileEncryption->read($sessionId);
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
$dataOutput = $fileEncryption->read($sessionId);
@@ -124,7 +134,7 @@ public function testRead(): void
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testDestroy(): void
{
@@ -142,16 +152,16 @@ public function testDestroy(): void
$success = $fileEncryption->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileExist);
$success = $fileEncryption->destroy($sessionId);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileNotExist);
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testGc(): void
{
@@ -165,19 +175,19 @@ public function testGc(): void
$success = $fileEncryption->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileExist);
$lifetime = -1000;
$success = $fileEncryption->gc($lifetime);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileNotExist);
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testValidateId(): void
{
@@ -198,7 +208,7 @@ public function testValidateId(): void
}
/**
- * @throws \Rancoud\Session\SessionException
+ * @throws SessionException
*/
public function testUpdateTimestamp(): void
{
@@ -212,31 +222,31 @@ public function testUpdateTimestamp(): void
$success = $fileEncryption->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- $oldFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertNotEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $oldFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertNotSame($data, $dataInFile);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInFileDecrypted = $encryptionTrait->decrypt($dataInFile);
- static::assertEquals($data, $dataInFileDecrypted);
+ static::assertSame($data, $dataInFileDecrypted);
- sleep(1);
+ \sleep(1);
$success = $fileEncryption->updateTimestamp($sessionId, $data);
static::assertTrue($success);
- clearstatcache();
+ \clearstatcache();
- $dataInFile2 = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertNotEquals($data, $dataInFile2);
+ $dataInFile2 = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertNotSame($data, $dataInFile2);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInFileDecrypted = $encryptionTrait->decrypt($dataInFile2);
- static::assertEquals($data, $dataInFileDecrypted);
- static::assertNotEquals($dataInFile, $dataInFile2);
+ static::assertSame($data, $dataInFileDecrypted);
+ static::assertNotSame($dataInFile, $dataInFile2);
- $newFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $newFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($oldFileModifiedTime < $newFileModifiedTime);
}
@@ -251,6 +261,6 @@ public function testCreateId(): void
$string = $fileEncryption->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
}
}
diff --git a/tests/FileTest.php b/tests/FileTest.php
index ff430b3..34b4caf 100644
--- a/tests/FileTest.php
+++ b/tests/FileTest.php
@@ -1,12 +1,14 @@
open($savePath, $sessionName);
static::assertTrue($success);
- $savePathNotCreated = $savePath . DIRECTORY_SEPARATOR . 'tests';
+ $savePathNotCreated = $savePath . \DIRECTORY_SEPARATOR . 'tests';
$success = $file->open($savePathNotCreated, $sessionName);
static::assertTrue($success);
- $success = file_exists($savePathNotCreated);
+ $success = \file_exists($savePathNotCreated);
static::assertTrue($success);
}
@@ -78,6 +83,9 @@ public function testClose(): void
static::assertTrue($success);
}
+ /**
+ * @throws SessionException
+ */
public function testWrite(): void
{
$file = new File();
@@ -89,10 +97,13 @@ public function testWrite(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertSame($data, $dataInFile);
}
+ /**
+ * @throws SessionException
+ */
public function testRead(): void
{
$file = new File();
@@ -107,7 +118,7 @@ public function testRead(): void
$dataOutput = $file->read($sessionId);
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
$dataOutput = $file->read($sessionId);
@@ -115,6 +126,9 @@ public function testRead(): void
static::assertIsString($dataOutput);
}
+ /**
+ * @throws SessionException
+ */
public function testDestroy(): void
{
$file = new File();
@@ -130,14 +144,17 @@ public function testDestroy(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileExist);
$success = $file->destroy($sessionId);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileNotExist);
}
+ /**
+ * @throws SessionException
+ */
public function testGc(): void
{
$file = new File();
@@ -149,17 +166,20 @@ public function testGc(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileExist);
$lifetime = -1000;
$success = $file->gc($lifetime);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($isFileNotExist);
}
+ /**
+ * @throws SessionException
+ */
public function testValidateId(): void
{
$file = new File();
@@ -177,6 +197,9 @@ public function testValidateId(): void
static::assertFalse($file->validateId('kjlfez/fez'));
}
+ /**
+ * @throws SessionException
+ */
public function testUpdateTimestamp(): void
{
$file = new File();
@@ -188,20 +211,20 @@ public function testUpdateTimestamp(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- $oldFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $oldFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertSame($data, $dataInFile);
- sleep(1);
+ \sleep(1);
$success = $file->updateTimestamp($sessionId, $data);
static::assertTrue($success);
- clearstatcache();
+ \clearstatcache();
- $dataInFile2 = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
- static::assertEquals($data, $dataInFile2);
- static::assertEquals($dataInFile, $dataInFile2);
- $newFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ $dataInFile2 = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
+ static::assertSame($data, $dataInFile2);
+ static::assertSame($dataInFile, $dataInFile2);
+ $newFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'sess_' . $sessionId);
static::assertTrue($oldFileModifiedTime < $newFileModifiedTime);
}
@@ -215,6 +238,25 @@ public function testCreateId(): void
$string = $file->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testLengthSessionID(): void
+ {
+ $file = new File();
+ $file->setLengthSessionID(50);
+ static::assertSame(50, $file->getLengthSessionID());
+ }
+
+ public function testLengthSessionIDSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not set length session ID below 32');
+
+ $file = new File();
+ $file->setLengthSessionID(1);
}
}
diff --git a/tests/FileWithNewPrefixTest.php b/tests/FileWithNewPrefixTest.php
index e4cb8fd..2697421 100644
--- a/tests/FileWithNewPrefixTest.php
+++ b/tests/FileWithNewPrefixTest.php
@@ -4,7 +4,7 @@
declare(strict_types=1);
-namespace Rancoud\Session\Test;
+namespace tests;
use PHPUnit\Framework\TestCase;
use Rancoud\Session\File;
@@ -16,20 +16,20 @@ class FileWithNewPrefixTest extends TestCase
{
protected function setUp(): void
{
- $path = ini_get('session.save_path');
+ $path = \ini_get('session.save_path');
if (empty($path)) {
- $path = DIRECTORY_SEPARATOR . 'tmp';
+ $path = \DIRECTORY_SEPARATOR . 'tmp';
}
- $pattern = $path . DIRECTORY_SEPARATOR . 'myprefix_*';
- foreach (glob($pattern) as $file) {
- if (file_exists($file)) {
- unlink($file);
+ $pattern = $path . \DIRECTORY_SEPARATOR . 'myprefix_*';
+ foreach (\glob($pattern) as $file) {
+ if (\file_exists($file)) {
+ \unlink($file);
}
}
- if (is_dir($path . DIRECTORY_SEPARATOR . 'tests')) {
- rmdir($path . DIRECTORY_SEPARATOR . 'tests');
+ if (\is_dir($path . \DIRECTORY_SEPARATOR . 'tests')) {
+ \rmdir($path . \DIRECTORY_SEPARATOR . 'tests');
}
}
@@ -38,9 +38,9 @@ protected function setUp(): void
*/
private function getPath(): string
{
- $path = ini_get('session.save_path');
+ $path = \ini_get('session.save_path');
if (empty($path)) {
- return DIRECTORY_SEPARATOR . 'tmp';
+ return \DIRECTORY_SEPARATOR . 'tmp';
}
return $path;
@@ -49,7 +49,7 @@ private function getPath(): string
/**
* @param File $file
*
- * @throws \PHPUnit\Framework\AssertionFailedError
+ * @throws \Rancoud\Session\SessionException
*/
private function openSessionForSavingSavePath(File $file): void
{
@@ -57,6 +57,9 @@ private function openSessionForSavingSavePath(File $file): void
static::assertTrue($success);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testOpen(): void
{
$file = new File();
@@ -66,10 +69,10 @@ public function testOpen(): void
$success = $file->open($savePath, $sessionName);
static::assertTrue($success);
- $savePathNotCreated = $savePath . DIRECTORY_SEPARATOR . 'tests';
+ $savePathNotCreated = $savePath . \DIRECTORY_SEPARATOR . 'tests';
$success = $file->open($savePathNotCreated, $sessionName);
static::assertTrue($success);
- $success = file_exists($savePathNotCreated);
+ $success = \file_exists($savePathNotCreated);
static::assertTrue($success);
}
@@ -81,6 +84,9 @@ public function testClose(): void
static::assertTrue($success);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testWrite(): void
{
$file = new File();
@@ -93,10 +99,13 @@ public function testWrite(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
- static::assertEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ static::assertSame($data, $dataInFile);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testRead(): void
{
$file = new File();
@@ -112,7 +121,7 @@ public function testRead(): void
$dataOutput = $file->read($sessionId);
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
$dataOutput = $file->read($sessionId);
@@ -120,6 +129,9 @@ public function testRead(): void
static::assertIsString($dataOutput);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testDestroy(): void
{
$file = new File();
@@ -136,14 +148,17 @@ public function testDestroy(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
static::assertTrue($isFileExist);
$success = $file->destroy($sessionId);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
static::assertTrue($isFileNotExist);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testGc(): void
{
$file = new File();
@@ -156,17 +171,20 @@ public function testGc(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $isFileExist = file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $isFileExist = \file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
static::assertTrue($isFileExist);
$lifetime = -1000;
$success = $file->gc($lifetime);
static::assertTrue($success);
- $isFileNotExist = !file_exists($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $isFileNotExist = !\file_exists($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
static::assertTrue($isFileNotExist);
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testValidateId(): void
{
$file = new File();
@@ -185,6 +203,9 @@ public function testValidateId(): void
static::assertFalse($file->validateId('kjlfez/fez'));
}
+ /**
+ * @throws \Rancoud\Session\SessionException
+ */
public function testUpdateTimestamp(): void
{
$file = new File();
@@ -197,20 +218,20 @@ public function testUpdateTimestamp(): void
$success = $file->write($sessionId, $data);
static::assertTrue($success);
- $dataInFile = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
- $oldFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
- static::assertEquals($data, $dataInFile);
+ $dataInFile = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $oldFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ static::assertSame($data, $dataInFile);
- sleep(1);
+ \sleep(1);
$success = $file->updateTimestamp($sessionId, $data);
static::assertTrue($success);
- clearstatcache();
+ \clearstatcache();
- $dataInFile2 = file_get_contents($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
- static::assertEquals($data, $dataInFile2);
- static::assertEquals($dataInFile, $dataInFile2);
- $newFileModifiedTime = filemtime($this->getPath() . DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ $dataInFile2 = \file_get_contents($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
+ static::assertSame($data, $dataInFile2);
+ static::assertSame($dataInFile, $dataInFile2);
+ $newFileModifiedTime = \filemtime($this->getPath() . \DIRECTORY_SEPARATOR . 'myprefix_' . $sessionId);
static::assertTrue($oldFileModifiedTime < $newFileModifiedTime);
}
@@ -225,6 +246,6 @@ public function testCreateId(): void
$string = $file->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
}
}
diff --git a/tests/RedisEncryptionTest.php b/tests/RedisEncryptionTest.php
index 3eb1472..7f5ae4b 100644
--- a/tests/RedisEncryptionTest.php
+++ b/tests/RedisEncryptionTest.php
@@ -4,7 +4,7 @@
declare(strict_types=1);
-namespace Rancoud\Session\Test;
+namespace tests;
use PHPUnit\Framework\TestCase;
use Predis\Client as Predis;
@@ -26,8 +26,8 @@ public static function setUpBeforeClass(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
static::$redis = new Predis($params);
static::$redis->flushdb();
@@ -77,12 +77,12 @@ public function testWrite(): void
static::assertTrue($success);
$dataInRedis = static::$redis->get($sessionId);
- static::assertNotEquals($data, $dataInRedis);
+ static::assertNotSame($data, $dataInRedis);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInRedisDecrypted = $encryptionTrait->decrypt($dataInRedis);
- static::assertEquals($data, $dataInRedisDecrypted);
+ static::assertSame($data, $dataInRedisDecrypted);
}
/**
@@ -103,7 +103,7 @@ public function testRead(): void
$dataOutput = $redis->read($sessionId);
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
$dataOutput = $redis->read($sessionId);
@@ -157,7 +157,7 @@ public function testGc(): void
$isKeyExist = static::$redis->exists($sessionId) === 1;
static::assertTrue($isKeyExist);
- sleep(2);
+ \sleep(2);
$lifetime = 0;
$success = $redis->gc($lifetime);
@@ -181,8 +181,8 @@ public function testSetNewRedis(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
$redis->setNewRedis($params);
@@ -231,15 +231,15 @@ public function testUpdateTimestamp(): void
static::assertTrue($success);
$dataInRedis = static::$redis->get($sessionId);
- static::assertNotEquals($data, $dataInRedis);
+ static::assertNotSame($data, $dataInRedis);
$ttl1 = static::$redis->ttl($sessionId);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInRedisDecrypted = $encryptionTrait->decrypt($dataInRedis);
- static::assertEquals($data, $dataInRedisDecrypted);
+ static::assertSame($data, $dataInRedisDecrypted);
- sleep(2);
+ \sleep(2);
$ttl2 = static::$redis->ttl($sessionId);
@@ -247,13 +247,13 @@ public function testUpdateTimestamp(): void
static::assertTrue($success);
$dataInRedis2 = static::$redis->get($sessionId);
- static::assertNotEquals($data, $dataInRedis2);
+ static::assertNotSame($data, $dataInRedis2);
$ttl3 = static::$redis->ttl($sessionId);
$encryptionTrait = $this->getObjectForTrait('Rancoud\Session\Encryption');
$encryptionTrait->setKey('randomKey');
$dataInRedisDecrypted = $encryptionTrait->decrypt($dataInRedis2);
- static::assertEquals($data, $dataInRedisDecrypted);
+ static::assertSame($data, $dataInRedisDecrypted);
static::assertTrue($ttl2 < $ttl1);
static::assertTrue($ttl3 > $ttl2);
@@ -271,6 +271,6 @@ public function testCreateId(): void
$string = $redis->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
}
}
diff --git a/tests/RedisTest.php b/tests/RedisTest.php
index a8228da..04e50da 100644
--- a/tests/RedisTest.php
+++ b/tests/RedisTest.php
@@ -4,11 +4,12 @@
declare(strict_types=1);
-namespace Rancoud\Session\Test;
+namespace tests;
use PHPUnit\Framework\TestCase;
use Predis\Client as Predis;
use Rancoud\Session\Redis;
+use Rancoud\Session\SessionException;
/**
* Class RedisTest.
@@ -26,8 +27,8 @@ public static function setUpBeforeClass(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
static::$redis = new Predis($params);
static::$redis->flushdb();
@@ -68,7 +69,7 @@ public function testWrite(): void
static::assertTrue($success);
$dataInRedis = static::$redis->get($sessionId);
- static::assertEquals($data, $dataInRedis);
+ static::assertSame($data, $dataInRedis);
}
public function testRead(): void
@@ -84,7 +85,7 @@ public function testRead(): void
$dataOutput = $redis->read($sessionId);
static::assertNotEmpty($dataOutput);
static::assertIsString($dataOutput);
- static::assertEquals($data, $dataOutput);
+ static::assertSame($data, $dataOutput);
$sessionId = '';
$dataOutput = $redis->read($sessionId);
@@ -128,7 +129,7 @@ public function testGc(): void
$isKeyExist = static::$redis->exists($sessionId) === 1;
static::assertTrue($isKeyExist);
- sleep(2);
+ \sleep(2);
$lifetime = 0;
$success = $redis->gc($lifetime);
@@ -147,8 +148,8 @@ public function testSetNewRedis(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
$redis->setNewRedis($params);
@@ -187,10 +188,10 @@ public function testUpdateTimestamp(): void
static::assertTrue($success);
$dataInRedis = static::$redis->get($sessionId);
- static::assertEquals($data, $dataInRedis);
+ static::assertSame($data, $dataInRedis);
$ttl1 = static::$redis->ttl($sessionId);
- sleep(2);
+ \sleep(2);
$ttl2 = static::$redis->ttl($sessionId);
@@ -198,7 +199,7 @@ public function testUpdateTimestamp(): void
static::assertTrue($success);
$dataInRedis2 = static::$redis->get($sessionId);
- static::assertEquals($data, $dataInRedis2);
+ static::assertSame($data, $dataInRedis2);
$ttl3 = static::$redis->ttl($sessionId);
static::assertTrue($ttl2 < $ttl1);
@@ -215,6 +216,25 @@ public function testCreateId(): void
$string = $redis->create_sid();
- static::assertSame(preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ static::assertSame(\preg_match('/^[a-zA-Z0-9-]{127}+$/', $string), 1);
+ }
+
+ /**
+ * @throws SessionException
+ */
+ public function testLengthSessionID(): void
+ {
+ $redis = new Redis();
+ $redis->setLengthSessionID(50);
+ static::assertSame(50, $redis->getLengthSessionID());
+ }
+
+ public function testLengthSessionIDSessionException(): void
+ {
+ $this->expectException(SessionException::class);
+ $this->expectExceptionMessage('could not set length session ID below 32');
+
+ $redis = new Redis();
+ $redis->setLengthSessionID(1);
}
}
diff --git a/tests/SessionTest.php b/tests/SessionTest.php
index 84c1bac..8d21544 100644
--- a/tests/SessionTest.php
+++ b/tests/SessionTest.php
@@ -4,7 +4,7 @@
declare(strict_types=1);
-namespace Rancoud\Session\Test;
+namespace tests;
use PHPUnit\Framework\TestCase;
use Rancoud\Session\File;
@@ -18,21 +18,22 @@ class SessionTest extends TestCase
{
protected function setUp(): void
{
- $path = ini_get('session.save_path');
+ $path = \ini_get('session.save_path');
if (empty($path)) {
- $path = DIRECTORY_SEPARATOR . 'tmp';
+ $path = \DIRECTORY_SEPARATOR . 'tmp';
}
- $pattern = $path . DIRECTORY_SEPARATOR . 'sess_*';
- foreach (glob($pattern) as $file) {
- if (file_exists($file)) {
- unlink($file);
+ $pattern = $path . \DIRECTORY_SEPARATOR . 'sess_*';
+ foreach (\glob($pattern) as $file) {
+ if (\file_exists($file)) {
+ \unlink($file);
}
}
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testGetNull(): void
@@ -43,17 +44,19 @@ public function testGetNull(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testSet(): void
{
Session::set('a', 'b');
$value = Session::get('a');
- static::assertEquals('b', $value);
+ static::assertSame('b', $value);
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testHas(): void
@@ -69,6 +72,7 @@ public function testHas(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testHasKeyAndValue(): void
@@ -87,6 +91,7 @@ public function testHasKeyAndValue(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testRemove(): void
@@ -104,6 +109,7 @@ public function testRemove(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testGetAndRemove(): void
@@ -111,7 +117,7 @@ public function testGetAndRemove(): void
Session::set('a', 'b');
$value = Session::getAndRemove('a');
- static::assertEquals('b', $value);
+ static::assertSame('b', $value);
$value = Session::getAndRemove('empty');
static::assertNull($value);
@@ -119,6 +125,7 @@ public function testGetAndRemove(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testStartException(): void
@@ -133,6 +140,7 @@ public function testStartException(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseDefaultDriverWhenAlreadyStartedException(): void
@@ -147,6 +155,7 @@ public function testUseDefaultDriverWhenAlreadyStartedException(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseFileDriverWhenAlreadyStartedException(): void
@@ -161,6 +170,7 @@ public function testUseFileDriverWhenAlreadyStartedException(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseCustomDriverWhenAlreadyStartedException(): void
@@ -175,6 +185,7 @@ public function testUseCustomDriverWhenAlreadyStartedException(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseDefaultDriver(): void
@@ -187,6 +198,7 @@ public function testUseDefaultDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseDefaultEncryptionDriver(): void
@@ -199,6 +211,7 @@ public function testUseDefaultEncryptionDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseFileDriver(): void
@@ -211,6 +224,7 @@ public function testUseFileDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseFileDriverWithPrefix(): void
@@ -225,18 +239,19 @@ public function testUseFileDriverWithPrefix(): void
Session::commit();
static::assertInstanceOf(File::class, Session::getDriver());
- static::assertFileExists($path . DIRECTORY_SEPARATOR . $prefix . $sessionId);
+ static::assertFileExists($path . \DIRECTORY_SEPARATOR . $prefix . $sessionId);
- $pattern = $path . DIRECTORY_SEPARATOR . 'youhou_*';
- foreach (glob($pattern) as $file) {
- if (file_exists($file)) {
- unlink($file);
+ $pattern = $path . \DIRECTORY_SEPARATOR . 'youhou_*';
+ foreach (\glob($pattern) as $file) {
+ if (\file_exists($file)) {
+ \unlink($file);
}
}
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseFileEncryptionDriver(): void
@@ -249,6 +264,7 @@ public function testUseFileEncryptionDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseNewDatabaseDriver(): void
@@ -261,8 +277,8 @@ public function testUseNewDatabaseDriver(): void
'database' => 'test_database'
];
- $mysqlHost = getenv('MYSQL_HOST', true);
- $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
Session::useNewDatabaseDriver($params);
Session::start();
@@ -272,6 +288,7 @@ public function testUseNewDatabaseDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseNewDatabaseEncryptionDriver(): void
@@ -284,8 +301,8 @@ public function testUseNewDatabaseEncryptionDriver(): void
'database' => 'test_database'
];
- $mysqlHost = getenv('MYSQL_HOST', true);
- $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $params['host'] = ($mysqlHost !== false) ? $mysqlHost : '127.0.0.1';
Session::useNewDatabaseEncryptionDriver($params, 'randomKey');
Session::start();
@@ -295,6 +312,7 @@ public function testUseNewDatabaseEncryptionDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Rancoud\Database\DatabaseException
* @throws \Exception
*/
@@ -308,8 +326,8 @@ public function testUseCurrentDatabaseDriver(): void
'database' => 'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
$db = new \Rancoud\Database\Database($conf);
Session::useCurrentDatabaseDriver($db);
@@ -320,6 +338,7 @@ public function testUseCurrentDatabaseDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Rancoud\Database\DatabaseException
* @throws \Exception
*/
@@ -334,8 +353,8 @@ public function testUseCurrentDatabaseEncryptionDriver(): void
'database' => 'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
$db = new \Rancoud\Database\Database($conf);
Session::useCurrentDatabaseEncryptionDriver($db, 'randomKey');
@@ -347,12 +366,13 @@ public function testUseCurrentDatabaseEncryptionDriver(): void
$sessionId = Session::getId();
Session::commit();
- $userIdInTable = $db->selectVar('SELECT id_user FROM sessions WHERE id = :id', ['id' => $sessionId]);
- static::assertEquals($userId, $userIdInTable);
+ $userIdInTable = (int) $db->selectVar('SELECT id_user FROM sessions WHERE id = :id', ['id' => $sessionId]);
+ static::assertSame($userId, $userIdInTable);
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseNewRedisDriver(): void
@@ -363,8 +383,8 @@ public function testUseNewRedisDriver(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
Session::useNewRedisDriver($params);
Session::start();
@@ -374,6 +394,7 @@ public function testUseNewRedisDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseNewRedisEncryptionDriver(): void
@@ -384,8 +405,8 @@ public function testUseNewRedisEncryptionDriver(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
Session::useNewRedisEncryptionDriver($params, 'randomKey');
Session::start();
@@ -395,6 +416,7 @@ public function testUseNewRedisEncryptionDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseCurrentRedisDriver(): void
@@ -405,8 +427,8 @@ public function testUseCurrentRedisDriver(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
$redis = new \Predis\Client($params);
Session::useCurrentRedisDriver($redis);
@@ -417,6 +439,7 @@ public function testUseCurrentRedisDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseCurrentRedisEncryptionDriver(): void
@@ -427,8 +450,8 @@ public function testUseCurrentRedisEncryptionDriver(): void
'port' => 6379,
];
- $redisHost = getenv('REDIS_HOST', true);
- $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
+ $redisHost = \getenv('REDIS_HOST', true);
+ $params['host'] = ($redisHost !== false) ? $redisHost : '127.0.0.1';
$redis = new \Predis\Client($params);
Session::useCurrentRedisEncryptionDriver($redis, 'randomKey');
@@ -439,6 +462,7 @@ public function testUseCurrentRedisEncryptionDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseCustomDriver(): void
@@ -451,12 +475,13 @@ public function testUseCustomDriver(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUseEncryptionDriverThrowExceptionWhenMethodIncrorrect(): void
{
$this->expectException(SessionException::class);
- $this->expectExceptionMessage('Method unknowed: incorrect');
+ $this->expectExceptionMessage('Unknown method: incorrect');
Session::useFileEncryptionDriver('randomKey', 'incorrect');
}
@@ -465,23 +490,24 @@ public function testUseEncryptionDriverThrowExceptionWhenMethodIncrorrect(): voi
/**
* @runInSeparateProcess
+ *
* @throws SessionException
* @throws \Exception
*/
public function testSetOption(): void
{
$defaultOption = Session::getOption('name');
- static::assertEquals($defaultOption, ini_get('session.name'));
+ static::assertSame($defaultOption, \ini_get('session.name'));
Session::setOption('name', 'my_custom_name');
$customOption = Session::getOption('name');
- static::assertEquals('my_custom_name', $customOption);
+ static::assertSame('my_custom_name', $customOption);
Session::start(['name' => 'my_other_name']);
$customOption = Session::getOption('name');
- static::assertEquals('my_other_name', $customOption);
+ static::assertSame('my_other_name', $customOption);
}
/**
@@ -497,6 +523,7 @@ public function testSetOptionThrowException(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testGetAll(): void
@@ -507,11 +534,12 @@ public function testGetAll(): void
Session::set('a', 'b');
$sessionValues = Session::getAll();
- static::assertEquals(['a' => 'b'], $sessionValues);
+ static::assertSame(['a' => 'b'], $sessionValues);
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testFlash(): void
@@ -532,18 +560,18 @@ public function testFlash(): void
Session::setFlash($flaKey2, $flaValue2);
static::assertTrue(Session::hasFlash($flaKey1));
- static::assertEquals($flaValue1, Session::getFlash($flaKey1));
- static::assertEquals([$flaKey1 => $flaValue1, $flaKey2 => $flaValue2], Session::getAllFlash());
+ static::assertSame($flaValue1, Session::getFlash($flaKey1));
+ static::assertSame([$flaKey1 => $flaValue1, $flaKey2 => $flaValue2], Session::getAllFlash());
Session::start(['lazy_write' => '0']);
Session::keepFlash([$flaKey2]);
- static::assertEquals(['flash_data' => [$flaKey2 => $flaValue2]], $_SESSION);
+ static::assertSame(['flash_data' => [$flaKey2 => $flaValue2]], $_SESSION);
$sessionId = Session::getId();
Session::commit();
- static::assertEquals([], Session::getAllFlash());
+ static::assertSame([], Session::getAllFlash());
Session::setId($sessionId);
Session::setReadWrite();
@@ -551,7 +579,7 @@ public function testFlash(): void
static::assertEmpty($_SESSION);
static::assertTrue(Session::hasFlash($flaKey2));
- static::assertEquals($flaValue2, Session::getFlash($flaKey2));
+ static::assertSame($flaValue2, Session::getFlash($flaKey2));
static::assertTrue(Session::hasFlashKeyAndValue($flaKey2, $flaValue2));
Session::setFlash($flaKey3, $flaValue3);
@@ -561,21 +589,22 @@ public function testFlash(): void
Session::commit();
- static::assertEquals([], Session::getAllFlash());
+ static::assertSame([], Session::getAllFlash());
Session::start();
$expectedFlashValues = [$flaKey2 => $flaValue2, $flaKey3 => $flaValue3, $flaKey4 => $flaValue4];
- static::assertEquals($expectedFlashValues, Session::getAllFlash());
+ static::assertSame($expectedFlashValues, Session::getAllFlash());
static::assertEmpty($_SESSION);
Session::removeFlash($flaKey2);
Session::removeFlash($flaKey3);
- static::assertEquals([$flaKey4 => $flaValue4], Session::getAllFlash());
+ static::assertSame([$flaKey4 => $flaValue4], Session::getAllFlash());
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testRollback(): void
@@ -592,6 +621,7 @@ public function testRollback(): void
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testUnsaved(): void
@@ -604,11 +634,12 @@ public function testUnsaved(): void
static::assertTrue(Session::has('azerty'));
Session::unsaved();
Session::start();
- static::assertEquals(['a' => 'b'], $_SESSION);
+ static::assertSame(['a' => 'b'], $_SESSION);
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testRegenerate(): void
@@ -617,11 +648,12 @@ public function testRegenerate(): void
$sessionId = Session::getId();
$success = Session::regenerate();
static::assertTrue($success);
- static::assertNotEquals($sessionId, Session::getId());
+ static::assertNotSame($sessionId, Session::getId());
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testDestroy(): void
@@ -630,12 +662,13 @@ public function testDestroy(): void
$sessionId = Session::getId();
$success = Session::destroy();
static::assertTrue($success);
- static::assertNotEquals($sessionId, Session::getId());
+ static::assertNotSame($sessionId, Session::getId());
static::assertEmpty($_SESSION);
}
/**
* @runInSeparateProcess
+ *
* @throws \Exception
*/
public function testSetReadOnly(): void
@@ -647,6 +680,7 @@ public function testSetReadOnly(): void
/**
* @runInSeparateProcess
+ *
* @throws \Rancoud\Database\DatabaseException
* @throws \Exception
*/
@@ -660,8 +694,8 @@ public function testGc(): void
'database' => 'test_database'
]);
- $mysqlHost = getenv('MYSQL_HOST', true);
- $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
+ $mysqlHost = \getenv('MYSQL_HOST', true);
+ $conf->setHost(($mysqlHost !== false) ? $mysqlHost : '127.0.0.1');
$db = new \Rancoud\Database\Database($conf);
$db->truncateTables('sessions');
@@ -681,7 +715,7 @@ public function testGc(): void
$sessionId = Session::getId();
Session::commit();
- sleep(1);
+ \sleep(1);
$sql = 'UPDATE sessions SET last_access = DATE_ADD(NOW(), INTERVAL 50000 SECOND) WHERE id = :id';
$params = ['id' => $sessionId];
@@ -689,11 +723,11 @@ public function testGc(): void
Session::setOption('gc_maxlifetime', '1');
- sleep(1);
+ \sleep(1);
Session::gc();
$count = $db->count('SELECT COUNT(*) FROM sessions');
- static::assertEquals(1, $count);
+ static::assertSame(1, $count);
}
}