diff --git a/.editorconfig b/.editorconfig index f0677c3..1e716a7 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,16 +1,18 @@ -# editorconfig.org +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + root = true [*] -indent_style = space +charset = utf-8 indent_size = 4 +indent_style = space end_of_line = lf -charset = "utf-8" -trim_trailing_whitespace = true insert_final_newline = true +trim_trailing_whitespace = true + +[*.yml] +indent_size = 2 [*.md] trim_trailing_whitespace = false - -[*.{yaml,yml}] -indent_size = 2 diff --git a/.gitattributes b/.gitattributes index 926a808..aa29622 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,36 +1,10 @@ -# Define the line ending behavior of the different file extensions -# Set default behaviour, in case users don't have core.autocrlf set. -* text=auto -* text eol=lf - -# Explicitly declare text files we want to always be normalized and converted -# to native line endings on checkout. -*.php text -*.default text -*.ctp text -*.sql text -*.md text -*.po text -*.js text -*.css text -*.ini text -*.properties text -*.txt text -*.xml text -*.yml text -.htaccess text - -# Declare files that will always have CRLF line endings on checkout. -*.bat eol=crlf - -# Declare files that will always have LF line endings on checkout. -*.pem eol=lf - -# Denote all files that are truly binary and should not be modified. -*.png binary -*.jpg binary -*.gif binary -*.ico binary -*.mo binary -*.pdf binary -*.phar binary +/.github/ export-ignore +/docs/ export-ignore +/tests/ export-ignore +.editorconfig export-ignore +.gitattributes export-ignore +.gitignore export-ignore +.composer.lock export-ignore +/grumphp.yml export-ignore +/phpcs.xml export-ignore +/phpunit.xml.dist export-ignore diff --git a/.github/codecov.yml b/.github/codecov.yml new file mode 100644 index 0000000..0d79235 --- /dev/null +++ b/.github/codecov.yml @@ -0,0 +1,7 @@ +codecov: + require_ci_to_pass: yes + +coverage: + range: "90...100" + +comment: false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d651a6e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,56 @@ +name: CI + +on: + push: + branches: + - '3.x' + pull_request: + branches: + - '*' + workflow_dispatch: + +permissions: + contents: read # to fetch code (actions/checkout) + +jobs: + testsuite: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php-version: ['8.1', '8.3'] + + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + extensions: mbstring, intl + ini-values: zend.assertions = 1 + coverage: pcov + + - name: Composer install + uses: ramsey/composer-install@v3 + with: + dependency-versions: ${{ matrix.dependencies }} + composer-options: "${{ matrix.composer-options }}" + + - name: Run PHPUnit + env: + XDEBUG_MODE: coverage + run: | + if [[ '${{ matrix.php-version }}' == '8.1' ]]; then + export CODECOVERAGE=1 + vendor/bin/phpunit --display-warnings --display-incomplete --coverage-clover=coverage.xml + else + vendor/bin/phpunit --display-phpunit-deprecations --display-deprecations --display-warnings + fi + + - name: Submit code coverage + if: matrix.php-version == '8.1' + uses: codecov/codecov-action@v5 + with: + files: coverage.xml + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.gitignore b/.gitignore index 4dbd711..e9b2bcc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,12 @@ -/vendor/ -/.phpunit.result.cache - +vendor/ composer.lock +composer.phar + +/phpunit.xml +.phpunit.result.cache +.phpunit.cache + +/coverage.xml # OS generated files # ###################### @@ -27,11 +32,11 @@ Thumbs.db *.tmPreferences.cache # Eclipse .settings/* +/.project +/.buildpath # JetBrains, aka PHPStorm, IntelliJ IDEA .idea/* # NetBeans nbproject/* # Visual Studio Code .vscode -# Sass preprocessor -.sass-cache/ diff --git a/LICENSE b/LICENSE index 3c1937a..5ae5b73 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Breton Erwane +Copyright (c) 2016 Erwane Breton. (https://erwane-breton.fr/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index e776e59..aa54636 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,25 @@ -# CakePHP 4 Token plugin +# Token plugin for CakePHP + +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.txt) +[![codecov](https://codecov.io/gh/Erwane/cakephp-token/branch/3.x/graph/badge.svg?token=Ai4gc1GP9P)](https://codecov.io/gh/Erwane/cakephp-token) +[![Build Status](https://github.com/Erwane/cakephp-token/actions/workflows/ci.yml/badge.svg?branch=3.x)](https://github.com/Erwane/cakephp-contact/actions) +[![Packagist Downloads](https://img.shields.io/packagist/dt/Erwane/cakephp-token)](https://packagist.org/packages/Erwane/cakephp-token) +[![Packagist Version](https://img.shields.io/packagist/v/Erwane/cakephp-token)](https://packagist.org/packages/Erwane/cakephp-token) + +## Version map + +| branch | CakePHP core | PHP min | +|--------|--------------|---------| +| 1.x | ^3.0 | PHP 7.2 | +| 2.x | ^4.0 | PHP 7.4 | +| 3.x | ^5.0 | PHP 8.1 | ## Description This is a really "simple to use" cakephp 4 plugin for generating and reading temporaries tokens ## Installation ```bash -composer require erwane/cakephp-token:^2.0 +composer require erwane/cakephp-token bin/cake migrations migrate -p Token ``` diff --git a/composer.json b/composer.json index 666c116..c3faae7 100644 --- a/composer.json +++ b/composer.json @@ -1,54 +1,56 @@ { "name": "erwane/cakephp-token", - "description": "Easy use token in CakePHP 4", + "description": "CakePHP plugin for tokens", "type": "cakephp-plugin", "keywords": ["cakephp", "token"], "license": "MIT", "authors": [ { "name": "Erwane Breton", - "email": "erwane@phea.fr" + "email": "erwane@phea.fr", + "homepage": "https://erwane-breton.fr", + "role": "Developer" } ], + "support": { + "issues": "https://github.com/Erwane/cakephp-token/issues", + "source": "https://github.com/Erwane/cakephp-token", + "docs": "https://github.com/Erwane/cakephp-token/blob/master/README.md" + }, "require": { - "php": ">=7.4.0,<9", + "php": "^8.1", "ext-json": "*", - "cakephp/cakephp": ">=4.5,<5", - "cakephp/migrations": "^3.0" + "cakephp/cakephp": "^5.0", + "cakephp/migrations": "^4.0" }, "require-dev": { - "phpunit/phpunit": "^9.0", - "cakephp/cakephp-codesniffer" : "^3.0", - "php-parallel-lint/php-parallel-lint": "^1.2", - "phpro/grumphp": "^1.3" + "cakephp/cakephp-codesniffer": "^5.0", + "php-parallel-lint/php-parallel-lint": "^1.3", + "phpro/grumphp": "^2.0", + "phpunit/phpunit": "^10.5.5 || ^11.1.3" }, "autoload": { "psr-4": { - "Token\\": "src" + "Token\\": "src/" } }, - "autoload-dev": { "psr-4": { - "Token\\Test\\": "tests" + "Token\\Test\\": "tests/" } }, "scripts": { - "post-install-cmd": [ - "if [ $COMPOSER_DEV_MODE -eq 1 ]; then phpcs --config-set installed_paths vendor/cakephp/cakephp-codesniffer; fi" - ], - "post-update-cmd": [ - "if [ $COMPOSER_DEV_MODE -eq 1 ]; then phpcs --config-set installed_paths vendor/cakephp/cakephp-codesniffer; fi" - ], "cscheck": "vendor/bin/phpcs -p src/ tests/", - "csfix": "vendor/bin/phpcbf src/ tests/" + "csfix": "vendor/bin/phpcbf -p src/ tests/" }, "minimum-stability": "stable", + "prefer-stable": true, "config": { "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true, "phpro/grumphp": true } } diff --git a/config/Migrations/20160720184900_CreateTokens.php b/config/Migrations/20160720184900_CreateTokens.php index 38f3b86..e25bf50 100644 --- a/config/Migrations/20160720184900_CreateTokens.php +++ b/config/Migrations/20160720184900_CreateTokens.php @@ -13,25 +13,25 @@ */ class CreateTokens extends AbstractMigration { - public $autoId = false; + public bool $autoId = false; /** * Apply migrations * * @return void */ - public function change() + public function change(): void { $table = $this->table('token_tokens'); - $table->addColumn('id', 'string', [ 'limit' => 12, 'null' => false, ]) - ->addColumn('scope', 'string', [ 'limit' => 50, 'default' => null, 'null' => true, ]) - ->addColumn('scope_id', 'integer', [ 'signed' => false, 'limit' => MysqlAdapter::INT_REGULAR, 'default' => null, 'null' => true, ]) - ->addColumn('type', 'string', [ 'limit' => 64, 'null' => true, ]) - ->addColumn('content', 'text', [ 'null' => true, ]) - ->addColumn('expire', 'datetime', [ 'null' => false, ]) - ->addColumn('created', 'datetime', [ 'null' => false, ]) - ->addPrimaryKey([ 'id', ]) + $table->addColumn('id', 'string', ['limit' => 12, 'null' => false,]) + ->addColumn('scope', 'string', ['limit' => 50, 'default' => null, 'null' => true,]) + ->addColumn('scope_id', 'integer', ['signed' => false, 'limit' => MysqlAdapter::INT_REGULAR, 'default' => null, 'null' => true,]) + ->addColumn('type', 'string', ['limit' => 64, 'null' => true,]) + ->addColumn('content', 'text', ['null' => true,]) + ->addColumn('expire', 'datetime', ['null' => false,]) + ->addColumn('created', 'datetime', ['null' => false,]) + ->addPrimaryKey(['id',]) ->addIndex(['scope', 'scope_id']) ->create(); } diff --git a/config/Migrations/20170727143023_SimplifyTokens.php b/config/Migrations/20170727143023_SimplifyTokens.php index 45be06e..368ef15 100644 --- a/config/Migrations/20170727143023_SimplifyTokens.php +++ b/config/Migrations/20170727143023_SimplifyTokens.php @@ -13,7 +13,7 @@ */ class SimplifyTokens extends AbstractMigration { - public $autoId = false; + public bool $autoId = false; /** * Migration up @@ -42,9 +42,9 @@ public function down() $table = $this->table('token_tokens'); $table - ->addColumn('scope', 'string', [ 'limit' => 50, 'default' => null, 'null' => true, ]) - ->addColumn('scope_id', 'integer', [ 'signed' => false, 'limit' => MysqlAdapter::INT_REGULAR, 'default' => null, 'null' => true, ]) - ->addColumn('type', 'string', [ 'limit' => 64, 'null' => true, ]) + ->addColumn('scope', 'string', ['limit' => 50, 'default' => null, 'null' => true,]) + ->addColumn('scope_id', 'integer', ['signed' => false, 'limit' => MysqlAdapter::INT_REGULAR, 'default' => null, 'null' => true,]) + ->addColumn('type', 'string', ['limit' => 64, 'null' => true,]) ->addIndex(['scope', 'scope_id']) ->save(); } diff --git a/config/Migrations/20190708113200_BinaryId.php b/config/Migrations/20190708113200_BinaryId.php index 37689fc..02f7c58 100644 --- a/config/Migrations/20190708113200_BinaryId.php +++ b/config/Migrations/20190708113200_BinaryId.php @@ -17,7 +17,7 @@ class BinaryId extends AbstractMigration * * @return void */ - public function up() + public function up(): void { $table = $this->table('token_tokens'); diff --git a/config/Migrations/20210406113200_IdLength.php b/config/Migrations/20210406113200_IdLength.php index 166b76d..82b64df 100644 --- a/config/Migrations/20210406113200_IdLength.php +++ b/config/Migrations/20210406113200_IdLength.php @@ -17,7 +17,7 @@ class IdLength extends AbstractMigration * * @return void */ - public function up() + public function up(): void { $table = $this->table('token_tokens'); diff --git a/grumphp.yml b/grumphp.yml index bcdc54d..0dc21a8 100644 --- a/grumphp.yml +++ b/grumphp.yml @@ -7,3 +7,4 @@ grumphp: phpcs: whitelist_patterns: - /^src\/(.*\.php)/ + - /^tests\/(.*\.php)/ diff --git a/phpcs.xml b/phpcs.xml index 33076db..a66f9b9 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,5 +1,5 @@ - + @@ -7,9 +7,13 @@ - + - + src/ + tests/ + + + 0 diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1fdcf99..60082c7 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,26 +1,31 @@ - + + - + + - + + + + + - - ./tests/TestCase + + tests/TestCase - - - + + - ./src/ - ./plugins/*/src/ + src/ - - - - + diff --git a/src/Model/Entity/Token.php b/src/Model/Entity/Token.php index 1854195..1a39e1f 100644 --- a/src/Model/Entity/Token.php +++ b/src/Model/Entity/Token.php @@ -1,6 +1,18 @@ newEntity([ 'id' => $this->_uniqId($tokenLength), 'content' => $content, @@ -80,24 +95,6 @@ public function generate(array $content = [], $expire = null, int $tokenLength = return $entity->id; } - /** - * Alias for generate - * - * @param array $content Token content as array - * @param \DateTimeInterface|string|null $expire Expire date or null - * @return string Token string id - * @throws \Exception - * @deprecated Use TokensTable::generate - * @codeCoverageIgnore - * @noinspection PhpUnused - */ - public function newToken(array $content = [], $expire = null): string - { - deprecationWarning('TokensTable::newToken() is deprecated. Use TokensTable::generate().'); - - return $this->generate($content, $expire); - } - /** * Generate uniq token id * @@ -106,7 +103,7 @@ public function newToken(array $content = [], $expire = null): string */ protected function _uniqId(int $length): string { - $length = ($length > 0 && $length <= 32) ? $length : 8; + $length = $length > 0 && $length <= 32 ? $length : 8; do { // generate random @@ -115,13 +112,11 @@ protected function _uniqId(int $length): string // cleanup $clean = preg_replace('/[^A-Za-z0-9]/', '', $random); - // @codeCoverageIgnoreStart try { $randomInt = random_int(1, $length * 2); - } catch (Exception $exception) { + } catch (Exception) { $randomInt = mt_rand(1, $length * 2); } - // @codeCoverageIgnoreEnd // random part length $key = substr($clean, $randomInt, $length); @@ -132,9 +127,10 @@ protected function _uniqId(int $length): string /** * clean expired tokens + * * @return void */ - protected function _cleanExpired() + protected function _cleanExpired(): void { $this->deleteAll(['expire <' => FrozenTime::now()]); } diff --git a/src/Plugin.php b/src/Plugin.php index 15ba25f..24dae19 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -1,6 +1,18 @@ generate($content, $expire, $tokenLength); } @@ -42,7 +53,7 @@ public static function generate(array $content = [], string $expire = null, int /** * Read token from id * - * @param string $id Token string id + * @param string $id Token string id * @return \Token\Model\Entity\Token|null Entity * @deprecated Use Token::get(string $id) */ @@ -54,7 +65,7 @@ public static function read(string $id): ?TokenEntity /** * Read token from id * - * @param string $id Token string id + * @param string $id Token string id * @return \Token\Model\Entity\Token|null Entity */ public static function get(string $id): ?TokenEntity @@ -65,10 +76,10 @@ public static function get(string $id): ?TokenEntity /** * Delete token * - * @param \Token\Model\Entity\Token|string $token Token entity or string id + * @param \Token\Model\Entity\Token|string $token Token entity or string id * @return bool */ - public static function delete($token): bool + public static function delete(TokenEntity|string $token): bool { if (is_string($token)) { $token = self::get($token); diff --git a/tests/Fixture/TokensFixture.php b/tests/Fixture/TokensFixture.php index 0a4a3c9..2d9b7f5 100644 --- a/tests/Fixture/TokensFixture.php +++ b/tests/Fixture/TokensFixture.php @@ -7,19 +7,17 @@ /** * Class TokensFixture - * - * @package Token\Test\Fixture */ class TokensFixture extends TestFixture { - public $table = 'token_tokens'; + public string $table = 'token_tokens'; /** * fields property * * @var array */ - public $fields = [ + public array $fields = [ 'id' => ['type' => 'string', 'limit' => 50, 'null' => false], 'content' => ['type' => 'text', 'null' => true], 'expire' => 'datetime', diff --git a/tests/TestCase/MigrationsTest.php b/tests/TestCase/MigrationsTest.php index 1e186e2..56cc165 100644 --- a/tests/TestCase/MigrationsTest.php +++ b/tests/TestCase/MigrationsTest.php @@ -9,15 +9,10 @@ use Migrations\Migrations; /** - * Class MigrationsTest - * - * @package Token\Test\TestCase + * Migrations tests */ class MigrationsTest extends TestCase { - /** - * @inheritDoc - */ public function tearDown(): void { parent::tearDown(); @@ -27,9 +22,6 @@ public function tearDown(): void } } - /** - * @test - */ public function testMigrations() { ConnectionManager::setConfig('migration', ['url' => 'sqlite:///' . TMP . 'test_token']); @@ -45,7 +37,7 @@ public function testMigrations() } } } catch (Exception $e) { - self::assertFalse(true, "Can't cleanup database"); + $this->assertFalse(true, "Can't cleanup database"); } $migrations = new Migrations([ @@ -53,15 +45,15 @@ public function testMigrations() 'connection' => 'migration', ]); $success = $migrations->migrate(); - self::assertTrue($success); + $this->assertTrue($success); $status = $migrations->status(); - self::assertCount(4, $status); + $this->assertCount(4, $status); $schema = $cnx->getSchemaCollection()->describe('token_tokens'); // Columns - self::assertSame(['id', 'content', 'expire', 'created'], $schema->columns()); + $this->assertSame(['id', 'content', 'expire', 'created'], $schema->columns()); // Describe $columns = [ @@ -103,7 +95,7 @@ public function testMigrations() foreach ($columns as $name => $expected) { $column = $schema->getColumn($name); - self::assertSame($column, $expected, "Field `$name`: comparison fail"); + $this->assertSame($column, $expected, "Field `$name`: comparison fail"); } } } diff --git a/tests/TestCase/Model/Table/TokensTableTest.php b/tests/TestCase/Model/Table/TokensTableTest.php index 6770a33..f6638b8 100644 --- a/tests/TestCase/Model/Table/TokensTableTest.php +++ b/tests/TestCase/Model/Table/TokensTableTest.php @@ -3,15 +3,18 @@ namespace Token\Test\TestCase\Model\Table; +use Cake\ORM\Table; use Cake\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use Token\Model\Entity\Token; +use Token\Model\Table\TokensTable; /** - * Class TokensTableTest - * - * @package Token\Test\TestCase\Model\Table - * @coversDefaultClass \Token\Model\Table\TokensTable + * TokensTable tests */ +#[UsesClass(TokensTable::class)] +#[CoversClass(TokensTable::class)] class TokensTableTest extends TestCase { /** @@ -19,111 +22,66 @@ class TokensTableTest extends TestCase * * @var \Token\Model\Table\TokensTable */ - public $table; + public TokensTable|Table $table; - /** - * Fixtures - * - * @var array - */ - public $fixtures = [ + public array $fixtures = [ 'plugin.Token.Tokens', ]; - /** - * setUp method - * - * @return void - */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->table = $this->getTableLocator()->get('Token.Tokens'); } - /** - * tearDown method - * - * @return void - */ - public function tearDown(): void + protected function tearDown(): void { unset($this->table); parent::tearDown(); } - /** - * @test - * @covers ::_initializeSchema - */ public function testSchema() { $schema = $this->table->getSchema(); - self::assertSame('json', $schema->getColumnType('content')); + $this->assertSame('json', $schema->getColumnType('content')); } - /** - * @test - * @covers ::initialize - */ public function testInitialize() { - self::assertSame('token_tokens', $this->table->getTable()); - self::assertSame('id', $this->table->getPrimaryKey()); - self::assertTrue($this->table->hasBehavior('Timestamp')); + $this->assertSame('token_tokens', $this->table->getTable()); + $this->assertSame('id', $this->table->getPrimaryKey()); + $this->assertTrue($this->table->hasBehavior('Timestamp')); } - /** - * @test - * @covers ::read - * @covers ::_cleanExpired - */ public function testReadExpired() { $entity = $this->table->read('abcde456'); - self::assertNull($entity); + $this->assertNull($entity); } - /** - * @test - * @covers ::read - */ public function testReadExists() { $entity = $this->table->read('abcde123'); - self::assertInstanceOf(Token::class, $entity); - self::assertSame('abcde123', $entity->id); + $this->assertInstanceOf(Token::class, $entity); + $this->assertSame('abcde123', $entity->id); } - /** - * @test - * @covers ::read - */ public function testReadExistsBinary() { $entity = $this->table->read('abcdE123'); - self::assertNull($entity); + $this->assertNull($entity); } - /** - * @test - * @covers ::read - */ public function testReadContent() { $entity = $this->table->read('abcde789'); - self::assertCount(3, $entity->content); - self::assertArrayHasKey('email', $entity->content); - self::assertSame('erwane@phea.fr', $entity->content['email']); + $this->assertCount(3, $entity->content); + $this->assertArrayHasKey('email', $entity->content); + $this->assertSame('erwane@phea.fr', $entity->content['email']); } - /** - * @test - * @covers ::generate - * @covers ::_uniqId - */ public function testGenerateWithNoData() { // no data at all @@ -132,14 +90,10 @@ public function testGenerateWithNoData() /** @var \Token\Model\Entity\Token $entity */ $entity = $this->table->get($id); - self::assertSame($entity->expire->toDateString(), date('Y-m-d', strtotime('now + 1 day'))); - self::assertEmpty($entity->content); + $this->assertSame($entity->expire->toDateString(), date('Y-m-d', strtotime('now + 1 day'))); + $this->assertEmpty($entity->content); } - /** - * @test - * @covers ::generate - */ public function testGenerateExpire3Days() { // // expire in 3 days @@ -148,13 +102,9 @@ public function testGenerateExpire3Days() /** @var \Token\Model\Entity\Token $entity */ $entity = $this->table->get($id); - self::assertSame($entity->expire->toDateString(), date('Y-m-d', strtotime('now + 3 day'))); + $this->assertSame($entity->expire->toDateString(), date('Y-m-d', strtotime('now + 3 day'))); } - /** - * @test - * @covers ::generate - */ public function testGenerateWithData() { // content as array @@ -167,19 +117,15 @@ public function testGenerateWithData() /** @var \Token\Model\Entity\Token $entity */ $entity = $this->table->get($id); - self::assertCount(3, $entity->content); - self::assertArrayHasKey('model', $entity->content); + $this->assertCount(3, $entity->content); + $this->assertArrayHasKey('model', $entity->content); } - /** - * @test - * @covers ::generate - */ public function testGenerateWithLength() { // content as array $id = $this->table->generate(['model' => 'Users'], null, 32); - self::assertEquals(32, strlen($id)); + $this->assertEquals(32, strlen($id)); } } diff --git a/tests/TestCase/TokenTest.php b/tests/TestCase/TokenTest.php index a8bfdf1..3be7848 100644 --- a/tests/TestCase/TokenTest.php +++ b/tests/TestCase/TokenTest.php @@ -4,82 +4,58 @@ namespace Token\Test\TestCase; use Cake\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\UsesClass; use Token\Token; /** - * Class TokenTest - * - * @package Token\Test\TestCase - * @coversDefaultClass \Token\Token + * Token tests */ +#[UsesClass(Token::class)] +#[CoversClass(Token::class)] class TokenTest extends TestCase { - /** - * Fixtures - * - * @var array - */ - public $fixtures = [ + public array $fixtures = [ 'plugin.Token.Tokens', ]; - /** - * @test - * @covers ::getTable - */ public function testGetTable() { $table = Token::getTable(); - self::assertInstanceOf('Token\Model\Table\TokensTable', $table); + $this->assertInstanceOf('Token\Model\Table\TokensTable', $table); } - /** - * @test - * @covers ::get - */ public function testGetExpired() { $token = Token::get('abcde456'); - self::assertNull($token); + $this->assertNull($token); } - /** - * @test - * @covers ::get - */ public function testGetData() { $token = Token::get('abcde789'); - self::assertCount(3, $token->content); - self::assertArrayHasKey('email', $token->content); - self::assertSame('erwane@phea.fr', $token->content['email']); + $this->assertCount(3, $token->content); + $this->assertArrayHasKey('email', $token->content); + $this->assertSame('erwane@phea.fr', $token->content['email']); } - /** - * @test - * @covers ::read - */ public function testReadData() { /** @noinspection PhpDeprecationInspection */ $token = Token::read('abcde789'); - self::assertCount(3, $token->content); - self::assertArrayHasKey('email', $token->content); - self::assertSame('erwane@phea.fr', $token->content['email']); + $this->assertCount(3, $token->content); + $this->assertArrayHasKey('email', $token->content); + $this->assertSame('erwane@phea.fr', $token->content['email']); } - /** - * @test - * @covers ::generate - */ public function testGenerate() { // no data at all $id = Token::generate(); $token = Token::get($id); - self::assertSame($token->expire->toDateString(), date('Y-m-d', strtotime('now + 1 day'))); - self::assertEmpty($token->content); + $this->assertSame($token->expire->toDateString(), date('Y-m-d', strtotime('now + 1 day'))); + $this->assertEmpty($token->content); // content as array $id = Token::generate([ @@ -88,26 +64,22 @@ public function testGenerate() 'type' => 'accountValidation', ]); $token = Token::get($id); - self::assertCount(3, $token->content); - self::assertArrayHasKey('model', $token->content); + $this->assertCount(3, $token->content); + $this->assertArrayHasKey('model', $token->content); } - /** - * @test - * @covers ::delete - */ public function testDelete() { // expired token $result = Token::delete('abcde456'); - self::assertFalse($result); + $this->assertFalse($result); // exist token $result = Token::delete('abcde789'); - self::assertTrue($result); + $this->assertTrue($result); // Check if deleted $token = Token::get('abcde789'); - self::assertNull($token); + $this->assertNull($token); } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 844cbdf..b370e6f 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -2,63 +2,46 @@ declare(strict_types=1); use Cake\Core\Configure; -use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; -use Cake\Routing\Router; use Cake\Utility\Security; use Migrations\TestSuite\Migrator; -$findRoot = function ($root) { - do { - $lastRoot = $root; - $root = dirname($root); - if (is_dir($root . '/vendor/cakephp/cakephp')) { - return $root; - } - } while ($root !== $lastRoot); +require dirname(__DIR__) . '/vendor/autoload.php'; - /** @noinspection PhpUnhandledExceptionInspection */ - throw new Exception('Cannot find the root of the application, unable to run tests'); -}; -$root = $findRoot(__FILE__); -unset($findRoot); -chdir($root); - -require_once 'vendor/cakephp/cakephp/src/basics.php'; -require_once 'vendor/autoload.php'; - -$_SERVER['PHP_SELF'] = '/'; - -define("ROOT", dirname(__FILE__, 2)); +define('ROOT', dirname(__DIR__) . DS); define('TMP', sys_get_temp_dir() . DS); -const TESTS = ROOT . DS . 'tests' . DS; -const CAKE_CORE_INCLUDE_PATH = ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp'; - -if (!defined('TEST_APP')) { - define('TEST_APP', TESTS . 'test_app' . DS); -} - -const APP = ROOT . 'App' . DS; +// const CORE_PATH = ROOT . 'vendor' . DS . 'cakephp' . DS . 'cakephp' . DS; +// const CAKE = CORE_PATH . 'src' . DS; +// require CAKE . 'Core/functions_global.php'; Configure::write('debug', true); -Configure::write('App', [ - 'namespace' => 'TestApp', - 'paths' => [ - 'plugins' => [ROOT . 'Plugin' . DS], - 'templates' => [ROOT . 'templates' . DS], - ], -]); +Configure::write('App.encoding', 'UTF-8'); +Security::setSalt('a-long-but-not-random-value'); +// Ensure default test connection is defined if (!getenv('DB_URL')) { putenv('DB_URL=sqlite:///:memory:'); } - ConnectionManager::setConfig('test', ['url' => getenv('DB_URL')]); -Router::reload(); -Security::setSalt('oJt5xYtBOSCLtlra3s5xgs96USjPLNJ8np657QSI4zhksqOh'); - -Plugin::getCollection()->add(new \Token\Plugin()); -$_SERVER['PHP_SELF'] = '/'; +// Configure::write('App', [ +// 'namespace' => 'TestApp', +// 'paths' => [ +// 'plugins' => [ROOT . 'Plugin' . DS], +// 'templates' => [ROOT . 'templates' . DS], +// ], +// ]); +// +// if (!getenv('DB_URL')) { +// putenv('DB_URL=sqlite:///:memory:'); +// } +// +// ConnectionManager::setConfig('test', ['url' => getenv('DB_URL')]); +// Router::reload(); +// Security::setSalt('oJt5xYtBOSCLtlra3s5xgs96USjPLNJ8np657QSI4zhksqOh'); +// +// Plugin::getCollection()->add(new \Token\Plugin()); +// +// $_SERVER['PHP_SELF'] = '/'; (new Migrator())->run();