From 9826d49a323bdb25f74fef032b34d9f34b4b6ba7 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 15 Jul 2018 16:20:00 -0400 Subject: [PATCH 01/70] Changed the dotload to "overload" to ensure that new vars from .env are always active --- library/Core/autoload.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/Core/autoload.php b/library/Core/autoload.php index 0c6621d4..b143c64d 100644 --- a/library/Core/autoload.php +++ b/library/Core/autoload.php @@ -25,4 +25,4 @@ require appPath('/vendor/autoload.php'); // Load environment -(new Dotenv(appPath()))->load(); +(new Dotenv(appPath()))->overload(); From 9a72abdb58b64982bea2a4aa836b1440ce0911ca Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 15 Jul 2018 17:54:24 -0400 Subject: [PATCH 02/70] Added companies table, model, migration and tests --- library/Models/Companies.php | 55 +++++++++++++++ .../20180715202028_add_companies_table.php | 69 +++++++++++++++++++ .../library/Models/CompaniesCest.php | 43 ++++++++++++ .../library/Models/PrefixesCest.php | 31 +++++++++ .../integration/library/Models/UsersCest.php | 22 ++++++ 5 files changed, 220 insertions(+) create mode 100644 library/Models/Companies.php create mode 100644 storage/db/migrations/20180715202028_add_companies_table.php create mode 100644 tests/integration/library/Models/CompaniesCest.php create mode 100644 tests/integration/library/Models/PrefixesCest.php diff --git a/library/Models/Companies.php b/library/Models/Companies.php new file mode 100644 index 00000000..7752ecbc --- /dev/null +++ b/library/Models/Companies.php @@ -0,0 +1,55 @@ + + */ + public function getModelFilters(): array + { + return [ + 'com_id' => Filter::FILTER_ABSINT, + 'com_name' => Filter::FILTER_STRING, + 'com_address' => Filter::FILTER_STRING, + 'com_city' => Filter::FILTER_STRING, + 'com_telephone' => Filter::FILTER_STRING, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_companies'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'com'; + } +} diff --git a/storage/db/migrations/20180715202028_add_companies_table.php b/storage/db/migrations/20180715202028_add_companies_table.php new file mode 100644 index 00000000..21299bc1 --- /dev/null +++ b/storage/db/migrations/20180715202028_add_companies_table.php @@ -0,0 +1,69 @@ +table( + 'co_companies', + [ + 'id' => 'com_id', + 'signed' => false, + ] + ); + + $table + ->addColumn( + 'com_name', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'com_address', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'com_city', + 'string', + [ + 'limit' => 64, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'com_telephone', + 'string', + [ + 'limit' => 24, + 'null' => false, + 'default' => '', + ] + ) + ->addIndex('com_name') + ->addIndex('com_city') + ->save(); + + $this->execute( + 'ALTER TABLE co_companies ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_companies'); + } +} diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php new file mode 100644 index 00000000..00c9c355 --- /dev/null +++ b/tests/integration/library/Models/CompaniesCest.php @@ -0,0 +1,43 @@ +haveModelDefinition( + Companies::class, + [ + 'com_id', + 'com_name', + 'com_address', + 'com_city', + 'com_telephone', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new Companies(); + $expected = [ + 'com_id' => Filter::FILTER_ABSINT, + 'com_name' => Filter::FILTER_STRING, + 'com_address' => Filter::FILTER_STRING, + 'com_city' => Filter::FILTER_STRING, + 'com_telephone' => Filter::FILTER_STRING, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new Companies(); + $I->assertEquals('com', $model->getTablePrefix()); + } +} diff --git a/tests/integration/library/Models/PrefixesCest.php b/tests/integration/library/Models/PrefixesCest.php new file mode 100644 index 00000000..069346b0 --- /dev/null +++ b/tests/integration/library/Models/PrefixesCest.php @@ -0,0 +1,31 @@ +getTablePrefix(); + $count++; + } + + $I->assertEquals($count, count($prefixes)); + } +} diff --git a/tests/integration/library/Models/UsersCest.php b/tests/integration/library/Models/UsersCest.php index 11489517..035554b0 100644 --- a/tests/integration/library/Models/UsersCest.php +++ b/tests/integration/library/Models/UsersCest.php @@ -6,6 +6,7 @@ use Lcobucci\JWT\ValidationData; use Niden\Models\Users; use Niden\Traits\TokenTrait; +use Phalcon\Filter; class UsersCest { @@ -27,6 +28,27 @@ public function validateModel(IntegrationTester $I) ); } + public function validateFilters(IntegrationTester $I) + { + $model = new Users(); + $expected = [ + 'usr_id' => Filter::FILTER_ABSINT, + 'usr_status_flag' => Filter::FILTER_ABSINT, + 'usr_username' => Filter::FILTER_STRING, + 'usr_password' => Filter::FILTER_STRING, + 'usr_issuer' => Filter::FILTER_STRING, + 'usr_token_password' => Filter::FILTER_STRING, + 'usr_token_id' => Filter::FILTER_STRING, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new Users(); + $I->assertEquals('usr', $model->getTablePrefix()); + } + public function checkValidationData(IntegrationTester $I) { /** @var Users $user */ From 4d762736701724097d4a671ceea573591fd92ba2 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 15 Jul 2018 18:24:45 -0400 Subject: [PATCH 03/70] Added products table, model, migration and tests --- library/Models/Products.php | 53 ++++++++++++++ .../20180715221034_add_products_table.php | 73 +++++++++++++++++++ .../library/Models/ProductsCest.php | 43 +++++++++++ 3 files changed, 169 insertions(+) create mode 100644 library/Models/Products.php create mode 100644 storage/db/migrations/20180715221034_add_products_table.php create mode 100644 tests/integration/library/Models/ProductsCest.php diff --git a/library/Models/Products.php b/library/Models/Products.php new file mode 100644 index 00000000..d823c1b7 --- /dev/null +++ b/library/Models/Products.php @@ -0,0 +1,53 @@ + + */ + public function getModelFilters(): array + { + return [ + 'prd_id' => Filter::FILTER_ABSINT, + 'prd_name' => Filter::FILTER_STRING, + 'prd_description' => Filter::FILTER_STRING, + 'prd_quantity' => Filter::FILTER_ABSINT, + 'prd_price' => Filter::FILTER_FLOAT, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_products'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'prd'; + } +} diff --git a/storage/db/migrations/20180715221034_add_products_table.php b/storage/db/migrations/20180715221034_add_products_table.php new file mode 100644 index 00000000..28c609c3 --- /dev/null +++ b/storage/db/migrations/20180715221034_add_products_table.php @@ -0,0 +1,73 @@ +table( + 'co_products', + [ + 'id' => 'prd_id', + 'signed' => false, + ] + ); + + $table + ->addColumn( + 'prd_name', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'prd_description', + 'string', + [ + 'limit' => 256, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'prd_quantity', + 'integer', + [ + 'limit' => 11, + 'null' => false, + 'signed' => false, + 'default' => 0, + ] + ) + ->addColumn( + 'prd_price', + 'decimal', + [ + 'precision' => 10, + 'scale' => 2, + 'null' => false, + 'signed' => false, + 'default' => 0, + ] + ) + ->addIndex('prd_name') + ->addIndex('prd_quantity') + ->addIndex('prd_price') + ->save(); + + $this->execute( + 'ALTER TABLE co_products ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_products'); + } +} diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php new file mode 100644 index 00000000..2107225b --- /dev/null +++ b/tests/integration/library/Models/ProductsCest.php @@ -0,0 +1,43 @@ +haveModelDefinition( + Products::class, + [ + 'prd_id', + 'prd_name', + 'prd_description', + 'prd_quantity', + 'prd_price', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new Products(); + $expected = [ + 'prd_id' => Filter::FILTER_ABSINT, + 'prd_name' => Filter::FILTER_STRING, + 'prd_description' => Filter::FILTER_STRING, + 'prd_quantity' => Filter::FILTER_ABSINT, + 'prd_price' => Filter::FILTER_FLOAT, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new Products(); + $I->assertEquals('prd', $model->getTablePrefix()); + } +} From 51e472ac4651dc933e5b50893ae56dc581410927 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 19:19:41 -0400 Subject: [PATCH 04/70] Added migrations for product type tables, individuals, individual types and companies_x_products --- ...20180717231009_add_product_types_table.php | 50 +++++++++ .../20180717231024_add_individuals_table.php | 100 ++++++++++++++++++ ...80717231029_add_individual_types_table.php | 56 ++++++++++ ...231052_add_companies_to_products_table.php | 50 +++++++++ 4 files changed, 256 insertions(+) create mode 100644 storage/db/migrations/20180717231009_add_product_types_table.php create mode 100644 storage/db/migrations/20180717231024_add_individuals_table.php create mode 100644 storage/db/migrations/20180717231029_add_individual_types_table.php create mode 100644 storage/db/migrations/20180717231052_add_companies_to_products_table.php diff --git a/storage/db/migrations/20180717231009_add_product_types_table.php b/storage/db/migrations/20180717231009_add_product_types_table.php new file mode 100644 index 00000000..42802266 --- /dev/null +++ b/storage/db/migrations/20180717231009_add_product_types_table.php @@ -0,0 +1,50 @@ +table( + 'co_product_types', + [ + 'id' => 'prt_id', + 'signed' => false, + ] + ); + + $table + ->addColumn( + 'prt_name', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'prt_description', + 'string', + [ + 'limit' => 256, + 'null' => false, + 'default' => '', + ] + ) + ->addIndex('prt_name') + ->save(); + + $this->execute( + 'ALTER TABLE co_product_types ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_product_types'); + } +} diff --git a/storage/db/migrations/20180717231024_add_individuals_table.php b/storage/db/migrations/20180717231024_add_individuals_table.php new file mode 100644 index 00000000..9971f433 --- /dev/null +++ b/storage/db/migrations/20180717231024_add_individuals_table.php @@ -0,0 +1,100 @@ +table( + 'co_individuals', + [ + 'id' => 'ind_id', + 'signed' => false, + ] + ); + $table + ->addColumn( + 'ind_com_id', + 'integer', + [ + 'signed' => false, + 'limit' => 11, + 'null' => false, + 'default' => 0, + ] + ) + ->addColumn( + 'ind_idt_id', + 'integer', + [ + 'signed' => false, + 'limit' => 11, + 'null' => false, + 'default' => 0, + ] + ) + ->addColumn( + 'ind_name_prefix', + 'string', + [ + 'limit' => 16, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'ind_name_first', + 'string', + [ + 'limit' => 64, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'ind_name_middle', + 'string', + [ + 'limit' => 64, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'ind_name_last', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'ind_name_suffix', + 'string', + [ + 'limit' => 16, + 'null' => false, + 'default' => '', + ] + ) + ->addIndex('ind_com_id') + ->addIndex('ind_idt_id') + ->addIndex('ind_name_first') + ->addIndex('ind_name_middle') + ->addIndex('ind_name_last') + ->save(); + + $this->execute( + 'ALTER TABLE co_individuals ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_employees'); + } +} diff --git a/storage/db/migrations/20180717231029_add_individual_types_table.php b/storage/db/migrations/20180717231029_add_individual_types_table.php new file mode 100644 index 00000000..dc7f49a4 --- /dev/null +++ b/storage/db/migrations/20180717231029_add_individual_types_table.php @@ -0,0 +1,56 @@ +table( + 'co_companies_x_products', + [ + 'id' => false, + 'primary_key' => [ + 'cxp_com_id', + 'cxp_prd_id', + ], + ] + ); + + $table + ->addColumn( + 'cxp_com_id', + 'integer', + [ + 'signed' => false, + 'limit' => 11, + 'null' => false, + 'default' => 0, + ] + ) + ->addColumn( + 'cxp_prd_id', + 'integer', + [ + 'signed' => false, + 'limit' => 11, + 'null' => false, + 'default' => 0, + ] + ) + ->addIndex('cxp_com_id') + ->addIndex('cxp_prd_id') + ->save(); + + $this->execute( + 'ALTER TABLE co_companies_x_products ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_companies_x_products'); + } +} diff --git a/storage/db/migrations/20180717231052_add_companies_to_products_table.php b/storage/db/migrations/20180717231052_add_companies_to_products_table.php new file mode 100644 index 00000000..9600bce6 --- /dev/null +++ b/storage/db/migrations/20180717231052_add_companies_to_products_table.php @@ -0,0 +1,50 @@ +table( + 'co_individual_types', + [ + 'id' => 'idt_id', + 'signed' => false, + ] + ); + + $table + ->addColumn( + 'idt_name', + 'string', + [ + 'limit' => 128, + 'null' => false, + 'default' => '', + ] + ) + ->addColumn( + 'idt_description', + 'string', + [ + 'limit' => 256, + 'null' => false, + 'default' => '', + ] + ) + ->addIndex('idt_name') + ->save(); + + $this->execute( + 'ALTER TABLE co_individual_types ' . + 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' + ); + } + + public function down() + { + $this->dropTable('co_individual_types'); + } +} From c8b46258d73b780eb2d57e392208d0bf62480a1f Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 19:23:41 -0400 Subject: [PATCH 05/70] Added product type id in products; corrected migrations --- ...80717231029_add_individual_types_table.php | 34 ++++++++----------- ...231052_add_companies_to_products_table.php | 34 +++++++++++-------- ...717232102_add_product_type_to_products.php | 33 ++++++++++++++++++ 3 files changed, 67 insertions(+), 34 deletions(-) create mode 100644 storage/db/migrations/20180717232102_add_product_type_to_products.php diff --git a/storage/db/migrations/20180717231029_add_individual_types_table.php b/storage/db/migrations/20180717231029_add_individual_types_table.php index dc7f49a4..f5709504 100644 --- a/storage/db/migrations/20180717231029_add_individual_types_table.php +++ b/storage/db/migrations/20180717231029_add_individual_types_table.php @@ -8,49 +8,43 @@ class AddIndividualTypesTable extends AbstractMigration public function up() { $table = $this->table( - 'co_companies_x_products', + 'co_individual_types', [ - 'id' => false, - 'primary_key' => [ - 'cxp_com_id', - 'cxp_prd_id', - ], + 'id' => 'idt_id', + 'signed' => false, ] ); $table ->addColumn( - 'cxp_com_id', - 'integer', + 'idt_name', + 'string', [ - 'signed' => false, - 'limit' => 11, + 'limit' => 128, 'null' => false, - 'default' => 0, + 'default' => '', ] ) ->addColumn( - 'cxp_prd_id', - 'integer', + 'idt_description', + 'string', [ - 'signed' => false, - 'limit' => 11, + 'limit' => 256, 'null' => false, - 'default' => 0, + 'default' => '', ] ) - ->addIndex('cxp_com_id') - ->addIndex('cxp_prd_id') + ->addIndex('idt_name') ->save(); $this->execute( - 'ALTER TABLE co_companies_x_products ' . + 'ALTER TABLE co_individual_types ' . 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' ); } public function down() { - $this->dropTable('co_companies_x_products'); + $this->dropTable('co_individual_types'); } } diff --git a/storage/db/migrations/20180717231052_add_companies_to_products_table.php b/storage/db/migrations/20180717231052_add_companies_to_products_table.php index 9600bce6..44e7f91c 100644 --- a/storage/db/migrations/20180717231052_add_companies_to_products_table.php +++ b/storage/db/migrations/20180717231052_add_companies_to_products_table.php @@ -8,43 +8,49 @@ class AddCompaniesToProductsTable extends AbstractMigration public function up() { $table = $this->table( - 'co_individual_types', + 'co_companies_x_products', [ - 'id' => 'idt_id', - 'signed' => false, + 'id' => false, + 'primary_key' => [ + 'cxp_com_id', + 'cxp_prd_id', + ], ] ); $table ->addColumn( - 'idt_name', - 'string', + 'cxp_com_id', + 'integer', [ - 'limit' => 128, + 'signed' => false, + 'limit' => 11, 'null' => false, - 'default' => '', + 'default' => 0, ] ) ->addColumn( - 'idt_description', - 'string', + 'cxp_prd_id', + 'integer', [ - 'limit' => 256, + 'signed' => false, + 'limit' => 11, 'null' => false, - 'default' => '', + 'default' => 0, ] ) - ->addIndex('idt_name') + ->addIndex('cxp_com_id') + ->addIndex('cxp_prd_id') ->save(); $this->execute( - 'ALTER TABLE co_individual_types ' . + 'ALTER TABLE co_companies_x_products ' . 'CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' ); } public function down() { - $this->dropTable('co_individual_types'); + $this->dropTable('co_companies_x_products'); } } diff --git a/storage/db/migrations/20180717232102_add_product_type_to_products.php b/storage/db/migrations/20180717232102_add_product_type_to_products.php new file mode 100644 index 00000000..9a01c1f0 --- /dev/null +++ b/storage/db/migrations/20180717232102_add_product_type_to_products.php @@ -0,0 +1,33 @@ +table('co_products'); + + $table + ->addColumn( + 'prd_prt_id', + 'integer', + [ + 'signed' => false, + 'limit' => 11, + 'null' => false, + 'default' => 0, + 'after' => 'prd_id', + ] + ) + ->addIndex('prd_id') + ->save(); + } + + public function down() + { + $table = $this->table('co_products'); + $table->removeColumn('prd_prt_id'); + } +} From 827b733dd681c3738fc7ac0afe1a87bc7eb5f3ed Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 19:30:31 -0400 Subject: [PATCH 06/70] Added relationship constants --- library/Constants/Relationships.php | 15 +++++++++++++++ .../library/Constants/RelationshipsCest.php | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 library/Constants/Relationships.php create mode 100644 tests/unit/library/Constants/RelationshipsCest.php diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php new file mode 100644 index 00000000..e1af8a57 --- /dev/null +++ b/library/Constants/Relationships.php @@ -0,0 +1,15 @@ +assertEquals('company', Relationships::COMPANY); + $I->assertEquals('individual', Relationships::INDIVIDUAL); + $I->assertEquals('individualType', Relationships::INDIVIDUAL_TYPE); + $I->assertEquals('individuals', Relationships::INDIVIDUALS); + $I->assertEquals('product', Relationships::PRODUCT); + $I->assertEquals('productType', Relationships::PRODUCT_TYPE); + } +} From 5354099dc514af91bb77f39fb9db1e7e1ce576f9 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 19:38:37 -0400 Subject: [PATCH 07/70] Adjusted products model; added product types model and tests --- library/Models/ProductTypes.php | 69 +++++++++++++++++++ library/Models/Products.php | 21 +++++- .../library/Models/ProductTypesCest.php | 40 +++++++++++ .../library/Models/ProductsCest.php | 2 + 4 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 library/Models/ProductTypes.php create mode 100644 tests/integration/library/Models/ProductTypesCest.php diff --git a/library/Models/ProductTypes.php b/library/Models/ProductTypes.php new file mode 100644 index 00000000..09e2ced5 --- /dev/null +++ b/library/Models/ProductTypes.php @@ -0,0 +1,69 @@ +belongsTo( + 'prt_id', + Products::class, + 'prd_prt_id', + [ + 'alias' => Relationships::PRODUCT, + 'reusable' => true, + ] + ); + + parent::initialize(); + } + + /** + * Model filters + * + * @return array + */ + public function getModelFilters(): array + { + return [ + 'prt_id' => Filter::FILTER_ABSINT, + 'prt_name' => Filter::FILTER_STRING, + 'prt_description' => Filter::FILTER_STRING, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_product_types'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'prt'; + } +} diff --git a/library/Models/Products.php b/library/Models/Products.php index d823c1b7..9c15ae91 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -4,7 +4,7 @@ namespace Niden\Models; -use Niden\Traits\TokenTrait; +use Niden\Constants\Relationships; use Niden\Mvc\Model\AbstractModel; use Phalcon\Filter; @@ -15,6 +15,24 @@ */ class Products extends AbstractModel { + /** + * Initialize relationships and model properties + */ + public function initialize() + { + $this->hasOne( + 'prd_prt_id', + ProductTypes::class, + 'prt_id', + [ + 'alias' => Relationships::PRODUCT_TYPE, + 'reusable' => true, + ] + ); + + parent::initialize(); + } + /** * Model filters * @@ -24,6 +42,7 @@ public function getModelFilters(): array { return [ 'prd_id' => Filter::FILTER_ABSINT, + 'prd_prt_id' => Filter::FILTER_ABSINT, 'prd_name' => Filter::FILTER_STRING, 'prd_description' => Filter::FILTER_STRING, 'prd_quantity' => Filter::FILTER_ABSINT, diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php new file mode 100644 index 00000000..8ecafcc9 --- /dev/null +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -0,0 +1,40 @@ +haveModelDefinition( + ProductTypes::class, + [ + 'prt_id', + 'prt_name', + 'prt_description', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new ProductTypes(); + $expected = [ + 'prt_id' => Filter::FILTER_ABSINT, + 'prt_name' => Filter::FILTER_STRING, + 'prt_description' => Filter::FILTER_STRING, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new ProductTypes(); + $I->assertEquals('prt', $model->getTablePrefix()); + } +} diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index 2107225b..d89436b0 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -14,6 +14,7 @@ public function validateModel(IntegrationTester $I) Products::class, [ 'prd_id', + 'prd_prt_id', 'prd_name', 'prd_description', 'prd_quantity', @@ -27,6 +28,7 @@ public function validateFilters(IntegrationTester $I) $model = new Products(); $expected = [ 'prd_id' => Filter::FILTER_ABSINT, + 'prd_prt_id' => Filter::FILTER_ABSINT, 'prd_name' => Filter::FILTER_STRING, 'prd_description' => Filter::FILTER_STRING, 'prd_quantity' => Filter::FILTER_ABSINT, From 050cc387ef6f08bc69e90d1c11f955844d8c4385 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 19:53:18 -0400 Subject: [PATCH 08/70] Adjusted relationships; added individual types/individuals models --- library/Constants/Relationships.php | 1 + library/Models/Companies.php | 30 ++++++- library/Models/IndividualTypes.php | 69 +++++++++++++++ library/Models/Individuals.php | 84 +++++++++++++++++++ .../library/Models/IndividualTypesCest.php | 39 +++++++++ .../library/Models/ProductTypesCest.php | 1 - 6 files changed, 221 insertions(+), 3 deletions(-) create mode 100644 library/Models/IndividualTypes.php create mode 100644 library/Models/Individuals.php create mode 100644 tests/integration/library/Models/IndividualTypesCest.php diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php index e1af8a57..b63eb44e 100644 --- a/library/Constants/Relationships.php +++ b/library/Constants/Relationships.php @@ -12,4 +12,5 @@ class Relationships const INDIVIDUALS = 'individuals'; const PRODUCT = 'product'; const PRODUCT_TYPE = 'productType'; + const PRODUCTS = 'products'; } diff --git a/library/Models/Companies.php b/library/Models/Companies.php index 7752ecbc..ea837c11 100644 --- a/library/Models/Companies.php +++ b/library/Models/Companies.php @@ -4,7 +4,7 @@ namespace Niden\Models; -use Niden\Traits\TokenTrait; +use Niden\Constants\Relationships; use Niden\Mvc\Model\AbstractModel; use Phalcon\Filter; @@ -15,7 +15,33 @@ */ class Companies extends AbstractModel { - use TokenTrait; + /** + * Initialize relationships and model properties + */ + public function initialize() + { + $this->hasMany( + 'com_id', + Individuals::class, + 'ind_com_id', + [ + 'alias' => Relationships::INDIVIDUALS, + 'reusable' => true, + ] + ); + + $this->hasMany( + 'com_id', + Products::class, + 'prd_com_id', + [ + 'alias' => Relationships::PRODUCTS, + 'reusable' => true, + ] + ); + + parent::initialize(); + } /** * Model filters diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php new file mode 100644 index 00000000..34c901f5 --- /dev/null +++ b/library/Models/IndividualTypes.php @@ -0,0 +1,69 @@ +belongsTo( + 'idt_id', + Individuals::class, + 'ind_idt_id', + [ + 'alias' => Relationships::INDIVIDUAL, + 'reusable' => true, + ] + ); + + parent::initialize(); + } + + /** + * Model filters + * + * @return array + */ + public function getModelFilters(): array + { + return [ + 'idt_id' => Filter::FILTER_ABSINT, + 'idt_name' => Filter::FILTER_STRING, + 'idt_description' => Filter::FILTER_STRING, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_individual_types'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'idt'; + } +} diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php new file mode 100644 index 00000000..2710620f --- /dev/null +++ b/library/Models/Individuals.php @@ -0,0 +1,84 @@ +belongsTo( + 'ind_com_id', + Companies::class, + 'com_id', + [ + 'alias' => Relationships::COMPANY, + 'reusable' => true, + ] + ); + + $this->hasOne( + 'ind_idt_id', + IndividualTypes::class, + 'idt_id', + [ + 'alias' => Relationships::INDIVIDUAL_TYPE, + 'reusable' => true, + ] + ); + + parent::initialize(); + } + + /** + * Model filters + * + * @return array + */ + public function getModelFilters(): array + { + return [ + 'ind_id' => Filter::FILTER_ABSINT, + 'ind_com_id' => Filter::FILTER_ABSINT, + 'ind_idt_id' => Filter::FILTER_ABSINT, + 'ind_name_prefix' => Filter::FILTER_STRING, + 'ind_name_first' => Filter::FILTER_STRING, + 'ind_name_middle' => Filter::FILTER_STRING, + 'ind_name_last' => Filter::FILTER_STRING, + 'ind_name_suffix' => Filter::FILTER_STRING, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_individuals'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'ind'; + } +} diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php new file mode 100644 index 00000000..fed89cb1 --- /dev/null +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -0,0 +1,39 @@ +haveModelDefinition( + IndividualTypes::class, + [ + 'idt_id', + 'idt_name', + 'idt_description', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new IndividualTypes(); + $expected = [ + 'idt_id' => Filter::FILTER_ABSINT, + 'idt_name' => Filter::FILTER_STRING, + 'idt_description' => Filter::FILTER_STRING, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new IndividualTypes(); + $I->assertEquals('idt', $model->getTablePrefix()); + } +} diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index 8ecafcc9..fdbd165f 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -3,7 +3,6 @@ namespace Niden\Tests\integration\library\Models; use IntegrationTester; -use Niden\Models\Products; use Niden\Models\ProductTypes; use Phalcon\Filter; From 88310128d41e283720b197d5a9de8e7c7dfb7264 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 17 Jul 2018 20:45:36 -0400 Subject: [PATCH 09/70] Added helper method to read relationships; Added relationship tests for models --- library/Models/Products.php | 10 +++ tests/_support/Helper/Integration.php | 28 +++++++++ .../library/Models/CompaniesCest.php | 13 ++++ .../library/Models/IndividualTypesCest.php | 11 ++++ .../library/Models/IndividualsCest.php | 62 +++++++++++++++++++ .../library/Models/ProductTypesCest.php | 11 ++++ .../library/Models/ProductsCest.php | 13 ++++ .../integration/library/Models/UsersCest.php | 6 ++ .../library/Constants/RelationshipsCest.php | 1 + 9 files changed, 155 insertions(+) create mode 100644 tests/integration/library/Models/IndividualsCest.php diff --git a/library/Models/Products.php b/library/Models/Products.php index 9c15ae91..f6ab1a18 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -20,6 +20,16 @@ class Products extends AbstractModel */ public function initialize() { + $this->belongsTo( + 'prd_com_id', + Companies::class, + 'com_id', + [ + 'alias' => Relationships::COMPANY, + 'reusable' => true, + ] + ); + $this->hasOne( 'prd_prt_id', ProductTypes::class, diff --git a/tests/_support/Helper/Integration.php b/tests/_support/Helper/Integration.php index 175d019f..7dd45049 100644 --- a/tests/_support/Helper/Integration.php +++ b/tests/_support/Helper/Integration.php @@ -64,6 +64,34 @@ public function grabFromDi(string $name) return $this->diContainer->get($name); } + /** + * Returns the relationships that a model has + * + * @param string $class + * + * @return array + */ + public function getModelRelationships(string $class): array + { + /** @var AbstractModel $class */ + $model = new $class(); + $manager = $model->getModelsManager(); + $relationships = $manager->getRelations($class); + + $data = []; + foreach ($relationships as $relationship) { + $data[] = [ + $relationship->getType(), + $relationship->getFields(), + $relationship->getReferencedModel(), + $relationship->getReferencedFields(), + $relationship->getOptions(), + ]; + } + + return $data; + } + /** * Get a record from $modelName with fields provided * diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index 00c9c355..90fc9cb7 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -3,7 +3,10 @@ namespace Niden\Tests\integration\library\Models; use IntegrationTester; +use Niden\Constants\Relationships; use Niden\Models\Companies; +use Niden\Models\Individuals; +use Niden\Models\Products; use Phalcon\Filter; class CompaniesCest @@ -40,4 +43,14 @@ public function validatePrefix(IntegrationTester $I) $model = new Companies(); $I->assertEquals('com', $model->getTablePrefix()); } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(Companies::class); + $expected = [ + [2, 'com_id', Individuals::class, 'ind_com_id', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], + [2, 'com_id', Products::class, 'prd_com_id', ['alias' => Relationships::PRODUCTS, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } } diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index fed89cb1..2bee0418 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -3,6 +3,8 @@ namespace Niden\Tests\integration\library\Models; use IntegrationTester; +use Niden\Constants\Relationships; +use Niden\Models\Individuals; use Niden\Models\IndividualTypes; use Phalcon\Filter; @@ -36,4 +38,13 @@ public function validatePrefix(IntegrationTester $I) $model = new IndividualTypes(); $I->assertEquals('idt', $model->getTablePrefix()); } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(IndividualTypes::class); + $expected = [ + [0, 'idt_id', Individuals::class, 'ind_idt_id', ['alias' => Relationships::INDIVIDUAL, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } } diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php new file mode 100644 index 00000000..ecb9b605 --- /dev/null +++ b/tests/integration/library/Models/IndividualsCest.php @@ -0,0 +1,62 @@ +haveModelDefinition( + Individuals::class, + [ + 'ind_id', + 'ind_com_id', + 'ind_idt_id', + 'ind_name_prefix', + 'ind_name_first', + 'ind_name_middle', + 'ind_name_last', + 'ind_name_suffix', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new Individuals(); + $expected = [ + 'ind_id' => Filter::FILTER_ABSINT, + 'ind_com_id' => Filter::FILTER_ABSINT, + 'ind_idt_id' => Filter::FILTER_ABSINT, + 'ind_name_prefix' => Filter::FILTER_STRING, + 'ind_name_first' => Filter::FILTER_STRING, + 'ind_name_middle' => Filter::FILTER_STRING, + 'ind_name_last' => Filter::FILTER_STRING, + 'ind_name_suffix' => Filter::FILTER_STRING, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new Individuals(); + $I->assertEquals('ind', $model->getTablePrefix()); + } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(Individuals::class); + $expected = [ + [0, 'ind_com_id', Companies::class, 'com_id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [1, 'ind_idt_id', IndividualTypes::class, 'idt_id', ['alias' => Relationships::INDIVIDUAL_TYPE, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } +} diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index fdbd165f..a1ad72ab 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -3,6 +3,8 @@ namespace Niden\Tests\integration\library\Models; use IntegrationTester; +use Niden\Constants\Relationships; +use Niden\Models\Products; use Niden\Models\ProductTypes; use Phalcon\Filter; @@ -36,4 +38,13 @@ public function validatePrefix(IntegrationTester $I) $model = new ProductTypes(); $I->assertEquals('prt', $model->getTablePrefix()); } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(ProductTypes::class); + $expected = [ + [0, 'prt_id', Products::class, 'prd_prt_id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } } diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index d89436b0..5f0bd038 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -3,7 +3,10 @@ namespace Niden\Tests\integration\library\Models; use IntegrationTester; +use Niden\Constants\Relationships; +use Niden\Models\Companies; use Niden\Models\Products; +use Niden\Models\ProductTypes; use Phalcon\Filter; class ProductsCest @@ -42,4 +45,14 @@ public function validatePrefix(IntegrationTester $I) $model = new Products(); $I->assertEquals('prd', $model->getTablePrefix()); } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(Products::class); + $expected = [ + [0, 'prd_com_id', Companies::class, 'com_id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [1, 'prd_prt_id', ProductTypes::class, 'prt_id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } } diff --git a/tests/integration/library/Models/UsersCest.php b/tests/integration/library/Models/UsersCest.php index 035554b0..58a212ff 100644 --- a/tests/integration/library/Models/UsersCest.php +++ b/tests/integration/library/Models/UsersCest.php @@ -72,4 +72,10 @@ public function checkValidationData(IntegrationTester $I) $I->assertEquals($validationData, $user->getValidationData()); } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(Users::class); + $I->assertEquals(0, count($actual)); + } } diff --git a/tests/unit/library/Constants/RelationshipsCest.php b/tests/unit/library/Constants/RelationshipsCest.php index 8ee64f87..9312e3e4 100644 --- a/tests/unit/library/Constants/RelationshipsCest.php +++ b/tests/unit/library/Constants/RelationshipsCest.php @@ -15,5 +15,6 @@ public function checkConstants(CliTester $I) $I->assertEquals('individuals', Relationships::INDIVIDUALS); $I->assertEquals('product', Relationships::PRODUCT); $I->assertEquals('productType', Relationships::PRODUCT_TYPE); + $I->assertEquals('products', Relationships::PRODUCTS); } } From 184afe13b1fcfb266b8040e5d32436e8d3d33369 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 10:59:10 -0400 Subject: [PATCH 10/70] Added validator for company records --- library/Validation/CompaniesValidator.php | 24 ++++++++++++++++ .../Validation/CompaniesValidatorCest.php | 28 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 library/Validation/CompaniesValidator.php create mode 100644 tests/integration/library/Validation/CompaniesValidatorCest.php diff --git a/library/Validation/CompaniesValidator.php b/library/Validation/CompaniesValidator.php new file mode 100644 index 00000000..89b2d9d0 --- /dev/null +++ b/library/Validation/CompaniesValidator.php @@ -0,0 +1,24 @@ + "The company name is required", + ] + ); + $this->setFilters('name', Filter::FILTER_STRING); + $this->add('name', $presenceOf); + } +} diff --git a/tests/integration/library/Validation/CompaniesValidatorCest.php b/tests/integration/library/Validation/CompaniesValidatorCest.php new file mode 100644 index 00000000..c7db40b7 --- /dev/null +++ b/tests/integration/library/Validation/CompaniesValidatorCest.php @@ -0,0 +1,28 @@ + '', + 'address' => '123 Phalcon way', + 'city' => 'World', + 'phone' => '555-999-4444', + ]; + $messages = $validation->validate($_POST); + $I->assertEquals(1, count($messages)); + $I->assertEquals('The company name is required', $messages[0]->getMessage()); + } +} From be5cbe658e3781cb54cf7eaf752f11602e62add8 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 10:59:37 -0400 Subject: [PATCH 11/70] Added transformer for Companies --- library/Transformers/CompaniesTransformer.php | 31 ++++++++++++++ .../Transformers/CompaniesTransformerCest.php | 40 +++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 library/Transformers/CompaniesTransformer.php create mode 100644 tests/integration/library/Transformers/CompaniesTransformerCest.php diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php new file mode 100644 index 00000000..4b99d600 --- /dev/null +++ b/library/Transformers/CompaniesTransformer.php @@ -0,0 +1,31 @@ + $company->get('com_id'), + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ]; + } +} diff --git a/tests/integration/library/Transformers/CompaniesTransformerCest.php b/tests/integration/library/Transformers/CompaniesTransformerCest.php new file mode 100644 index 00000000..84a7ebe2 --- /dev/null +++ b/tests/integration/library/Transformers/CompaniesTransformerCest.php @@ -0,0 +1,40 @@ +haveRecordWithFields( + Companies::class, + [ + 'com_name' => 'acme', + 'com_address' => '123 Phalcon way', + 'com_city' => 'World', + 'com_telephone' => '555-999-4444', + ] + ); + + $transformer = new CompaniesTransformer(); + $expected = [ + 'id' => $company->get('com_id'), + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ]; + + $I->assertEquals($expected, $transformer->transform($company)); + } +} From 0d7fd3e0bae9e91d54c0b55e10126ba01ab6beec Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 10:59:55 -0400 Subject: [PATCH 12/70] Added validator in companies model; More companies tests; Adjusted response for errors; Added company add controller --- api/controllers/Companies/AddController.php | 76 +++++++++++++++++++ library/Http/Response.php | 17 +++++ library/Models/Companies.php | 22 ++++++ .../library/Models/CompaniesCest.php | 31 ++++++++ 4 files changed, 146 insertions(+) create mode 100644 api/controllers/Companies/AddController.php diff --git a/api/controllers/Companies/AddController.php b/api/controllers/Companies/AddController.php new file mode 100644 index 00000000..4b7fe03e --- /dev/null +++ b/api/controllers/Companies/AddController.php @@ -0,0 +1,76 @@ +validate($this->request->getPost()); + + /** + * If no messages are returned, go ahead with the query + */ + if (0 === count($messages)) { + $name = $this->request->getPost('name', Filter::FILTER_STRING); + $address = $this->request->getPost('address', Filter::FILTER_STRING); + $city = $this->request->getPost('city', Filter::FILTER_STRING); + $phone = $this->request->getPost('phone', Filter::FILTER_STRING); + + $company = new Companies(); + $result = $company + ->set('com_name', $name) + ->set('com_address', $address) + ->set('com_city', $city) + ->set('com_telephone', $phone) + ->save() + ; + + if (false !== $result) { + /** + * Everything is fine, return the record back + */ + return $this->format([$result], CompaniesTransformer::class); + } + + /** + * Errors happened store them + */ + $messages = $company->getMessages(); + } + + /** + * Set the errors in the payload + */ + $this->response->setPayloadErrors($messages); + } +} diff --git a/library/Http/Response.php b/library/Http/Response.php index 447ba96e..f6ecd757 100644 --- a/library/Http/Response.php +++ b/library/Http/Response.php @@ -8,6 +8,8 @@ use League\Fractal\Resource\Item; use Niden\Transformers\PayloadTransformer; use Phalcon\Http\Response as PhResponse; +use Phalcon\Mvc\Model\MessageInterface as ModelMessage; +use Phalcon\Validation\Message\Group as ValidationMessage; class Response extends PhResponse { @@ -15,6 +17,7 @@ class Response extends PhResponse * @var array */ private $content = []; + /** * Sets the payload code as Error * @@ -30,6 +33,20 @@ public function setPayloadError(string $detail = ''): Response return $this; } + /** + * Traverses the errors collection and sets the errors in the payload + * + * @param ModelMessage[]|ValidationMessage $errors + * + * @return Response + */ + public function setPayloadErrors($errors): Response + { + foreach ($errors as $error) { + $this->setPayloadError($error->getMessage()); + } + } + /** * Sets the payload code as Error * diff --git a/library/Models/Companies.php b/library/Models/Companies.php index ea837c11..4171a7fc 100644 --- a/library/Models/Companies.php +++ b/library/Models/Companies.php @@ -7,6 +7,8 @@ use Niden\Constants\Relationships; use Niden\Mvc\Model\AbstractModel; use Phalcon\Filter; +use Phalcon\Validation; +use Phalcon\Validation\Validator\Uniqueness; /** * Class Companies @@ -78,4 +80,24 @@ public function getTablePrefix(): string { return 'com'; } + + /** + * Validates the company name + * + * @return bool + */ + public function validation() + { + $validator = new Validation(); + $validator->add( + 'com_name', + new Uniqueness( + [ + 'message' => 'The company name already exists in the database', + ] + ) + ); + + return $this->validate($validator); + } } diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index 90fc9cb7..4d690534 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -53,4 +53,35 @@ public function validateRelationships(IntegrationTester $I) ]; $I->assertEquals($expected, $actual); } + + public function validateUniqueName(IntegrationTester $I) + { + $companyOne = new Companies(); + /** @var Companies $companyOne */ + $result = $companyOne + ->set('com_name', 'acme') + ->set('com_address', '123 Phalcon way') + ->set('com_city', 'World') + ->set('com_telephone', '555-999-4444') + ->save() + ; + $I->assertNotEquals(false, $result); + + $companyTwo = new Companies(); + /** @var Companies $companyTwo */ + $result = $companyTwo + ->set('com_name', 'acme') + ->set('com_address', '123 Phalcon way') + ->set('com_city', 'World') + ->set('com_telephone', '555-999-4444') + ->save() + ; + $I->assertEquals(false, $result); + $I->assertEquals(1, count($companyTwo->getMessages())); + + $messages = $companyTwo->getMessages(); + $I->assertEquals('The company name already exists in the database', $messages[0]->getMessage()); + $result = $companyOne->delete(); + $I->assertNotEquals(false, $result); + } } From 3461ca50063cad00e2367486c363dab78c2190fa Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 12:00:48 -0400 Subject: [PATCH 13/70] Added more tests --- api/controllers/Companies/AddController.php | 2 +- library/Http/Response.php | 2 + tests/unit/library/Http/ResponseCest.php | 41 +++++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/api/controllers/Companies/AddController.php b/api/controllers/Companies/AddController.php index 4b7fe03e..ef0462e7 100644 --- a/api/controllers/Companies/AddController.php +++ b/api/controllers/Companies/AddController.php @@ -4,12 +4,12 @@ namespace Niden\Api\Controllers\Users; -use Niden\Api\Validation\CompaniesValidator; use Niden\Exception\ModelException; use Niden\Http\Response; use Niden\Models\Companies; use Niden\Traits\FractalTrait; use Niden\Transformers\CompaniesTransformer; +use Niden\Validation\CompaniesValidator; use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; diff --git a/library/Http/Response.php b/library/Http/Response.php index f6ecd757..df01d0a1 100644 --- a/library/Http/Response.php +++ b/library/Http/Response.php @@ -45,6 +45,8 @@ public function setPayloadErrors($errors): Response foreach ($errors as $error) { $this->setPayloadError($error->getMessage()); } + + return $this; } /** diff --git a/tests/unit/library/Http/ResponseCest.php b/tests/unit/library/Http/ResponseCest.php index 9fd6118d..838f8fe8 100755 --- a/tests/unit/library/Http/ResponseCest.php +++ b/tests/unit/library/Http/ResponseCest.php @@ -5,6 +5,9 @@ use function is_string; use function json_decode; use Niden\Http\Response; +use Phalcon\Mvc\Model\Message as ModelMessage; +use Phalcon\Validation\Message as ValidationMessage; +use Phalcon\Validation\Message\Group as ValidationGroup; use \UnitTester; class ResponseCest @@ -51,6 +54,44 @@ public function checkResponseWithErrorCode(UnitTester $I) $I->assertEquals('error content', $payload['errors'][0]); } + public function checkResponseWithModelErrors(UnitTester $I) + { + $messages = [ + new ModelMessage('hello'), + new ModelMessage('goodbye'), + ]; + $response = new Response(); + $response + ->setPayloadErrors($messages); + + $payload = $this->checkPayload($I, $response, true); + + $I->assertFalse(isset($payload['data'])); + $I->assertEquals(2, count($payload['errors'])); + $I->assertEquals('hello', $payload['errors'][0]); + $I->assertEquals('goodbye', $payload['errors'][1]); + } + + public function checkResponseWithValidationErrors(UnitTester $I) + { + $group = new ValidationGroup(); + $message = new ValidationMessage('hello'); + $group->appendMessage($message); + $message = new ValidationMessage('goodbye'); + $group->appendMessage($message); + + $response = new Response(); + $response + ->setPayloadErrors($group); + + $payload = $this->checkPayload($I, $response, true); + + $I->assertFalse(isset($payload['data'])); + $I->assertEquals(2, count($payload['errors'])); + $I->assertEquals('hello', $payload['errors'][0]); + $I->assertEquals('goodbye', $payload['errors'][1]); + } + private function checkPayload(UnitTester $I, Response $response, bool $error = false): array { $contents = $response->getContent(); From 0968e25b5366225ee79964cf5787f914a0bb7e49 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 13:04:51 -0400 Subject: [PATCH 14/70] Added companies tests and logic in the controller --- api/controllers/Companies/AddController.php | 10 +- ...GetOneController.php => GetController.php} | 0 api/controllers/Users/GetManyController.php | 39 ---- tests/api/Companies/AddCest.php | 95 ++++++++ tests/api/Users/UserCest.php | 197 ----------------- tests/api/Users/UsersCest.php | 207 ++++++++++++++---- 6 files changed, 259 insertions(+), 289 deletions(-) rename api/controllers/Users/{GetOneController.php => GetController.php} (100%) delete mode 100644 api/controllers/Users/GetManyController.php create mode 100644 tests/api/Companies/AddCest.php delete mode 100644 tests/api/Users/UserCest.php diff --git a/api/controllers/Companies/AddController.php b/api/controllers/Companies/AddController.php index ef0462e7..f7dc4c97 100644 --- a/api/controllers/Companies/AddController.php +++ b/api/controllers/Companies/AddController.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Niden\Api\Controllers\Users; +namespace Niden\Api\Controllers\Companies; use Niden\Exception\ModelException; use Niden\Http\Response; @@ -42,9 +42,9 @@ public function callAction() */ if (0 === count($messages)) { $name = $this->request->getPost('name', Filter::FILTER_STRING); - $address = $this->request->getPost('address', Filter::FILTER_STRING); - $city = $this->request->getPost('city', Filter::FILTER_STRING); - $phone = $this->request->getPost('phone', Filter::FILTER_STRING); + $address = $this->request->getPost('address', Filter::FILTER_STRING, ''); + $city = $this->request->getPost('city', Filter::FILTER_STRING, ''); + $phone = $this->request->getPost('phone', Filter::FILTER_STRING, ''); $company = new Companies(); $result = $company @@ -59,7 +59,7 @@ public function callAction() /** * Everything is fine, return the record back */ - return $this->format([$result], CompaniesTransformer::class); + return $this->format([$company], CompaniesTransformer::class); } /** diff --git a/api/controllers/Users/GetOneController.php b/api/controllers/Users/GetController.php similarity index 100% rename from api/controllers/Users/GetOneController.php rename to api/controllers/Users/GetController.php diff --git a/api/controllers/Users/GetManyController.php b/api/controllers/Users/GetManyController.php deleted file mode 100644 index 41d0ec2a..00000000 --- a/api/controllers/Users/GetManyController.php +++ /dev/null @@ -1,39 +0,0 @@ -format($this->getUsers(), UsersTransformer::class); - } -} diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php new file mode 100644 index 00000000..02812878 --- /dev/null +++ b/tests/api/Companies/AddCest.php @@ -0,0 +1,95 @@ +addRecord($I); + $token = $I->apiLogin(); + $name = uniqid('com'); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST( + Data::$companiesAddUrl, + Data::companyAddJson( + $name, + '123 Phalcon way', + 'World', + '555-444-7777' + ) + ); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + + $company = $I->getRecordWithFields( + Companies::class, + [ + 'com_name' => $name, + ] + ); + $I->assertNotEquals(false, $company); + + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $company->get('com_id'), + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ], + ] + ); + + $I->assertNotEquals(false, $company->delete()); + } + + public function addNewCompanyWithExistingName(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + $name = uniqid('com'); + $I->haveRecordWithFields( + Companies::class, + [ + 'com_name' => $name + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST( + Data::$companiesAddUrl, + Data::companyAddJson( + $name, + '123 Phalcon way', + 'World', + '555-444-7777' + ) + ); + $I->deleteHeader('Authorization'); + $I->seeErrorJsonResponse('The company name already exists in the database'); + } + + private function addRecord(ApiTester $I) + { + return $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + } +} diff --git a/tests/api/Users/UserCest.php b/tests/api/Users/UserCest.php deleted file mode 100644 index e4cd5362..00000000 --- a/tests/api/Users/UserCest.php +++ /dev/null @@ -1,197 +0,0 @@ -deleteHeader('Authorization'); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Invalid Token'); - } - - public function loginKnownUserGetUnknownUser(ApiTester $I) - { - $this->addRecord($I); - $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$loginUrl, Data::loginJson()); - $I->seeResponseIsSuccessful(); - - $response = $I->grabResponse(); - $response = json_decode($response, true); - $data = $response['data']; - $token = $data['token']; - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Record not found'); - } - - public function loginKnownUserIncorrectSignature(ApiTester $I) - { - $record = $this->addRecord($I); - $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$loginUrl, Data::loginJson()); - $I->seeResponseIsSuccessful(); - - $signer = new Sha512(); - $builder = new Builder(); - - $token = $builder - ->setIssuer('https://niden.net') - ->setAudience($this->getTokenAudience()) - ->setId('110011', true) - ->setIssuedAt(time() - 3600) - ->setNotBefore(time() - 3590) - ->setExpiration(time() - 3000) - ->sign($signer, '123456') - ->getToken(); - - $wrongToken = $token->__toString(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $wrongToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Invalid Token'); - } - - public function loginKnownUserExpiredToken(ApiTester $I) - { - $record = $this->addRecord($I); - $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$loginUrl, Data::loginJson()); - $I->seeResponseIsSuccessful(); - - $signer = new Sha512(); - $builder = new Builder(); - - $token = $builder - ->setIssuer('https://niden.net') - ->setAudience($this->getTokenAudience()) - ->setId('110011', true) - ->setIssuedAt(time() - 3600) - ->setNotBefore(time() - 3590) - ->setExpiration(time() - 3000) - ->sign($signer, '12345') - ->getToken(); - - $expiredToken = $token->__toString(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $expiredToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Invalid Token'); - } - - public function loginKnownUserInvalidToken(ApiTester $I) - { - $record = $this->addRecord($I); - $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$loginUrl, Data::loginJson()); - $I->seeResponseIsSuccessful(); - - $signer = new Sha512(); - $builder = new Builder(); - - $token = $builder - ->setIssuer('https://niden.net') - ->setAudience($this->getTokenAudience()) - ->setId('110011', true) - ->setIssuedAt(time() - 3600) - ->setNotBefore(time() - 3590) - ->setExpiration(time() - 3000) - ->sign($signer, '12345') - ->getToken(); - - $invalidToken = $token->__toString(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Invalid Token'); - } - - public function loginKnownUserInvalidUserInToken(ApiTester $I) - { - $record = $this->addRecord($I); - $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$loginUrl, Data::loginJson()); - $I->seeResponseIsSuccessful(); - - $signer = new Sha512(); - $builder = new Builder(); - - $token = $builder - ->setIssuer('https://niden.com') - ->setAudience($this->getTokenAudience()) - ->setId('110011', true) - ->setIssuedAt(time() - 3600) - ->setNotBefore(time() - 3590) - ->setExpiration(time() - 3000) - ->sign($signer, '12345') - ->getToken(); - - $invalidToken = $token->__toString(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Invalid Token'); - } - - public function loginKnownUserCorrectToken(ApiTester $I) - { - $this->addRecord($I); - $I->apiLogin(); - } - - public function loginKnownUserValidToken(ApiTester $I) - { - $user = $this->addRecord($I); - $token = $I->apiLogin(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($user->get('usr_id'))); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse( - [ - [ - 'id' => $user->get('usr_id'), - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), - ], - ] - ); - } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } -} diff --git a/tests/api/Users/UsersCest.php b/tests/api/Users/UsersCest.php index 9b1c1e62..e4cd5362 100644 --- a/tests/api/Users/UsersCest.php +++ b/tests/api/Users/UsersCest.php @@ -3,68 +3,186 @@ namespace Niden\Tests\api\Users; use ApiTester; +use Lcobucci\JWT\Builder; +use Lcobucci\JWT\Signer\Hmac\Sha512; use Niden\Models\Users; +use Niden\Traits\TokenTrait; use Page\Data; -class UsersCest +class UserCest { - public function getManyUsers(ApiTester $I) + use TokenTrait; + + public function loginKnownUserNoToken(ApiTester $I) { - $userOne = $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Invalid Token'); + } - $userTwo = $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser1', - 'usr_password' => 'testpassword1', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '789789', - 'usr_token_id' => '001100', - ] - ); + public function loginKnownUserGetUnknownUser(ApiTester $I) + { + $this->addRecord($I); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$loginUrl, Data::loginJson()); + $I->seeResponseIsSuccessful(); + + $response = $I->grabResponse(); + $response = json_decode($response, true); + $data = $response['data']; + $token = $data['token']; + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Record not found'); + } + + public function loginKnownUserIncorrectSignature(ApiTester $I) + { + $record = $this->addRecord($I); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$loginUrl, Data::loginJson()); + $I->seeResponseIsSuccessful(); + + $signer = new Sha512(); + $builder = new Builder(); + + $token = $builder + ->setIssuer('https://niden.net') + ->setAudience($this->getTokenAudience()) + ->setId('110011', true) + ->setIssuedAt(time() - 3600) + ->setNotBefore(time() - 3590) + ->setExpiration(time() - 3000) + ->sign($signer, '123456') + ->getToken(); + + $wrongToken = $token->__toString(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $wrongToken); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Invalid Token'); + } + + public function loginKnownUserExpiredToken(ApiTester $I) + { + $record = $this->addRecord($I); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$loginUrl, Data::loginJson()); + $I->seeResponseIsSuccessful(); + + $signer = new Sha512(); + $builder = new Builder(); + + $token = $builder + ->setIssuer('https://niden.net') + ->setAudience($this->getTokenAudience()) + ->setId('110011', true) + ->setIssuedAt(time() - 3600) + ->setNotBefore(time() - 3590) + ->setExpiration(time() - 3000) + ->sign($signer, '12345') + ->getToken(); + + $expiredToken = $token->__toString(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $expiredToken); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Invalid Token'); + } + + public function loginKnownUserInvalidToken(ApiTester $I) + { + $record = $this->addRecord($I); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$loginUrl, Data::loginJson()); + $I->seeResponseIsSuccessful(); + + $signer = new Sha512(); + $builder = new Builder(); + + $token = $builder + ->setIssuer('https://niden.net') + ->setAudience($this->getTokenAudience()) + ->setId('110011', true) + ->setIssuedAt(time() - 3600) + ->setNotBefore(time() - 3590) + ->setExpiration(time() - 3000) + ->sign($signer, '12345') + ->getToken(); + + $invalidToken = $token->__toString(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Invalid Token'); + } + + public function loginKnownUserInvalidUserInToken(ApiTester $I) + { + $record = $this->addRecord($I); + $I->deleteHeader('Authorization'); + $I->sendPOST(Data::$loginUrl, Data::loginJson()); + $I->seeResponseIsSuccessful(); + + $signer = new Sha512(); + $builder = new Builder(); + + $token = $builder + ->setIssuer('https://niden.com') + ->setAudience($this->getTokenAudience()) + ->setId('110011', true) + ->setIssuedAt(time() - 3600) + ->setNotBefore(time() - 3590) + ->setExpiration(time() - 3000) + ->sign($signer, '12345') + ->getToken(); + + $invalidToken = $token->__toString(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->seeResponseIsSuccessful(); + $I->seeErrorJsonResponse('Invalid Token'); + } + + public function loginKnownUserCorrectToken(ApiTester $I) + { + $this->addRecord($I); + $I->apiLogin(); + } + public function loginKnownUserValidToken(ApiTester $I) + { + $user = $this->addRecord($I); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl); + $I->sendPOST(Data::$userGetUrl, Data::userGetJson($user->get('usr_id'))); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( [ [ - 'id' => $userOne->get('usr_id'), - 'status' => $userOne->get('usr_status_flag'), - 'username' => $userOne->get('usr_username'), - 'issuer' => $userOne->get('usr_issuer'), - 'tokenPassword' => $userOne->get('usr_token_password'), - 'tokenId' => $userOne->get('usr_token_id'), - ], - [ - 'id' => $userTwo->get('usr_id'), - 'status' => $userTwo->get('usr_status_flag'), - 'username' => $userTwo->get('usr_username'), - 'issuer' => $userTwo->get('usr_issuer'), - 'tokenPassword' => $userTwo->get('usr_token_password'), - 'tokenId' => $userTwo->get('usr_token_id'), + 'id' => $user->get('usr_id'), + 'status' => $user->get('usr_status_flag'), + 'username' => $user->get('usr_username'), + 'issuer' => $user->get('usr_issuer'), + 'tokenPassword' => $user->get('usr_token_password'), + 'tokenId' => $user->get('usr_token_id'), ], ] ); } - public function getManyUsersWithNoData(ApiTester $I) + private function addRecord(ApiTester $I) { - $userOne = $I->haveRecordWithFields( + return $I->haveRecordWithFields( Users::class, [ 'usr_status_flag' => 1, @@ -75,12 +193,5 @@ public function getManyUsersWithNoData(ApiTester $I) 'usr_token_id' => '110011', ] ); - - $token = $I->apiLogin(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); } } From a4f071d9ed19ab13e865d897289162194c9ec32e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 13:05:03 -0400 Subject: [PATCH 15/70] Removed getone/getmany for users and replaced it only with get --- api/controllers/Users/GetController.php | 19 +++-- library/Providers/RouterProvider.php | 11 +-- library/Traits/UserTrait.php | 18 ++-- tests/_support/Page/Data.php | 28 ++++-- tests/api/IncorrectPayloadCest.php | 2 +- tests/api/Users/UsersCest.php | 94 +++++++++++++++++++-- tests/unit/library/Providers/RouterCest.php | 4 +- 7 files changed, 135 insertions(+), 41 deletions(-) diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 9ebeb6c2..663b3fd9 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -6,6 +6,7 @@ use Niden\Http\Request; use Niden\Http\Response; +use Niden\Models\Users; use Niden\Traits\FractalTrait; use Niden\Traits\ResponseTrait; use Niden\Traits\UserTrait; @@ -13,9 +14,10 @@ use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; +use Phalcon\Mvc\Model\Query\Builder; /** - * Class GetOneController + * Class GetController * * @package Niden\Api\Controllers\Users * @@ -23,7 +25,7 @@ * @property Request $request * @property Response $response */ -class GetOneController extends Controller +class GetController extends Controller { use FractalTrait; use ResponseTrait; @@ -36,13 +38,20 @@ public function callAction() { /** @var int $userId */ $userId = $this->request->getPost('userId', Filter::FILTER_ABSINT, 0); - $parameters = ['usr_id' => $userId]; - $results = $this->getUsers($parameters); + $parameters = []; + if ($userId > 0) { + $parameters['usr_id'] = $userId; + } + + /** + * Execute the query + */ + $results = $this->getUsers($parameters); if (count($results) > 0) { return $this->format($results, UsersTransformer::class); } else { - $this->halt($this->application, 'Record not found'); + $this->halt($this->application, 'Record(s) not found'); } } } diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index c4e384ff..70da822e 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -4,8 +4,8 @@ namespace Niden\Providers; -use Niden\Api\Controllers\Users\GetOneController; -use Niden\Api\Controllers\Users\GetManyController; +use Niden\Api\Controllers\Companies\AddController as CompaniesAddController; +use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; use Niden\Middleware\NotFoundMiddleware; use Niden\Middleware\PayloadMiddleware; @@ -14,6 +14,7 @@ use Niden\Middleware\TokenUserMiddleware; use Niden\Middleware\TokenValidationMiddleware; use Niden\Middleware\TokenVerificationMiddleware; + use Phalcon\Di\ServiceProviderInterface; use Phalcon\DiInterface; use Phalcon\Events\Manager; @@ -106,9 +107,9 @@ private function getRoutes(): array { return [ // Class, Method, Route, Handler - [LoginController::class, '', 'post', '/login'], - [GetOneController::class, '/user', 'post', '/get'], - [GetManyController::class, '/users', 'post', '/get'], + [LoginController::class, '', 'post', '/login'], + [CompaniesAddController::class, '/companies', 'post', '/add'], + [UsersGetController::class, '/users', 'post', '/get'], ]; } } diff --git a/library/Traits/UserTrait.php b/library/Traits/UserTrait.php index 2f615b57..c0bb62dd 100644 --- a/library/Traits/UserTrait.php +++ b/library/Traits/UserTrait.php @@ -33,7 +33,9 @@ protected function getUserByToken(Token $token) 'usr_status_flag' => Flags::ACTIVE, ]; - return $this->getUser($parameters); + $result = $this->getUsers($parameters); + + return $result[0] ?? false; } /** @@ -52,19 +54,9 @@ protected function getUserByUsernameAndPassword($username, $password) 'usr_status_flag' => Flags::ACTIVE, ]; - return $this->getUser($parameters); - } - - /** - * @param array $parameters - * - * @return Users|false - */ - protected function getUser(array $parameters = []) - { - $results = $this->getUsers($parameters); + $result = $this->getUsers($parameters); - return $results[0] ?? false; + return $result[0] ?? false; } /** diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index fa9c9733..4be2bb51 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -4,10 +4,10 @@ class Data { - public static $loginUrl = '/login'; - public static $userGetUrl = '/user/get'; - public static $usersGetUrl = '/users/get'; - public static $wrongUrl = '/sommething'; + public static $companiesAddUrl = '/companies/add'; + public static $loginUrl = '/login'; + public static $usersGetUrl = '/users/get'; + public static $wrongUrl = '/sommething'; public static function loginJson() { @@ -21,12 +21,28 @@ public static function loginJson() ); } - public static function userGetJson($userId) + public static function usersGetJson($userId = 0) + { + $payload = [ + 'data' => [], + ]; + + if ($userId > 0) { + $payload['data']['userId'] = $userId; + } + + return json_encode($payload); + } + + public static function companyAddJson($name, $address = '', $city = '', $phone = '') { return json_encode( [ 'data' => [ - 'userId' => $userId, + 'name' => $name, + 'address' => $address, + 'city' => $city, + 'phone' => $phone, ] ] ); diff --git a/tests/api/IncorrectPayloadCest.php b/tests/api/IncorrectPayloadCest.php index d29e742e..7b161c77 100644 --- a/tests/api/IncorrectPayloadCest.php +++ b/tests/api/IncorrectPayloadCest.php @@ -12,7 +12,7 @@ class IncorrectPayloadCest { public function checkDefaultRoute(ApiTester $I) { - $I->sendPOST(Data::$userGetUrl, '{"key": "value}'); + $I->sendPOST(Data::$usersGetUrl, '{"key": "value}'); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Malformed JSON'); } diff --git a/tests/api/Users/UsersCest.php b/tests/api/Users/UsersCest.php index e4cd5362..4bbf4be9 100644 --- a/tests/api/Users/UsersCest.php +++ b/tests/api/Users/UsersCest.php @@ -9,14 +9,14 @@ use Niden\Traits\TokenTrait; use Page\Data; -class UserCest +class UsersCest { use TokenTrait; public function loginKnownUserNoToken(ApiTester $I) { $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson(1)); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -34,9 +34,9 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) $token = $data['token']; $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson(1)); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson(1)); $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Record not found'); + $I->seeErrorJsonResponse('Record(s) not found'); } public function loginKnownUserIncorrectSignature(ApiTester $I) @@ -62,7 +62,7 @@ public function loginKnownUserIncorrectSignature(ApiTester $I) $wrongToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $wrongToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -90,7 +90,7 @@ public function loginKnownUserExpiredToken(ApiTester $I) $expiredToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $expiredToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -118,7 +118,7 @@ public function loginKnownUserInvalidToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -146,7 +146,7 @@ public function loginKnownUserInvalidUserInToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($record->get('usr_id'))); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -163,7 +163,7 @@ public function loginKnownUserValidToken(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$userGetUrl, Data::userGetJson($user->get('usr_id'))); + $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($user->get('usr_id'))); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -180,6 +180,82 @@ public function loginKnownUserValidToken(ApiTester $I) ); } + public function getManyUsers(ApiTester $I) + { + $userOne = $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + + $userTwo = $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser1', + 'usr_password' => 'testpassword1', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '789789', + 'usr_token_id' => '001100', + ] + ); + + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$usersGetUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $userOne->get('usr_id'), + 'status' => $userOne->get('usr_status_flag'), + 'username' => $userOne->get('usr_username'), + 'issuer' => $userOne->get('usr_issuer'), + 'tokenPassword' => $userOne->get('usr_token_password'), + 'tokenId' => $userOne->get('usr_token_id'), + ], + [ + 'id' => $userTwo->get('usr_id'), + 'status' => $userTwo->get('usr_status_flag'), + 'username' => $userTwo->get('usr_username'), + 'issuer' => $userTwo->get('usr_issuer'), + 'tokenPassword' => $userTwo->get('usr_token_password'), + 'tokenId' => $userTwo->get('usr_token_id'), + ], + ] + ); + } + + public function getManyUsersWithNoData(ApiTester $I) + { + $userOne = $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$usersGetUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + } + private function addRecord(ApiTester $I) { return $I->haveRecordWithFields( diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index d1910d43..6942f707 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -33,8 +33,8 @@ public function checkRegistration(UnitTester $I) $I->assertEquals('POST', $routes[0]->getHttpMethods()); $I->assertEquals('/login', $routes[0]->getPattern()); $I->assertEquals('POST', $routes[1]->getHttpMethods()); - $I->assertEquals('/user/get', $routes[1]->getPattern()); + $I->assertEquals('/companies/add', $routes[1]->getPattern()); $I->assertEquals('POST', $routes[2]->getHttpMethods()); $I->assertEquals('/users/get', $routes[2]->getPattern()); - } + } } From f33ece856f016f482580b7ef2c861db409fc70f1 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 13:27:52 -0400 Subject: [PATCH 16/70] Added product types transformer and tests --- .../Transformers/ProductTypesTransformer.php | 29 +++++++++++++++ .../ProductTypesTransformerCest.php | 35 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 library/Transformers/ProductTypesTransformer.php create mode 100644 tests/integration/library/Transformers/ProductTypesTransformerCest.php diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php new file mode 100644 index 00000000..2115be2c --- /dev/null +++ b/library/Transformers/ProductTypesTransformer.php @@ -0,0 +1,29 @@ + $type->get('prt_id'), + 'name' => $type->get('prt_name'), + ]; + } +} diff --git a/tests/integration/library/Transformers/ProductTypesTransformerCest.php b/tests/integration/library/Transformers/ProductTypesTransformerCest.php new file mode 100644 index 00000000..e75bb3bf --- /dev/null +++ b/tests/integration/library/Transformers/ProductTypesTransformerCest.php @@ -0,0 +1,35 @@ +haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('type'), + ] + ); + + $transformer = new ProductTypesTransformer(); + $expected = [ + 'id' => $type->get('prt_id'), + 'name' => $type->get('prt_name'), + ]; + + $I->assertEquals($expected, $transformer->transform($type)); + } +} From ca247386c1dc03b1987d106fa56c559e8a18e671 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 13:32:05 -0400 Subject: [PATCH 17/70] Added route to get the product types and product types get controller --- .../ProductTypes/GetController.php | 52 +++++++++++++++++++ library/Providers/RouterProvider.php | 8 +-- tests/unit/library/Providers/RouterCest.php | 6 ++- 3 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 api/controllers/ProductTypes/GetController.php diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php new file mode 100644 index 00000000..2982ccaa --- /dev/null +++ b/api/controllers/ProductTypes/GetController.php @@ -0,0 +1,52 @@ +addFrom(ProductTypes::class) + ->orderBy('prt_name') + ->getQuery() + ->execute() + ; + + if (count($results) > 0) { + return $this->format($results, ProductTypesTransformer::class); + } else { + $this->halt($this->application, 'Record(s) not found'); + } + } +} diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index 70da822e..c3c74649 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -5,6 +5,7 @@ namespace Niden\Providers; use Niden\Api\Controllers\Companies\AddController as CompaniesAddController; +use Niden\Api\Controllers\ProductTypes\GetController as ProductTypesGetController; use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; use Niden\Middleware\NotFoundMiddleware; @@ -107,9 +108,10 @@ private function getRoutes(): array { return [ // Class, Method, Route, Handler - [LoginController::class, '', 'post', '/login'], - [CompaniesAddController::class, '/companies', 'post', '/add'], - [UsersGetController::class, '/users', 'post', '/get'], + [LoginController::class, '', 'post', '/login'], + [CompaniesAddController::class, '/companies', 'post', '/add'], + [ProductTypesGetController::class, '/producttypes', 'post', '/get'], + [UsersGetController::class, '/users', 'post', '/get'], ]; } } diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 6942f707..8bbe7fee 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -29,12 +29,14 @@ public function checkRegistration(UnitTester $I) /** @var RouterInterface $router */ $router = $application->getRouter(); $routes = $router->getRoutes(); - $I->assertEquals(3, count($routes)); + $I->assertEquals(4, count($routes)); $I->assertEquals('POST', $routes[0]->getHttpMethods()); $I->assertEquals('/login', $routes[0]->getPattern()); $I->assertEquals('POST', $routes[1]->getHttpMethods()); $I->assertEquals('/companies/add', $routes[1]->getPattern()); $I->assertEquals('POST', $routes[2]->getHttpMethods()); - $I->assertEquals('/users/get', $routes[2]->getPattern()); + $I->assertEquals('/producttypes/get', $routes[2]->getPattern()); + $I->assertEquals('POST', $routes[3]->getHttpMethods()); + $I->assertEquals('/users/get', $routes[3]->getPattern()); } } From 37b52c8e12f302fac9a6a0cbc60a52b2998922b0 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 13:55:09 -0400 Subject: [PATCH 18/70] Refactored the UsersTrait -> QueryTrait; Tests for product types get --- api/controllers/LoginController.php | 4 +- .../ProductTypes/GetController.php | 12 +-- api/controllers/Users/GetController.php | 7 +- .../Middleware/AuthenticationMiddleware.php | 4 +- library/Middleware/TokenBase.php | 4 +- .../Traits/{UserTrait.php => QueryTrait.php} | 24 ++++-- tests/_support/Page/Data.php | 9 ++- tests/api/ProductTypes/GetCest.php | 73 +++++++++++++++++++ .../api/Users/{UsersCest.php => GetCest.php} | 2 +- .../Traits/{UsersCest.php => QueryCest.php} | 8 +- 10 files changed, 111 insertions(+), 36 deletions(-) rename library/Traits/{UserTrait.php => QueryTrait.php} (73%) create mode 100644 tests/api/ProductTypes/GetCest.php rename tests/api/Users/{UsersCest.php => GetCest.php} (99%) rename tests/integration/library/Traits/{UsersCest.php => QueryCest.php} (96%) diff --git a/api/controllers/LoginController.php b/api/controllers/LoginController.php index 5b445a62..90b6fb51 100644 --- a/api/controllers/LoginController.php +++ b/api/controllers/LoginController.php @@ -8,8 +8,8 @@ use Niden\Http\Request; use Niden\Http\Response; use Niden\Models\Users; +use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; -use Niden\Traits\UserTrait; use Phalcon\Filter; use Phalcon\Mvc\Controller; @@ -24,7 +24,7 @@ class LoginController extends Controller { use TokenTrait; - use UserTrait; + use QueryTrait; /** * Default action logging in diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 2982ccaa..4114d515 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -8,8 +8,8 @@ use Niden\Http\Response; use Niden\Models\ProductTypes; use Niden\Traits\FractalTrait; +use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; -use Niden\Traits\UserTrait; use Niden\Transformers\ProductTypesTransformer; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; @@ -27,21 +27,15 @@ class GetController extends Controller { use FractalTrait; + use QueryTrait; use ResponseTrait; - use UserTrait; /** * Get a user */ public function callAction() { - $builder = new Builder(); - $results = $builder - ->addFrom(ProductTypes::class) - ->orderBy('prt_name') - ->getQuery() - ->execute() - ; + $results = $this->getRecords(ProductTypes::class, [], 'prt_name'); if (count($results) > 0) { return $this->format($results, ProductTypesTransformer::class); diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 663b3fd9..45c18fba 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -8,13 +8,12 @@ use Niden\Http\Response; use Niden\Models\Users; use Niden\Traits\FractalTrait; +use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; -use Niden\Traits\UserTrait; use Niden\Transformers\UsersTransformer; use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; -use Phalcon\Mvc\Model\Query\Builder; /** * Class GetController @@ -29,7 +28,7 @@ class GetController extends Controller { use FractalTrait; use ResponseTrait; - use UserTrait; + use QueryTrait; /** * Get a user @@ -46,7 +45,7 @@ public function callAction() /** * Execute the query */ - $results = $this->getUsers($parameters); + $results = $this->getRecords(Users::class, $parameters); if (count($results) > 0) { return $this->format($results, UsersTransformer::class); diff --git a/library/Middleware/AuthenticationMiddleware.php b/library/Middleware/AuthenticationMiddleware.php index e677cba8..b08e48f5 100755 --- a/library/Middleware/AuthenticationMiddleware.php +++ b/library/Middleware/AuthenticationMiddleware.php @@ -5,8 +5,8 @@ namespace Niden\Middleware; use Niden\Http\Request; +use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; -use Niden\Traits\UserTrait; use Phalcon\Mvc\Micro; use Phalcon\Mvc\Micro\MiddlewareInterface; @@ -18,7 +18,7 @@ class AuthenticationMiddleware implements MiddlewareInterface { use ResponseTrait; - use UserTrait; + use QueryTrait; /** * Call me diff --git a/library/Middleware/TokenBase.php b/library/Middleware/TokenBase.php index f877b3bf..d514dda5 100755 --- a/library/Middleware/TokenBase.php +++ b/library/Middleware/TokenBase.php @@ -5,9 +5,9 @@ namespace Niden\Middleware; use Niden\Http\Request; +use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Traits\TokenTrait; -use Niden\Traits\UserTrait; use Phalcon\Mvc\Micro\MiddlewareInterface; /** @@ -19,7 +19,7 @@ abstract class TokenBase implements MiddlewareInterface { use ResponseTrait; use TokenTrait; - use UserTrait; + use QueryTrait; /** * @param Request $request diff --git a/library/Traits/UserTrait.php b/library/Traits/QueryTrait.php similarity index 73% rename from library/Traits/UserTrait.php rename to library/Traits/QueryTrait.php index c0bb62dd..a4b6fe3e 100644 --- a/library/Traits/UserTrait.php +++ b/library/Traits/QueryTrait.php @@ -12,11 +12,11 @@ use Phalcon\Mvc\Model\ResultsetInterface; /** - * Trait UserTrait + * Trait QueryTrait * * @package Niden\Traits */ -trait UserTrait +trait QueryTrait { /** * Gets a user from the database based on the JWT token @@ -33,7 +33,7 @@ protected function getUserByToken(Token $token) 'usr_status_flag' => Flags::ACTIVE, ]; - $result = $this->getUsers($parameters); + $result = $this->getRecords(Users::class, $parameters); return $result[0] ?? false; } @@ -54,28 +54,36 @@ protected function getUserByUsernameAndPassword($username, $password) 'usr_status_flag' => Flags::ACTIVE, ]; - $result = $this->getUsers($parameters); + $result = $this->getRecords(Users::class, $parameters); return $result[0] ?? false; } /** - * @param array $parameters + * Runs a query using the builder + * + * @param string $class + * @param array $where + * @param string $orderBy * * @return ResultsetInterface */ - protected function getUsers(array $parameters = []) + protected function getRecords(string $class, array $where = [], string $orderBy = '') { $builder = new Builder(); - $builder->addFrom(Users::class); + $builder->addFrom($class); - foreach ($parameters as $field => $value) { + foreach ($where as $field => $value) { $builder->andWhere( sprintf('%s = :%s:', $field, $field), [$field => $value] ); } + if (true !== empty($orderBy)) { + $builder->orderBy($orderBy); + } + return $builder->getQuery()->execute(); } } diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index 4be2bb51..f845d411 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -4,10 +4,11 @@ class Data { - public static $companiesAddUrl = '/companies/add'; - public static $loginUrl = '/login'; - public static $usersGetUrl = '/users/get'; - public static $wrongUrl = '/sommething'; + public static $companiesAddUrl = '/companies/add'; + public static $loginUrl = '/login'; + public static $productTypesGetUrl = '/producttypes/get'; + public static $usersGetUrl = '/users/get'; + public static $wrongUrl = '/sommething'; public static function loginJson() { diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php new file mode 100644 index 00000000..d8cca555 --- /dev/null +++ b/tests/api/ProductTypes/GetCest.php @@ -0,0 +1,73 @@ +addRecord($I); + $token = $I->apiLogin(); + + $typeOne = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('type-a-'), + ] + ); + $typeTwo = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('type-b-'), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$productTypesGetUrl, json_encode(['data' => []])); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $typeOne->get('prt_id'), + 'name' => $typeOne->get('prt_name'), + ], + [ + 'id' => $typeTwo->get('prt_id'), + 'name' => $typeTwo->get('prt_name'), + ], + ] + ); + } + + public function getProductTypesNoData(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$productTypesGetUrl, json_encode(['data' => []])); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + } + + private function addRecord(ApiTester $I) + { + return $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + } +} diff --git a/tests/api/Users/UsersCest.php b/tests/api/Users/GetCest.php similarity index 99% rename from tests/api/Users/UsersCest.php rename to tests/api/Users/GetCest.php index 4bbf4be9..37a05829 100644 --- a/tests/api/Users/UsersCest.php +++ b/tests/api/Users/GetCest.php @@ -9,7 +9,7 @@ use Niden\Traits\TokenTrait; use Page\Data; -class UsersCest +class GetCest { use TokenTrait; diff --git a/tests/integration/library/Traits/UsersCest.php b/tests/integration/library/Traits/QueryCest.php similarity index 96% rename from tests/integration/library/Traits/UsersCest.php rename to tests/integration/library/Traits/QueryCest.php index 30d4b871..f5bd68a6 100644 --- a/tests/integration/library/Traits/UsersCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -7,16 +7,16 @@ use \IntegrationTester; use Niden\Models\Users; use Niden\Exception\ModelException; +use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; -use Niden\Traits\UserTrait; /** - * Class ModelCest + * Class QueryCest */ -class UsersCest +class QueryCest { use TokenTrait; - use UserTrait; + use QueryTrait; /** * @param IntegrationTester $I From ca93024acfb59004d69ecc1367a1159e362e6fec Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 15:01:15 -0400 Subject: [PATCH 19/70] Refactor of the types transformer to be used in products and individuals --- .../Transformers/ProductTypesTransformer.php | 29 ----------------- library/Transformers/TypesTransformer.php | 31 +++++++++++++++++++ .../ProductTypesTransformerCest.php | 12 ++++--- 3 files changed, 38 insertions(+), 34 deletions(-) delete mode 100644 library/Transformers/ProductTypesTransformer.php create mode 100644 library/Transformers/TypesTransformer.php diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php deleted file mode 100644 index 2115be2c..00000000 --- a/library/Transformers/ProductTypesTransformer.php +++ /dev/null @@ -1,29 +0,0 @@ - $type->get('prt_id'), - 'name' => $type->get('prt_name'), - ]; - } -} diff --git a/library/Transformers/TypesTransformer.php b/library/Transformers/TypesTransformer.php new file mode 100644 index 00000000..3bb3639e --- /dev/null +++ b/library/Transformers/TypesTransformer.php @@ -0,0 +1,31 @@ + $model->get(sprintf('%s_id', $model->getTablePrefix())), + 'name' => $model->get(sprintf('%s_name', $model->getTablePrefix())), + 'description' => $model->get(sprintf('%s_description', $model->getTablePrefix())), + ]; + } +} diff --git a/tests/integration/library/Transformers/ProductTypesTransformerCest.php b/tests/integration/library/Transformers/ProductTypesTransformerCest.php index e75bb3bf..c3ff0f14 100644 --- a/tests/integration/library/Transformers/ProductTypesTransformerCest.php +++ b/tests/integration/library/Transformers/ProductTypesTransformerCest.php @@ -4,7 +4,7 @@ use IntegrationTester; use Niden\Models\ProductTypes; -use Niden\Transformers\ProductTypesTransformer; +use Niden\Transformers\TypesTransformer; use function uniqid; class ProductTypesTransformerCest @@ -20,14 +20,16 @@ public function checkTransformer(IntegrationTester $I) $type = $I->haveRecordWithFields( ProductTypes::class, [ - 'prt_name' => uniqid('type'), + 'prt_name' => uniqid('type-n-'), + 'prt_description' => uniqid('type-d-'), ] ); - $transformer = new ProductTypesTransformer(); + $transformer = new TypesTransformer(); $expected = [ - 'id' => $type->get('prt_id'), - 'name' => $type->get('prt_name'), + 'id' => $type->get('prt_id'), + 'name' => $type->get('prt_name'), + 'description' => $type->get('prt_description'), ]; $I->assertEquals($expected, $transformer->transform($type)); From 08ad6fd210e72b0399c8b8d5a2064c8b455b5516 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 15:01:34 -0400 Subject: [PATCH 20/70] Minor refactoring corrections; Added IndividualTypes get controller --- .../IndividualTypes/GetController.php | 41 +++++++++++++++++++ .../ProductTypes/GetController.php | 9 +--- api/controllers/Users/GetController.php | 32 ++++++++++----- tests/api/Users/GetCest.php | 2 +- 4 files changed, 65 insertions(+), 19 deletions(-) create mode 100644 api/controllers/IndividualTypes/GetController.php diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php new file mode 100644 index 00000000..a8cc817e --- /dev/null +++ b/api/controllers/IndividualTypes/GetController.php @@ -0,0 +1,41 @@ +getRecords(IndividualTypes::class, [], 'idt_name'); + + return $this->format($results, TypesTransformer::class); + } +} diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 4114d515..5fa4d793 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -10,10 +10,9 @@ use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; -use Niden\Transformers\ProductTypesTransformer; +use Niden\Transformers\TypesTransformer; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; -use Phalcon\Mvc\Model\Query\Builder; /** * Class GetController @@ -37,10 +36,6 @@ public function callAction() { $results = $this->getRecords(ProductTypes::class, [], 'prt_name'); - if (count($results) > 0) { - return $this->format($results, ProductTypesTransformer::class); - } else { - $this->halt($this->application, 'Record(s) not found'); - } + return $this->format($results, TypesTransformer::class); } } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 45c18fba..1b36e732 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -31,26 +31,36 @@ class GetController extends Controller use QueryTrait; /** - * Get a user + * Gets users */ public function callAction() { - /** @var int $userId */ - $userId = $this->request->getPost('userId', Filter::FILTER_ABSINT, 0); - $parameters = []; - if ($userId > 0) { - $parameters['usr_id'] = $userId; - } + $parameters = $this->checkParameters(); /** * Execute the query */ $results = $this->getRecords(Users::class, $parameters); - if (count($results) > 0) { - return $this->format($results, UsersTransformer::class); - } else { - $this->halt($this->application, 'Record(s) not found'); + return $this->format($results, UsersTransformer::class); + } + + /** + * Checks the passed parameters and returns the relevant array back + * + * @return array + */ + private function checkParameters(): array + { + $parameters = []; + + /** @var int $userId */ + $userId = $this->request->getPost('userId', Filter::FILTER_ABSINT, 0); + + if ($userId > 0) { + $parameters['usr_id'] = $userId; } + + return $parameters; } } diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 37a05829..142d6185 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -36,7 +36,7 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson(1)); $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Record(s) not found'); + $I->seeSuccessJsonResponse(); } public function loginKnownUserIncorrectSignature(ApiTester $I) From 1a8d14bde56c99c22f9918d7f4bbba37ce88dc02 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 15:30:27 -0400 Subject: [PATCH 21/70] Added route for individual types, implementation and tests --- api/controllers/Companies/AddController.php | 2 - .../IndividualTypes/GetController.php | 9 +-- .../ProductTypes/GetController.php | 7 -- api/controllers/Users/GetController.php | 7 -- library/Providers/RouterProvider.php | 10 ++- tests/_support/Page/Data.php | 11 +-- tests/api/IndividualTypes/GetCest.php | 75 +++++++++++++++++++ tests/unit/library/Providers/RouterCest.php | 8 +- 8 files changed, 93 insertions(+), 36 deletions(-) create mode 100644 tests/api/IndividualTypes/GetCest.php diff --git a/api/controllers/Companies/AddController.php b/api/controllers/Companies/AddController.php index f7dc4c97..27a91568 100644 --- a/api/controllers/Companies/AddController.php +++ b/api/controllers/Companies/AddController.php @@ -12,14 +12,12 @@ use Niden\Validation\CompaniesValidator; use Phalcon\Filter; use Phalcon\Mvc\Controller; -use Phalcon\Mvc\Micro; /** * Class AddController * * @package Niden\Api\Controllers\Companies * - * @property Micro $application * @property Response $response */ class AddController extends Controller diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index a8cc817e..cf688907 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -4,24 +4,17 @@ namespace Niden\Api\Controllers\IndividualTypes; -use Niden\Http\Request; -use Niden\Http\Response; use Niden\Models\IndividualTypes; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; use Phalcon\Mvc\Controller; -use Phalcon\Mvc\Micro; /** * Class GetController * * @package Niden\Api\Controllers\ProductTypes - * - * @property Micro $application - * @property Request $request - * @property Response $response */ class GetController extends Controller { @@ -30,7 +23,7 @@ class GetController extends Controller use ResponseTrait; /** - * Get a user + * Get the individual types */ public function callAction() { diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 5fa4d793..a87c0c43 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -4,24 +4,17 @@ namespace Niden\Api\Controllers\ProductTypes; -use Niden\Http\Request; -use Niden\Http\Response; use Niden\Models\ProductTypes; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; use Phalcon\Mvc\Controller; -use Phalcon\Mvc\Micro; /** * Class GetController * * @package Niden\Api\Controllers\ProductTypes - * - * @property Micro $application - * @property Request $request - * @property Response $response */ class GetController extends Controller { diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 1b36e732..0fa648ab 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -4,8 +4,6 @@ namespace Niden\Api\Controllers\Users; -use Niden\Http\Request; -use Niden\Http\Response; use Niden\Models\Users; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; @@ -13,16 +11,11 @@ use Niden\Transformers\UsersTransformer; use Phalcon\Filter; use Phalcon\Mvc\Controller; -use Phalcon\Mvc\Micro; /** * Class GetController * * @package Niden\Api\Controllers\Users - * - * @property Micro $application - * @property Request $request - * @property Response $response */ class GetController extends Controller { diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index c3c74649..bd98d2b8 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -5,6 +5,7 @@ namespace Niden\Providers; use Niden\Api\Controllers\Companies\AddController as CompaniesAddController; +use Niden\Api\Controllers\IndividualTypes\GetController as IndividualTypesGetController; use Niden\Api\Controllers\ProductTypes\GetController as ProductTypesGetController; use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; @@ -108,10 +109,11 @@ private function getRoutes(): array { return [ // Class, Method, Route, Handler - [LoginController::class, '', 'post', '/login'], - [CompaniesAddController::class, '/companies', 'post', '/add'], - [ProductTypesGetController::class, '/producttypes', 'post', '/get'], - [UsersGetController::class, '/users', 'post', '/get'], + [LoginController::class, '', 'post', '/login'], + [CompaniesAddController::class, '/companies', 'post', '/add'], + [IndividualTypesGetController::class, '/individualtypes', 'post', '/get'], + [ProductTypesGetController::class, '/producttypes', 'post', '/get'], + [UsersGetController::class, '/users', 'post', '/get'], ]; } } diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index f845d411..913b257a 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -4,11 +4,12 @@ class Data { - public static $companiesAddUrl = '/companies/add'; - public static $loginUrl = '/login'; - public static $productTypesGetUrl = '/producttypes/get'; - public static $usersGetUrl = '/users/get'; - public static $wrongUrl = '/sommething'; + public static $companiesAddUrl = '/companies/add'; + public static $loginUrl = '/login'; + public static $individualTypesGetUrl = '/individualtypes/get'; + public static $productTypesGetUrl = '/producttypes/get'; + public static $usersGetUrl = '/users/get'; + public static $wrongUrl = '/sommething'; public static function loginJson() { diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php new file mode 100644 index 00000000..2e08a1f1 --- /dev/null +++ b/tests/api/IndividualTypes/GetCest.php @@ -0,0 +1,75 @@ +addRecord($I); + $token = $I->apiLogin(); + + $typeOne = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'idt_name' => uniqid('type-a-'), + ] + ); + $typeTwo = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'idt_name' => uniqid('type-b-'), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$individualTypesGetUrl, json_encode(['data' => []])); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $typeOne->get('idt_id'), + 'name' => $typeOne->get('idt_name'), + 'description' => $typeOne->get('idt_description'), + ], + [ + 'id' => $typeTwo->get('idt_id'), + 'name' => $typeTwo->get('idt_name'), + 'description' => $typeTwo->get('idt_description'), + ], + ] + ); + } + + public function getIndividualTypesNoData(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendPOST(Data::$individualTypesGetUrl, json_encode(['data' => []])); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + } + + private function addRecord(ApiTester $I) + { + return $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + } +} diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 8bbe7fee..31a36bff 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -29,14 +29,16 @@ public function checkRegistration(UnitTester $I) /** @var RouterInterface $router */ $router = $application->getRouter(); $routes = $router->getRoutes(); - $I->assertEquals(4, count($routes)); + $I->assertEquals(5, count($routes)); $I->assertEquals('POST', $routes[0]->getHttpMethods()); $I->assertEquals('/login', $routes[0]->getPattern()); $I->assertEquals('POST', $routes[1]->getHttpMethods()); $I->assertEquals('/companies/add', $routes[1]->getPattern()); $I->assertEquals('POST', $routes[2]->getHttpMethods()); - $I->assertEquals('/producttypes/get', $routes[2]->getPattern()); + $I->assertEquals('/individualtypes/get', $routes[2]->getPattern()); $I->assertEquals('POST', $routes[3]->getHttpMethods()); - $I->assertEquals('/users/get', $routes[3]->getPattern()); + $I->assertEquals('/producttypes/get', $routes[3]->getPattern()); + $I->assertEquals('POST', $routes[4]->getHttpMethods()); + $I->assertEquals('/users/get', $routes[4]->getPattern()); } } From aea88fc8331a614e56b644dc1fc65d113fe370ec Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 16:55:09 -0400 Subject: [PATCH 22/70] Changed the payload returned to abide by JSONAPI standard regarding resources --- library/Constants/Resources.php | 15 ++++++ library/Transformers/CompaniesTransformer.php | 14 ++++-- library/Transformers/TypesTransformer.php | 12 +++-- library/Transformers/UsersTransformer.php | 16 ++++--- tests/api/Companies/AddCest.php | 14 ++++-- tests/api/IndividualTypes/GetCest.php | 20 +++++--- tests/api/ProductTypes/GetCest.php | 18 +++++-- tests/api/Users/GetCest.php | 48 +++++++++++-------- .../Transformers/CompaniesTransformerCest.php | 14 ++++-- .../IndividualTypesTransformerCest.php | 41 ++++++++++++++++ .../ProductTypesTransformerCest.php | 10 ++-- .../Transformers/UsersTransformerCest.php | 16 ++++--- .../unit/library/Constants/ResourcesCest.php | 19 ++++++++ 13 files changed, 195 insertions(+), 62 deletions(-) create mode 100644 library/Constants/Resources.php create mode 100644 tests/integration/library/Transformers/IndividualTypesTransformerCest.php create mode 100644 tests/unit/library/Constants/ResourcesCest.php diff --git a/library/Constants/Resources.php b/library/Constants/Resources.php new file mode 100644 index 00000000..30fe6cff --- /dev/null +++ b/library/Constants/Resources.php @@ -0,0 +1,15 @@ + $company->get('com_id'), - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), + 'id' => $company->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ], ]; } } diff --git a/library/Transformers/TypesTransformer.php b/library/Transformers/TypesTransformer.php index 3bb3639e..ef67eef9 100644 --- a/library/Transformers/TypesTransformer.php +++ b/library/Transformers/TypesTransformer.php @@ -5,6 +5,7 @@ namespace Niden\Transformers; use League\Fractal\TransformerAbstract; +use Niden\Constants\Resources; use Niden\Exception\ModelException; use Niden\Mvc\Model\AbstractModel; @@ -22,10 +23,15 @@ class TypesTransformer extends TransformerAbstract */ public function transform(AbstractModel $model) { + $prefix = $model->getTablePrefix(); + $type = ('prt' === $prefix) ? Resources::PRODUCT_TYPES : Resources::INDIVIDUAL_TYPES; return [ - 'id' => $model->get(sprintf('%s_id', $model->getTablePrefix())), - 'name' => $model->get(sprintf('%s_name', $model->getTablePrefix())), - 'description' => $model->get(sprintf('%s_description', $model->getTablePrefix())), + 'id' => $model->get(sprintf('%s_id', $prefix)), + 'type' => $type, + 'attributes' => [ + 'name' => $model->get(sprintf('%s_name', $prefix)), + 'description' => $model->get(sprintf('%s_description', $prefix)), + ], ]; } } diff --git a/library/Transformers/UsersTransformer.php b/library/Transformers/UsersTransformer.php index d18a03b6..b9eae7dc 100644 --- a/library/Transformers/UsersTransformer.php +++ b/library/Transformers/UsersTransformer.php @@ -5,6 +5,7 @@ namespace Niden\Transformers; use League\Fractal\TransformerAbstract; +use Niden\Constants\Resources; use Niden\Models\Users; /** @@ -21,12 +22,15 @@ class UsersTransformer extends TransformerAbstract public function transform(Users $user) { return [ - 'id' => $user->get('usr_id'), - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), + 'id' => $user->get('usr_id'), + 'type' => Resources::USERS, + 'attributes' => [ + 'status' => $user->get('usr_status_flag'), + 'username' => $user->get('usr_username'), + 'issuer' => $user->get('usr_issuer'), + 'tokenPassword' => $user->get('usr_token_password'), + 'tokenId' => $user->get('usr_token_id'), + ], ]; } } diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index 02812878..d0b130ac 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\api\Companies; use ApiTester; +use Niden\Constants\Resources; use Niden\Models\Companies; use Niden\Models\Users; use Page\Data; @@ -40,11 +41,14 @@ public function addNewCompany(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $company->get('com_id'), - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), + 'id' => $company->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ], ], ] ); diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index 2e08a1f1..a67540f9 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\api\IndividualTypes; use ApiTester; +use Niden\Constants\Resources; use Niden\Models\IndividualTypes; use Niden\Models\Users; use Page\Data; @@ -34,14 +35,20 @@ public function getIndividualTypes(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $typeOne->get('idt_id'), - 'name' => $typeOne->get('idt_name'), - 'description' => $typeOne->get('idt_description'), + 'id' => $typeOne->get('idt_id'), + 'type' => Resources::INDIVIDUAL_TYPES, + 'attributes' => [ + 'name' => $typeOne->get('idt_name'), + 'description' => $typeOne->get('idt_description'), + ], ], [ - 'id' => $typeTwo->get('idt_id'), - 'name' => $typeTwo->get('idt_name'), - 'description' => $typeTwo->get('idt_description'), + 'id' => $typeTwo->get('idt_id'), + 'type' => Resources::INDIVIDUAL_TYPES, + 'attributes' => [ + 'name' => $typeTwo->get('idt_name'), + 'description' => $typeTwo->get('idt_description'), + ], ], ] ); @@ -56,6 +63,7 @@ public function getIndividualTypesNoData(ApiTester $I) $I->sendPOST(Data::$individualTypesGetUrl, json_encode(['data' => []])); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); } private function addRecord(ApiTester $I) diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index d8cca555..dbd50be8 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\api\ProductTypes; use ApiTester; +use Niden\Constants\Resources; use Niden\Models\ProductTypes; use Niden\Models\Users; use Page\Data; @@ -34,12 +35,20 @@ public function getProductTypes(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $typeOne->get('prt_id'), - 'name' => $typeOne->get('prt_name'), + 'id' => $typeOne->get('prt_id'), + 'type' => Resources::PRODUCT_TYPES, + 'attributes' => [ + 'name' => $typeOne->get('prt_name'), + 'description' => $typeOne->get('prt_description'), + ], ], [ - 'id' => $typeTwo->get('prt_id'), - 'name' => $typeTwo->get('prt_name'), + 'id' => $typeTwo->get('prt_id'), + 'type' => Resources::PRODUCT_TYPES, + 'attributes' => [ + 'name' => $typeTwo->get('prt_name'), + 'description' => $typeTwo->get('prt_description'), + ], ], ] ); @@ -54,6 +63,7 @@ public function getProductTypesNoData(ApiTester $I) $I->sendPOST(Data::$productTypesGetUrl, json_encode(['data' => []])); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); } private function addRecord(ApiTester $I) diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 142d6185..bac4d04f 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -5,6 +5,7 @@ use ApiTester; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Signer\Hmac\Sha512; +use Niden\Constants\Resources; use Niden\Models\Users; use Niden\Traits\TokenTrait; use Page\Data; @@ -169,12 +170,15 @@ public function loginKnownUserValidToken(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $user->get('usr_id'), - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), + 'id' => $user->get('usr_id'), + 'type' => Resources::USERS, + 'attributes' => [ + 'status' => $user->get('usr_status_flag'), + 'username' => $user->get('usr_username'), + 'issuer' => $user->get('usr_issuer'), + 'tokenPassword' => $user->get('usr_token_password'), + 'tokenId' => $user->get('usr_token_id'), + ], ], ] ); @@ -215,20 +219,26 @@ public function getManyUsers(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $userOne->get('usr_id'), - 'status' => $userOne->get('usr_status_flag'), - 'username' => $userOne->get('usr_username'), - 'issuer' => $userOne->get('usr_issuer'), - 'tokenPassword' => $userOne->get('usr_token_password'), - 'tokenId' => $userOne->get('usr_token_id'), + 'id' => $userOne->get('usr_id'), + 'type' => Resources::USERS, + 'attributes' => [ + 'status' => $userOne->get('usr_status_flag'), + 'username' => $userOne->get('usr_username'), + 'issuer' => $userOne->get('usr_issuer'), + 'tokenPassword' => $userOne->get('usr_token_password'), + 'tokenId' => $userOne->get('usr_token_id'), + ], ], [ - 'id' => $userTwo->get('usr_id'), - 'status' => $userTwo->get('usr_status_flag'), - 'username' => $userTwo->get('usr_username'), - 'issuer' => $userTwo->get('usr_issuer'), - 'tokenPassword' => $userTwo->get('usr_token_password'), - 'tokenId' => $userTwo->get('usr_token_id'), + 'id' => $userTwo->get('usr_id'), + 'type' => Resources::USERS, + 'attributes' => [ + 'status' => $userTwo->get('usr_status_flag'), + 'username' => $userTwo->get('usr_username'), + 'issuer' => $userTwo->get('usr_issuer'), + 'tokenPassword' => $userTwo->get('usr_token_password'), + 'tokenId' => $userTwo->get('usr_token_id'), + ], ], ] ); @@ -236,7 +246,7 @@ public function getManyUsers(ApiTester $I) public function getManyUsersWithNoData(ApiTester $I) { - $userOne = $I->haveRecordWithFields( + $I->haveRecordWithFields( Users::class, [ 'usr_status_flag' => 1, diff --git a/tests/integration/library/Transformers/CompaniesTransformerCest.php b/tests/integration/library/Transformers/CompaniesTransformerCest.php index 84a7ebe2..fd5d88cf 100644 --- a/tests/integration/library/Transformers/CompaniesTransformerCest.php +++ b/tests/integration/library/Transformers/CompaniesTransformerCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\integration\library\Transformers; use IntegrationTester; +use Niden\Constants\Resources; use Niden\Models\Companies; use Niden\Transformers\CompaniesTransformer; @@ -28,11 +29,14 @@ public function checkTransformer(IntegrationTester $I) $transformer = new CompaniesTransformer(); $expected = [ - 'id' => $company->get('com_id'), - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), + 'id' => $company->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $company->get('com_name'), + 'address' => $company->get('com_address'), + 'city' => $company->get('com_city'), + 'phone' => $company->get('com_telephone'), + ], ]; $I->assertEquals($expected, $transformer->transform($company)); diff --git a/tests/integration/library/Transformers/IndividualTypesTransformerCest.php b/tests/integration/library/Transformers/IndividualTypesTransformerCest.php new file mode 100644 index 00000000..73734293 --- /dev/null +++ b/tests/integration/library/Transformers/IndividualTypesTransformerCest.php @@ -0,0 +1,41 @@ +haveRecordWithFields( + IndividualTypes::class, + [ + 'idt_name' => uniqid('type-n-'), + 'idt_description' => uniqid('type-d-'), + ] + ); + + $transformer = new TypesTransformer(); + $expected = [ + 'id' => $type->get('idt_id'), + 'type' => Resources::INDIVIDUAL_TYPES, + 'attributes' => [ + 'name' => $type->get('idt_name'), + 'description' => $type->get('idt_description'), + ], + ]; + + $I->assertEquals($expected, $transformer->transform($type)); + } +} diff --git a/tests/integration/library/Transformers/ProductTypesTransformerCest.php b/tests/integration/library/Transformers/ProductTypesTransformerCest.php index c3ff0f14..a1f741b1 100644 --- a/tests/integration/library/Transformers/ProductTypesTransformerCest.php +++ b/tests/integration/library/Transformers/ProductTypesTransformerCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\integration\library\Transformers; use IntegrationTester; +use Niden\Constants\Resources; use Niden\Models\ProductTypes; use Niden\Transformers\TypesTransformer; use function uniqid; @@ -27,9 +28,12 @@ public function checkTransformer(IntegrationTester $I) $transformer = new TypesTransformer(); $expected = [ - 'id' => $type->get('prt_id'), - 'name' => $type->get('prt_name'), - 'description' => $type->get('prt_description'), + 'id' => $type->get('prt_id'), + 'type' => Resources::PRODUCT_TYPES, + 'attributes' => [ + 'name' => $type->get('prt_name'), + 'description' => $type->get('prt_description'), + ], ]; $I->assertEquals($expected, $transformer->transform($type)); diff --git a/tests/integration/library/Transformers/UsersTransformerCest.php b/tests/integration/library/Transformers/UsersTransformerCest.php index 85f0b8ce..9d3f35c5 100644 --- a/tests/integration/library/Transformers/UsersTransformerCest.php +++ b/tests/integration/library/Transformers/UsersTransformerCest.php @@ -3,6 +3,7 @@ namespace Niden\Tests\integration\library\Transformers; use IntegrationTester; +use Niden\Constants\Resources; use Niden\Models\Users; use Niden\Transformers\UsersTransformer; @@ -30,12 +31,15 @@ public function checkTransformer(IntegrationTester $I) $transformer = new UsersTransformer(); $expected = [ - 'id' => $user->get('usr_id'), - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), + 'id' => $user->get('usr_id'), + 'type' => Resources::USERS, + 'attributes' => [ + 'status' => $user->get('usr_status_flag'), + 'username' => $user->get('usr_username'), + 'issuer' => $user->get('usr_issuer'), + 'tokenPassword' => $user->get('usr_token_password'), + 'tokenId' => $user->get('usr_token_id'), + ], ]; $I->assertEquals($expected, $transformer->transform($user)); diff --git a/tests/unit/library/Constants/ResourcesCest.php b/tests/unit/library/Constants/ResourcesCest.php new file mode 100644 index 00000000..70c564ed --- /dev/null +++ b/tests/unit/library/Constants/ResourcesCest.php @@ -0,0 +1,19 @@ +assertEquals('companies', Resources::COMPANIES); + $I->assertEquals('individualTypes', Resources::INDIVIDUAL_TYPES); + $I->assertEquals('individuals', Resources::INDIVIDUALS); + $I->assertEquals('productTypes', Resources::PRODUCT_TYPES); + $I->assertEquals('products', Resources::PRODUCTS); + $I->assertEquals('users', Resources::USERS); + } +} From a6d82ba98c26b156fb43b239f7b10dc985aac461 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 17:20:25 -0400 Subject: [PATCH 23/70] Changed the routes to GET for getting data; Made routes id/all aware --- library/Providers/RouterProvider.php | 12 +++++++---- tests/unit/library/Providers/RouterCest.php | 22 ++++++++++++++------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index bd98d2b8..c07d6799 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -110,10 +110,14 @@ private function getRoutes(): array return [ // Class, Method, Route, Handler [LoginController::class, '', 'post', '/login'], - [CompaniesAddController::class, '/companies', 'post', '/add'], - [IndividualTypesGetController::class, '/individualtypes', 'post', '/get'], - [ProductTypesGetController::class, '/producttypes', 'post', '/get'], - [UsersGetController::class, '/users', 'post', '/get'], + [CompaniesAddController::class, '/companies', 'post', '/'], + [CompaniesAddController::class, '/companies', 'post', '/{companyId:[0-9]+}'], + [IndividualTypesGetController::class, '/individualtypes', 'get', '/'], + [IndividualTypesGetController::class, '/individualtypes', 'get', '/{typeId:[0-9]+}'], + [ProductTypesGetController::class, '/producttypes', 'get', '/'], + [ProductTypesGetController::class, '/producttypes', 'get', '/{typeId:[0-9]+}'], + [UsersGetController::class, '/users', 'get', '/'], + [UsersGetController::class, '/users', 'get', '/{userId:[0-9]+}'], ]; } } diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 31a36bff..a0102df1 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -29,16 +29,24 @@ public function checkRegistration(UnitTester $I) /** @var RouterInterface $router */ $router = $application->getRouter(); $routes = $router->getRoutes(); - $I->assertEquals(5, count($routes)); + $I->assertEquals(9, count($routes)); $I->assertEquals('POST', $routes[0]->getHttpMethods()); $I->assertEquals('/login', $routes[0]->getPattern()); $I->assertEquals('POST', $routes[1]->getHttpMethods()); - $I->assertEquals('/companies/add', $routes[1]->getPattern()); + $I->assertEquals('/companies', $routes[1]->getPattern()); $I->assertEquals('POST', $routes[2]->getHttpMethods()); - $I->assertEquals('/individualtypes/get', $routes[2]->getPattern()); - $I->assertEquals('POST', $routes[3]->getHttpMethods()); - $I->assertEquals('/producttypes/get', $routes[3]->getPattern()); - $I->assertEquals('POST', $routes[4]->getHttpMethods()); - $I->assertEquals('/users/get', $routes[4]->getPattern()); + $I->assertEquals('/companies/{companyId:[0-9]+}', $routes[2]->getPattern()); + $I->assertEquals('GET', $routes[3]->getHttpMethods()); + $I->assertEquals('/individualtypes', $routes[3]->getPattern()); + $I->assertEquals('GET', $routes[4]->getHttpMethods()); + $I->assertEquals('/individualtypes/{typeId:[0-9]+}', $routes[4]->getPattern()); + $I->assertEquals('GET', $routes[5]->getHttpMethods()); + $I->assertEquals('/producttypes', $routes[5]->getPattern()); + $I->assertEquals('GET', $routes[6]->getHttpMethods()); + $I->assertEquals('/producttypes/{typeId:[0-9]+}', $routes[6]->getPattern()); + $I->assertEquals('GET', $routes[7]->getHttpMethods()); + $I->assertEquals('/users', $routes[7]->getPattern()); + $I->assertEquals('GET', $routes[8]->getHttpMethods()); + $I->assertEquals('/users/{userId:[0-9]+}', $routes[8]->getPattern()); } } From 7251e77b49e256db41c5604ff50febcecfc07a2b Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 17:21:01 -0400 Subject: [PATCH 24/70] Corrected app URLs for testing --- tests/_support/Page/Data.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index 913b257a..d2bc76c6 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -4,12 +4,12 @@ class Data { - public static $companiesAddUrl = '/companies/add'; - public static $loginUrl = '/login'; - public static $individualTypesGetUrl = '/individualtypes/get'; - public static $productTypesGetUrl = '/producttypes/get'; - public static $usersGetUrl = '/users/get'; - public static $wrongUrl = '/sommething'; + public static $companiesUrl = '/companies'; + public static $loginUrl = '/login'; + public static $individualTypesUrl = '/individualtypes'; + public static $productTypesUrl = '/producttypes'; + public static $usersUrl = '/users'; + public static $wrongUrl = '/sommething'; public static function loginJson() { From 952581784e7e00b646f68610471b7d4e5a3d0f3e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 17:21:17 -0400 Subject: [PATCH 25/70] Added userId parameter for the user controller; Adjusted tests for the new route changes --- api/controllers/Users/GetController.php | 20 ++++++++++----- tests/api/Users/GetCest.php | 34 ++++++++++++------------- 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 0fa648ab..d79f58d4 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -25,10 +25,14 @@ class GetController extends Controller /** * Gets users + * + * @param int $userId + * + * @return array */ - public function callAction() + public function callAction($userId = 0) { - $parameters = $this->checkParameters(); + $parameters = $this->checkParameters($userId); /** * Execute the query @@ -41,17 +45,19 @@ public function callAction() /** * Checks the passed parameters and returns the relevant array back * + * @param int $userId + * * @return array */ - private function checkParameters(): array + private function checkParameters($userId = 0): array { $parameters = []; - /** @var int $userId */ - $userId = $this->request->getPost('userId', Filter::FILTER_ABSINT, 0); + /** @var int $localUserId */ + $localUserId = $this->filter->sanitize($userId, Filter::FILTER_ABSINT); - if ($userId > 0) { - $parameters['usr_id'] = $userId; + if ($localUserId > 0) { + $parameters['usr_id'] = $localUserId; } return $parameters; diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index bac4d04f..6ab1c732 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -17,7 +17,7 @@ class GetCest public function loginKnownUserNoToken(ApiTester $I) { $I->deleteHeader('Authorization'); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson(1)); + $I->sendGET(Data::$usersUrl . '/1'); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -35,7 +35,7 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) $token = $data['token']; $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson(1)); + $I->sendGET(Data::$usersUrl . '/1'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } @@ -63,7 +63,7 @@ public function loginKnownUserIncorrectSignature(ApiTester $I) $wrongToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $wrongToken); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); + $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -91,7 +91,7 @@ public function loginKnownUserExpiredToken(ApiTester $I) $expiredToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $expiredToken); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); + $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -119,7 +119,7 @@ public function loginKnownUserInvalidToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); + $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -147,7 +147,7 @@ public function loginKnownUserInvalidUserInToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($record->get('usr_id'))); + $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } @@ -160,24 +160,24 @@ public function loginKnownUserCorrectToken(ApiTester $I) public function loginKnownUserValidToken(ApiTester $I) { - $user = $this->addRecord($I); - $token = $I->apiLogin(); + $record = $this->addRecord($I); + $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl, Data::usersGetJson($user->get('usr_id'))); + $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( [ [ - 'id' => $user->get('usr_id'), + 'id' => $record->get('usr_id'), 'type' => Resources::USERS, 'attributes' => [ - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), + 'status' => $record->get('usr_status_flag'), + 'username' => $record->get('usr_username'), + 'issuer' => $record->get('usr_issuer'), + 'tokenPassword' => $record->get('usr_token_password'), + 'tokenId' => $record->get('usr_token_id'), ], ], ] @@ -213,7 +213,7 @@ public function getManyUsers(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl); + $I->sendGET(Data::$usersUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -261,7 +261,7 @@ public function getManyUsersWithNoData(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$usersGetUrl); + $I->sendGET(Data::$usersUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); } From d1f1ef89e411204a4328357351459bdaf634399d Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 17:29:47 -0400 Subject: [PATCH 26/70] Added base controller; Refactor id parameter check; Adjusted product type tests --- api/controllers/BaseController.php | 44 +++++++++++++++++++ .../ProductTypes/GetController.php | 15 ++++--- api/controllers/Users/GetController.php | 34 ++------------ tests/api/ProductTypes/GetCest.php | 4 +- 4 files changed, 60 insertions(+), 37 deletions(-) create mode 100644 api/controllers/BaseController.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php new file mode 100644 index 00000000..772ae53c --- /dev/null +++ b/api/controllers/BaseController.php @@ -0,0 +1,44 @@ +filter->sanitize($recordId, Filter::FILTER_ABSINT); + + if ($localId > 0) { + $parameters[$field] = $localId; + } + + return $parameters; + } +} diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index a87c0c43..1b5538f9 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -4,30 +4,35 @@ namespace Niden\Api\Controllers\ProductTypes; +use Niden\Api\Controllers\BaseController; use Niden\Models\ProductTypes; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; -use Phalcon\Mvc\Controller; /** * Class GetController * * @package Niden\Api\Controllers\ProductTypes */ -class GetController extends Controller +class GetController extends BaseController { use FractalTrait; use QueryTrait; use ResponseTrait; /** - * Get a user + * Get product types + * + * @param int $typeId + * + * @return array */ - public function callAction() + public function callAction($typeId = 0) { - $results = $this->getRecords(ProductTypes::class, [], 'prt_name'); + $parameters = $this->checkIdParameter('prt_id', $typeId); + $results = $this->getRecords(ProductTypes::class, $parameters, 'prt_name'); return $this->format($results, TypesTransformer::class); } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index d79f58d4..903868ac 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -4,20 +4,19 @@ namespace Niden\Api\Controllers\Users; +use Niden\Api\Controllers\BaseController; use Niden\Models\Users; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Transformers\UsersTransformer; -use Phalcon\Filter; -use Phalcon\Mvc\Controller; /** * Class GetController * * @package Niden\Api\Controllers\Users */ -class GetController extends Controller +class GetController extends BaseController { use FractalTrait; use ResponseTrait; @@ -32,34 +31,9 @@ class GetController extends Controller */ public function callAction($userId = 0) { - $parameters = $this->checkParameters($userId); - - /** - * Execute the query - */ - $results = $this->getRecords(Users::class, $parameters); + $parameters = $this->checkIdParameter('usr_id', $userId); + $results = $this->getRecords(Users::class, $parameters, 'usr_username'); return $this->format($results, UsersTransformer::class); } - - /** - * Checks the passed parameters and returns the relevant array back - * - * @param int $userId - * - * @return array - */ - private function checkParameters($userId = 0): array - { - $parameters = []; - - /** @var int $localUserId */ - $localUserId = $this->filter->sanitize($userId, Filter::FILTER_ABSINT); - - if ($localUserId > 0) { - $parameters['usr_id'] = $localUserId; - } - - return $parameters; - } } diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index dbd50be8..927479f6 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -29,7 +29,7 @@ public function getProductTypes(ApiTester $I) ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$productTypesGetUrl, json_encode(['data' => []])); + $I->sendGET(Data::$productTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -60,7 +60,7 @@ public function getProductTypesNoData(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$productTypesGetUrl, json_encode(['data' => []])); + $I->sendGET(Data::$productTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); From b725fa256454ebb73dbdad9f234afc1d2bd2bcb4 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 18:09:34 -0400 Subject: [PATCH 27/70] Removed requirement to POST JSON; Corrected tests to use POSTed and GETed values --- .../IndividualTypes/GetController.php | 15 ++- library/Middleware/PayloadMiddleware.php | 102 ------------------ library/Providers/RouterProvider.php | 6 +- tests/_support/Page/Data.php | 39 ++----- tests/api/Companies/AddCest.php | 4 +- tests/api/IncorrectPayloadCest.php | 19 ---- tests/api/IndividualTypes/GetCest.php | 4 +- tests/api/LoginCest.php | 27 +---- tests/unit/library/Providers/RouterCest.php | 35 +++--- 9 files changed, 46 insertions(+), 205 deletions(-) delete mode 100755 library/Middleware/PayloadMiddleware.php delete mode 100644 tests/api/IncorrectPayloadCest.php diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index cf688907..b042d8c2 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -4,19 +4,19 @@ namespace Niden\Api\Controllers\IndividualTypes; +use Niden\Api\Controllers\BaseController; use Niden\Models\IndividualTypes; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; -use Phalcon\Mvc\Controller; /** * Class GetController * - * @package Niden\Api\Controllers\ProductTypes + * @package Niden\Api\Controllers\IndividualTypes */ -class GetController extends Controller +class GetController extends BaseController { use FractalTrait; use QueryTrait; @@ -24,10 +24,15 @@ class GetController extends Controller /** * Get the individual types + * + * @param int $typeId + * + * @return array */ - public function callAction() + public function callAction($typeId = 0) { - $results = $this->getRecords(IndividualTypes::class, [], 'idt_name'); + $parameters = $this->checkIdParameter('idt_id', $typeId); + $results = $this->getRecords(IndividualTypes::class, $parameters, 'idt_name'); return $this->format($results, TypesTransformer::class); } diff --git a/library/Middleware/PayloadMiddleware.php b/library/Middleware/PayloadMiddleware.php deleted file mode 100755 index 39dc17ff..00000000 --- a/library/Middleware/PayloadMiddleware.php +++ /dev/null @@ -1,102 +0,0 @@ -getService('request'); - if (true === $request->isPost()) { - $body = $request->getRawBody(); - if (true !== empty($body)) { - $data = json_decode($body, true); - $this->checkJson(); - $this->checkDataElement($data); - $this->parsePayload($data); - } - } - - return true; - } catch (Exception $ex) { - $this->halt($api, $ex->getMessage()); - - return false; - } - } - - /** - * Call me - * - * @param Micro $api - * - * @return bool - */ - public function call(Micro $api) - { - return true; - } - - /** - * Checks if the 'data' element has been sent - * - * @param array $data - * - * @throws Exception - */ - private function checkDataElement(array $data) - { - if (true !== isset($data['data'])) { - throw new Exception('"data" element not present in the payload'); - } - } - - /** - * Check if we have a JSON error - * - * @throws Exception - */ - private function checkJson() - { - if (JSON_ERROR_NONE !== json_last_error()) { - throw new Exception('Malformed JSON'); - } - } - - /** - * Parses the payload and injects the posted data in the POST array - * - * @param array $data - */ - private function parsePayload(array $data) - { - $_POST = $data['data']; - } -} diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index c07d6799..46130781 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -91,7 +91,6 @@ private function getMiddleware(): array { return [ NotFoundMiddleware::class => 'before', - PayloadMiddleware::class => 'before', AuthenticationMiddleware::class => 'before', TokenUserMiddleware::class => 'before', TokenVerificationMiddleware::class => 'before', @@ -109,9 +108,10 @@ private function getRoutes(): array { return [ // Class, Method, Route, Handler - [LoginController::class, '', 'post', '/login'], + [LoginController::class, '/login', 'post', '/'], [CompaniesAddController::class, '/companies', 'post', '/'], - [CompaniesAddController::class, '/companies', 'post', '/{companyId:[0-9]+}'], +// [CompaniesAddController::class, '/companies', 'get', '/'], +// [CompaniesAddController::class, '/companies', 'get', '/{companyId:[0-9]+}'], [IndividualTypesGetController::class, '/individualtypes', 'get', '/'], [IndividualTypesGetController::class, '/individualtypes', 'get', '/{typeId:[0-9]+}'], [ProductTypesGetController::class, '/producttypes', 'get', '/'], diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index d2bc76c6..fb80c1cb 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -13,40 +13,19 @@ class Data public static function loginJson() { - return json_encode( - [ - 'data' => [ - 'username' => 'testuser', - 'password' => 'testpassword', - ] - ] - ); - } - - public static function usersGetJson($userId = 0) - { - $payload = [ - 'data' => [], + return [ + 'username' => 'testuser', + 'password' => 'testpassword', ]; - - if ($userId > 0) { - $payload['data']['userId'] = $userId; - } - - return json_encode($payload); } public static function companyAddJson($name, $address = '', $city = '', $phone = '') { - return json_encode( - [ - 'data' => [ - 'name' => $name, - 'address' => $address, - 'city' => $city, - 'phone' => $phone, - ] - ] - ); + return [ + 'name' => $name, + 'address' => $address, + 'city' => $city, + 'phone' => $phone, + ]; } } diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index d0b130ac..eac85ed0 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -19,7 +19,7 @@ public function addNewCompany(ApiTester $I) $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendPOST( - Data::$companiesAddUrl, + Data::$companiesUrl, Data::companyAddJson( $name, '123 Phalcon way', @@ -70,7 +70,7 @@ public function addNewCompanyWithExistingName(ApiTester $I) $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendPOST( - Data::$companiesAddUrl, + Data::$companiesUrl, Data::companyAddJson( $name, '123 Phalcon way', diff --git a/tests/api/IncorrectPayloadCest.php b/tests/api/IncorrectPayloadCest.php deleted file mode 100644 index 7b161c77..00000000 --- a/tests/api/IncorrectPayloadCest.php +++ /dev/null @@ -1,19 +0,0 @@ -sendPOST(Data::$usersGetUrl, '{"key": "value}'); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('Malformed JSON'); - } -} diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index a67540f9..e0b56b5d 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -29,7 +29,7 @@ public function getIndividualTypes(ApiTester $I) ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$individualTypesGetUrl, json_encode(['data' => []])); + $I->sendGET(Data::$individualTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -60,7 +60,7 @@ public function getIndividualTypesNoData(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendPOST(Data::$individualTypesGetUrl, json_encode(['data' => []])); + $I->sendGET(Data::$individualTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); diff --git a/tests/api/LoginCest.php b/tests/api/LoginCest.php index 01eff31a..0084e50d 100644 --- a/tests/api/LoginCest.php +++ b/tests/api/LoginCest.php @@ -11,33 +11,14 @@ class LoginCest { - public function loginNoDataElement(ApiTester $I) - { - $I->sendPOST( - Data::$loginUrl, - json_encode( - [ - 'username' => 'user', - 'password' => 'pass', - ] - ) - ); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('"data" element not present in the payload'); - } - public function loginUnknownUser(ApiTester $I) { $I->sendPOST( Data::$loginUrl, - json_encode( - [ - 'data' => [ - 'username' => 'user', - 'password' => 'pass', - ] - ] - ) + [ + 'username' => 'user', + 'password' => 'pass', + ] ); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Incorrect credentials'); diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index a0102df1..0622fbd5 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -29,24 +29,21 @@ public function checkRegistration(UnitTester $I) /** @var RouterInterface $router */ $router = $application->getRouter(); $routes = $router->getRoutes(); - $I->assertEquals(9, count($routes)); - $I->assertEquals('POST', $routes[0]->getHttpMethods()); - $I->assertEquals('/login', $routes[0]->getPattern()); - $I->assertEquals('POST', $routes[1]->getHttpMethods()); - $I->assertEquals('/companies', $routes[1]->getPattern()); - $I->assertEquals('POST', $routes[2]->getHttpMethods()); - $I->assertEquals('/companies/{companyId:[0-9]+}', $routes[2]->getPattern()); - $I->assertEquals('GET', $routes[3]->getHttpMethods()); - $I->assertEquals('/individualtypes', $routes[3]->getPattern()); - $I->assertEquals('GET', $routes[4]->getHttpMethods()); - $I->assertEquals('/individualtypes/{typeId:[0-9]+}', $routes[4]->getPattern()); - $I->assertEquals('GET', $routes[5]->getHttpMethods()); - $I->assertEquals('/producttypes', $routes[5]->getPattern()); - $I->assertEquals('GET', $routes[6]->getHttpMethods()); - $I->assertEquals('/producttypes/{typeId:[0-9]+}', $routes[6]->getPattern()); - $I->assertEquals('GET', $routes[7]->getHttpMethods()); - $I->assertEquals('/users', $routes[7]->getPattern()); - $I->assertEquals('GET', $routes[8]->getHttpMethods()); - $I->assertEquals('/users/{userId:[0-9]+}', $routes[8]->getPattern()); + $expected = [ + ['POST', '/login'], + ['POST', '/companies'], + ['GET', '/individualtypes'], + ['GET', '/individualtypes/{typeId:[0-9]+}'], + ['GET', '/producttypes'], + ['GET', '/producttypes/{typeId:[0-9]+}'], + ['GET', '/users'], + ['GET', '/users/{userId:[0-9]+}'], + ]; + + $I->assertEquals(8, count($routes)); + foreach ($routes as $index => $route) { + $I->assertEquals($expected[$index][0], $route->getHttpMethods()); + $I->assertEquals($expected[$index][1], $route->getPattern()); + } } } From 620c5aa00f66012bd38bf47b27684744ab3666f6 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 18:52:19 -0400 Subject: [PATCH 28/70] Added more information in the readme --- README.md | 150 +++++++++++++++++++++++++++++------------------------- 1 file changed, 82 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 8fdb5adf..5c00d588 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,6 @@ As part of the security of the API, [JWT](https://jwt.io) are used. JSON Web Tok - Stop execution as early as possible when an error occurs - Execution - NotFound - 404 when the resource requested is not found - - Payload - Check the posted JSON string if it is correct - Authentication - After a `/login` checks the `Authentication` header - TokenUser - When a token is supplied, check if it corresponds to a user in the database - TokenVerification - When a token is supplied, check if it is correctly signed @@ -33,56 +32,53 @@ As part of the security of the API, [JWT](https://jwt.io) are used. JSON Web Tok ### Usage #### Requests -All requests to the API have be submitted using `POST`. All requests must send a JSON string with one root element `data`. Data needed for the request must be under the `data` element +The routes available are: -The endpoints are: +| Method | Route | Payload | +|--------|-------------------|-------------------------------------------------------------------------------------------------------------| +| `POST` | `login` | `{"username": string, "password": string}` | +| `POST` | `companies` | `{"name": string, "address": , "city": , "phone": ` | +| `GET` | `individualtypes` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | +| `GET` | `producttypes` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | +| `GET` | `users` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | -`/login` -| Method | Payload | -|--------|--------------------------------------------------------| -| `POST` | `{"data": {"username": "niden", "password": "12345"}}` | - -`/user/get` - -| Method | Payload | -|--------|---------------------------------------------------------| -| `POST` | `{"data": {"userId": 1}}` | with Bearer Authentication` | - -`/usesr/get` - -| Method | Payload | -|--------|---------| -| `POST` | Empty | - #### Responses ##### Structure +**Top Elements** +- `jsonapi` Contains the `version` of the API as a sub element +- `data` Data returned. Is not present if the `errors` is present +- `errors` Collection of errors that occurred in this request. Is not present if the `data` is present +- `meta` Contains `timestamp` and `hash` of the `json_encode($data)` or `json_encode($errors)` + +After a `GET` the API will always return a collection of records, even if there is only one returned. If no data is found, an empty resultset will be returned. + +Each endpoint returns records that follow this structure: ```json { - "jsonapi": { - "version": "1.0" // Version of the API - }, - "data": [ - // Payload returned if successful reply (not present if there is an error) - ], - "errors": [ - "Error 1", // Collection of errors - "Error 2" - }, - "meta": { - "timestamp": "2018-06-08T15:04:34+00:00", // Timestamp of the response - "hash": "e6d4d57162ae0f220c8649ae50a2b79fd1cb2c60" // Hash of the timestamp and payload (`data` if success, `error` if failure) + "id": 1051, + "type": "users", + "attributes": { + "status": 1, + "username": "niden", + "issuer": "https:\/\/niden.net", + "tokenPassword": "11110000", + "tokenId": "11001100" } } ``` -##### 404 + +The record always has `id` and `type` present at the top level. `id` is the unique id of the record in the database. `type` is a string representation of what the object is. In the above example it is a `users` record. Additional data from each record are under the `attributes` node. + +#### Samples +**404** ```json { "jsonapi": { "version": "1.0" }, "errors": { - "404 Not Found" + "404 not found" }, "meta": { "timestamp": "2018-06-08T15:04:34+00:00", @@ -91,14 +87,16 @@ The endpoints are: } ``` -##### Error +**Error** + ```json { "jsonapi": { "version": "1.0" }, "errors": { - "Description of the error" + "Description of the error no 1", + "Description of the error no 2" }, "meta": { "timestamp": "2018-06-08T15:04:34+00:00", @@ -107,14 +105,13 @@ The endpoints are: } ``` -##### Success +##### Success ```json { "jsonapi": { "version": "1.0" }, "data": [ - // Data returned ], "meta": { "timestamp": "2018-06-08T15:04:34+00:00", @@ -122,24 +119,29 @@ The endpoints are: } } ``` - -`/login` + +`POST /login` +``` +"username" => "niden" +"password" => "110011" +``` + ```json { "jsonapi": { "version": "1.0" }, "data": { - "token": "ab.cd.ef" - }, + "token": "aa.bb.cc" + ], "meta": { - "timestamp": "2018-06-08T15:04:34+00:00", - "hash": "e6d4d57162ae0f220c8649ae50a2b79fd1cb2c60" + "timestamp": "2018-06-08T15:07:35+00:00", + "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" } } ``` - -`/user/get` + +`GET /users/get/1051` ```json { "jsonapi": { @@ -147,21 +149,25 @@ The endpoints are: }, "data": [ { - "id": 1244, - "status": 1, - "username": "phalcon", - "issuer": "https:\/\/phalconphp.com", - "tokenPassword": "00001111", - "tokenId": "99009900" + "id": 1051, + "type": "users", + "attributes": { + "status": 1, + "username": "niden", + "issuer": "https:\/\/niden.net", + "tokenPassword": "11110000", + "tokenId": "11001100" + } } ], "meta": { - "timestamp": "2018-06-08T17:05:14+00:00", - "hash": "344d9766003e14409ab08df863d37d1ef44e5b60" + "timestamp": "2018-06-08T15:07:35+00:00", + "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" } } ``` -`/users/get` + +`GET /users/get` ```json { "jsonapi": { @@ -170,19 +176,25 @@ The endpoints are: "data": [ { "id": 1051, - "status": 1, - "username": "niden", - "issuer": "https:\/\/niden.net", - "tokenPassword": "11110000", - "tokenId": "11001100" + "type": "users", + "attributes": { + "status": 1, + "username": "niden", + "issuer": "https:\/\/niden.net", + "tokenPassword": "11110000", + "tokenId": "11001100" + } }, { "id": 1244, - "status": 1, - "username": "phalcon", - "issuer": "https:\/\/phalconphp.com", - "tokenPassword": "00001111", - "tokenId": "99009900" + "type": "users", + "attributes": { + "status": 1, + "username": "phalcon", + "issuer": "https:\/\/phalconphp.com", + "tokenPassword": "00001111", + "tokenId": "99009900" + } } ], "meta": { @@ -193,6 +205,8 @@ The endpoints are: ``` ### TODO -- Remove `/login` endpoint. Leave the generation of the JWT to the consumer (maybe) -- Perhaps add a new claim to the token tied to the device? `setClaim('deviceId', 'Web-Server')`. This will allow the client application to invalidate access to a device that has already been logged in. +- Work on companies `GET` +- Work on relationships and data returned - Write examples of code to send to the client +- Work on pagination +- Perhaps add a new claim to the token tied to the device? `setClaim('deviceId', 'Web-Server')`. This will allow the client application to invalidate access to a device that has already been logged in. From 327eb2b19f8c35dff7c0e32e12f551872c674994 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 21:38:29 -0400 Subject: [PATCH 29/70] Added routes for companies get --- library/Providers/RouterProvider.php | 6 +++--- tests/unit/library/Providers/RouterCest.php | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index 46130781..d2becd0a 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -5,12 +5,12 @@ namespace Niden\Providers; use Niden\Api\Controllers\Companies\AddController as CompaniesAddController; +use Niden\Api\Controllers\Companies\GetController as CompaniesGetController; use Niden\Api\Controllers\IndividualTypes\GetController as IndividualTypesGetController; use Niden\Api\Controllers\ProductTypes\GetController as ProductTypesGetController; use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; use Niden\Middleware\NotFoundMiddleware; -use Niden\Middleware\PayloadMiddleware; use Niden\Middleware\AuthenticationMiddleware; use Niden\Middleware\ResponseMiddleware; use Niden\Middleware\TokenUserMiddleware; @@ -110,8 +110,8 @@ private function getRoutes(): array // Class, Method, Route, Handler [LoginController::class, '/login', 'post', '/'], [CompaniesAddController::class, '/companies', 'post', '/'], -// [CompaniesAddController::class, '/companies', 'get', '/'], -// [CompaniesAddController::class, '/companies', 'get', '/{companyId:[0-9]+}'], + [CompaniesGetController::class, '/companies', 'get', '/'], + [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], [IndividualTypesGetController::class, '/individualtypes', 'get', '/'], [IndividualTypesGetController::class, '/individualtypes', 'get', '/{typeId:[0-9]+}'], [ProductTypesGetController::class, '/producttypes', 'get', '/'], diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 0622fbd5..cbf1acdc 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -32,6 +32,8 @@ public function checkRegistration(UnitTester $I) $expected = [ ['POST', '/login'], ['POST', '/companies'], + ['GET', '/cpompanies'], + ['GET', '/cpompanies/{typeId:[0-9]+}'], ['GET', '/individualtypes'], ['GET', '/individualtypes/{typeId:[0-9]+}'], ['GET', '/producttypes'], @@ -40,7 +42,7 @@ public function checkRegistration(UnitTester $I) ['GET', '/users/{userId:[0-9]+}'], ]; - $I->assertEquals(8, count($routes)); + $I->assertEquals(10, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); From 47ea12eff14ea5d036d105e21161c930121942cc Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 18 Jul 2018 21:38:43 -0400 Subject: [PATCH 30/70] Added companies get controller; refactored get controllers --- api/controllers/BaseController.php | 28 +++++++++++++++ api/controllers/Companies/GetController.php | 35 +++++++++++++++++++ .../IndividualTypes/GetController.php | 18 ++++------ .../ProductTypes/GetController.php | 18 ++++------ api/controllers/Users/GetController.php | 18 ++++------ 5 files changed, 84 insertions(+), 33 deletions(-) create mode 100644 api/controllers/Companies/GetController.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 772ae53c..79c57ae4 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -8,6 +8,7 @@ use Niden\Http\Request; use Niden\Http\Response; use Niden\Models\Users; +use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; use Phalcon\Filter; @@ -20,6 +21,9 @@ */ class BaseController extends Controller { + use FractalTrait; + use QueryTrait; + /** * Checks the passed id parameter and returns the relevant array back * @@ -41,4 +45,28 @@ protected function checkIdParameter(string $field, $recordId = 0): array return $parameters; } + + /** + * Processes getting records as a while or one using an id + * + * @param string $model + * @param string $field + * @param string $transformer + * @param int $recordId + * @param string $orderBy + * + * @return array + */ + protected function processCall( + string $model, + string $field, + string $transformer, + $recordId = 0, + string $orderBy = '' + ) { + $parameters = $this->checkIdParameter($field, $recordId); + $results = $this->getRecords($model, $parameters, $orderBy); + + return $this->format($results, $transformer); + } } diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php new file mode 100644 index 00000000..105cb2bb --- /dev/null +++ b/api/controllers/Companies/GetController.php @@ -0,0 +1,35 @@ +processCall( + Companies::class, + 'com_id', + CompaniesTransformer::class, + $companyId, + 'com_name' + ); + } +} diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index b042d8c2..174294c5 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -6,9 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\IndividualTypes; -use Niden\Traits\FractalTrait; -use Niden\Traits\QueryTrait; -use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; /** @@ -18,10 +15,6 @@ */ class GetController extends BaseController { - use FractalTrait; - use QueryTrait; - use ResponseTrait; - /** * Get the individual types * @@ -31,9 +24,12 @@ class GetController extends BaseController */ public function callAction($typeId = 0) { - $parameters = $this->checkIdParameter('idt_id', $typeId); - $results = $this->getRecords(IndividualTypes::class, $parameters, 'idt_name'); - - return $this->format($results, TypesTransformer::class); + return $this->processCall( + IndividualTypes::class, + 'idt_id', + TypesTransformer::class, + $typeId, + 'idt_name' + ); } } diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 1b5538f9..a2282d14 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -6,9 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\ProductTypes; -use Niden\Traits\FractalTrait; -use Niden\Traits\QueryTrait; -use Niden\Traits\ResponseTrait; use Niden\Transformers\TypesTransformer; /** @@ -18,10 +15,6 @@ */ class GetController extends BaseController { - use FractalTrait; - use QueryTrait; - use ResponseTrait; - /** * Get product types * @@ -31,9 +24,12 @@ class GetController extends BaseController */ public function callAction($typeId = 0) { - $parameters = $this->checkIdParameter('prt_id', $typeId); - $results = $this->getRecords(ProductTypes::class, $parameters, 'prt_name'); - - return $this->format($results, TypesTransformer::class); + return $this->processCall( + ProductTypes::class, + 'prt_id', + TypesTransformer::class, + $typeId, + 'prt_name' + ); } } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 903868ac..8da6fe73 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -6,9 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\Users; -use Niden\Traits\FractalTrait; -use Niden\Traits\QueryTrait; -use Niden\Traits\ResponseTrait; use Niden\Transformers\UsersTransformer; /** @@ -18,10 +15,6 @@ */ class GetController extends BaseController { - use FractalTrait; - use ResponseTrait; - use QueryTrait; - /** * Gets users * @@ -31,9 +24,12 @@ class GetController extends BaseController */ public function callAction($userId = 0) { - $parameters = $this->checkIdParameter('usr_id', $userId); - $results = $this->getRecords(Users::class, $parameters, 'usr_username'); - - return $this->format($results, UsersTransformer::class); + return $this->processCall( + Users::class, + 'usr_id', + UsersTransformer::class, + $userId, + 'usr_username' + ); } } From 8b1c5efbed24680de3a3701feb711eb5ef5c008e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 19 Jul 2018 13:38:12 -0400 Subject: [PATCH 31/70] Added companies get controller and routes --- README.md | 2 +- tests/api/Companies/GetCest.php | 127 ++++++++++++++++++++ tests/unit/library/Providers/RouterCest.php | 4 +- 3 files changed, 130 insertions(+), 3 deletions(-) create mode 100644 tests/api/Companies/GetCest.php diff --git a/README.md b/README.md index 5c00d588..ce298249 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ The record always has `id` and `type` present at the top level. `id` is the uniq }, "data": { "token": "aa.bb.cc" - ], + }, "meta": { "timestamp": "2018-06-08T15:07:35+00:00", "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php new file mode 100644 index 00000000..e6bc0fc2 --- /dev/null +++ b/tests/api/Companies/GetCest.php @@ -0,0 +1,127 @@ +addRecord($I); + $token = $I->apiLogin(); + + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'com_name' => uniqid('com-a-'), + 'com_address' => uniqid(), + 'com_city' => uniqid(), + 'com_telephone' => uniqid(), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('com_id')); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $comOne->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $comOne->get('com_name'), + 'address' => $comOne->get('com_address'), + 'city' => $comOne->get('com_city'), + 'phone' => $comOne->get('com_telephone'), + ], + ], + ] + ); + } + + public function getCompanies(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'com_name' => uniqid('com-a-'), + 'com_address' => uniqid(), + 'com_city' => uniqid(), + 'com_telephone' => uniqid(), + ] + ); + $comTwo = $I->haveRecordWithFields( + Companies::class, + [ + 'com_name' => uniqid('com-b-'), + 'com_address' => uniqid(), + 'com_city' => uniqid(), + 'com_telephone' => uniqid(), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $comOne->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $comOne->get('com_name'), + 'address' => $comOne->get('com_address'), + 'city' => $comOne->get('com_city'), + 'phone' => $comOne->get('com_telephone'), + ], + ], + [ + 'id' => $comTwo->get('com_id'), + 'type' => Resources::COMPANIES, + 'attributes' => [ + 'name' => $comTwo->get('com_name'), + 'address' => $comTwo->get('com_address'), + 'city' => $comTwo->get('com_city'), + 'phone' => $comTwo->get('com_telephone'), + ], + ], + ] + ); + } + + public function getCompaniesNoData(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function addRecord(ApiTester $I) + { + return $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + } +} diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index cbf1acdc..37d15bbc 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -32,8 +32,8 @@ public function checkRegistration(UnitTester $I) $expected = [ ['POST', '/login'], ['POST', '/companies'], - ['GET', '/cpompanies'], - ['GET', '/cpompanies/{typeId:[0-9]+}'], + ['GET', '/companies'], + ['GET', '/companies/{companyId:[0-9]+}'], ['GET', '/individualtypes'], ['GET', '/individualtypes/{typeId:[0-9]+}'], ['GET', '/producttypes'], From 1e2a908bce57f7b36c84f0e689ad1336e3878ad0 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 19 Jul 2018 13:38:51 -0400 Subject: [PATCH 32/70] Removed blank line --- library/Providers/RouterProvider.php | 1 - 1 file changed, 1 deletion(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index d2becd0a..4c010a91 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -16,7 +16,6 @@ use Niden\Middleware\TokenUserMiddleware; use Niden\Middleware\TokenValidationMiddleware; use Niden\Middleware\TokenVerificationMiddleware; - use Phalcon\Di\ServiceProviderInterface; use Phalcon\DiInterface; use Phalcon\Events\Manager; From 838a60a37a6a64e98752619b6e0662ee88042b72 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 18:28:04 -0400 Subject: [PATCH 33/70] Refactored types transformers; Added links element to responses --- .../IndividualTypes/GetController.php | 4 +-- .../ProductTypes/GetController.php | 4 +-- library/Transformers/CompaniesTransformer.php | 8 ++++++ .../IndividualTypesTransformer.php | 17 +++++++++++ .../Transformers/ProductTypesTransformer.php | 17 +++++++++++ library/Transformers/TypesTransformer.php | 28 ++++++++++++++----- .../Transformers/CompaniesTransformerCest.php | 8 ++++++ .../IndividualTypesTransformerCest.php | 12 ++++++-- .../ProductTypesTransformerCest.php | 12 ++++++-- 9 files changed, 95 insertions(+), 15 deletions(-) create mode 100644 library/Transformers/IndividualTypesTransformer.php create mode 100644 library/Transformers/ProductTypesTransformer.php diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index 174294c5..de01471e 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -6,7 +6,7 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\IndividualTypes; -use Niden\Transformers\TypesTransformer; +use Niden\Transformers\IndividualTypesTransformer; /** * Class GetController @@ -27,7 +27,7 @@ public function callAction($typeId = 0) return $this->processCall( IndividualTypes::class, 'idt_id', - TypesTransformer::class, + IndividualTypesTransformer::class, $typeId, 'idt_name' ); diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index a2282d14..c17c8511 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -6,7 +6,7 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\ProductTypes; -use Niden\Transformers\TypesTransformer; +use Niden\Transformers\ProductTypesTransformer; /** * Class GetController @@ -27,7 +27,7 @@ public function callAction($typeId = 0) return $this->processCall( ProductTypes::class, 'prt_id', - TypesTransformer::class, + ProductTypesTransformer::class, $typeId, 'prt_name' ); diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php index 84b5a9f9..7f506c81 100644 --- a/library/Transformers/CompaniesTransformer.php +++ b/library/Transformers/CompaniesTransformer.php @@ -6,6 +6,7 @@ use League\Fractal\TransformerAbstract; use Niden\Constants\Resources; +use function Niden\Core\envValue; use Niden\Models\Companies; /** @@ -30,6 +31,13 @@ public function transform(Companies $company) 'city' => $company->get('com_city'), 'phone' => $company->get('com_telephone'), ], + 'links' => [ + 'self' => sprintf( + '%s/companies/%s', + envValue('APP_URL', 'localhost'), + $company->get('com_id') + ), + ] ]; } } diff --git a/library/Transformers/IndividualTypesTransformer.php b/library/Transformers/IndividualTypesTransformer.php new file mode 100644 index 00000000..fe18b534 --- /dev/null +++ b/library/Transformers/IndividualTypesTransformer.php @@ -0,0 +1,17 @@ +getTablePrefix(); - $type = ('prt' === $prefix) ? Resources::PRODUCT_TYPES : Resources::INDIVIDUAL_TYPES; return [ - 'id' => $model->get(sprintf('%s_id', $prefix)), - 'type' => $type, + 'id' => $model->get(sprintf('%s_id', $this->prefix)), + 'type' => $this->type, 'attributes' => [ - 'name' => $model->get(sprintf('%s_name', $prefix)), - 'description' => $model->get(sprintf('%s_description', $prefix)), + 'name' => $model->get(sprintf('%s_name', $this->prefix)), + 'description' => $model->get(sprintf('%s_description', $this->prefix)), ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + $this->url, + $model->get($this->prefix . '_id') + ), + ] ]; } } diff --git a/tests/integration/library/Transformers/CompaniesTransformerCest.php b/tests/integration/library/Transformers/CompaniesTransformerCest.php index fd5d88cf..6cd0587d 100644 --- a/tests/integration/library/Transformers/CompaniesTransformerCest.php +++ b/tests/integration/library/Transformers/CompaniesTransformerCest.php @@ -4,6 +4,7 @@ use IntegrationTester; use Niden\Constants\Resources; +use function Niden\Core\envValue; use Niden\Models\Companies; use Niden\Transformers\CompaniesTransformer; @@ -37,6 +38,13 @@ public function checkTransformer(IntegrationTester $I) 'city' => $company->get('com_city'), 'phone' => $company->get('com_telephone'), ], + 'links' => [ + 'self' => sprintf( + '%s/companies/%s', + envValue('APP_URL', 'localhost'), + $company->get('com_id') + ), + ] ]; $I->assertEquals($expected, $transformer->transform($company)); diff --git a/tests/integration/library/Transformers/IndividualTypesTransformerCest.php b/tests/integration/library/Transformers/IndividualTypesTransformerCest.php index 73734293..52469fb9 100644 --- a/tests/integration/library/Transformers/IndividualTypesTransformerCest.php +++ b/tests/integration/library/Transformers/IndividualTypesTransformerCest.php @@ -4,8 +4,9 @@ use IntegrationTester; use Niden\Constants\Resources; +use function Niden\Core\envValue; use Niden\Models\IndividualTypes; -use Niden\Transformers\TypesTransformer; +use Niden\Transformers\IndividualTypesTransformer; use function uniqid; class IndividualTypesTransformerCest @@ -26,7 +27,7 @@ public function checkTransformer(IntegrationTester $I) ] ); - $transformer = new TypesTransformer(); + $transformer = new IndividualTypesTransformer(); $expected = [ 'id' => $type->get('idt_id'), 'type' => Resources::INDIVIDUAL_TYPES, @@ -34,6 +35,13 @@ public function checkTransformer(IntegrationTester $I) 'name' => $type->get('idt_name'), 'description' => $type->get('idt_description'), ], + 'links' => [ + 'self' => sprintf( + '%s/individualtypes/%s', + envValue('APP_URL', 'localhost'), + $type->get('idt_id') + ), + ] ]; $I->assertEquals($expected, $transformer->transform($type)); diff --git a/tests/integration/library/Transformers/ProductTypesTransformerCest.php b/tests/integration/library/Transformers/ProductTypesTransformerCest.php index a1f741b1..c0ff28e7 100644 --- a/tests/integration/library/Transformers/ProductTypesTransformerCest.php +++ b/tests/integration/library/Transformers/ProductTypesTransformerCest.php @@ -4,8 +4,9 @@ use IntegrationTester; use Niden\Constants\Resources; +use function Niden\Core\envValue; use Niden\Models\ProductTypes; -use Niden\Transformers\TypesTransformer; +use Niden\Transformers\ProductTypesTransformer; use function uniqid; class ProductTypesTransformerCest @@ -26,7 +27,7 @@ public function checkTransformer(IntegrationTester $I) ] ); - $transformer = new TypesTransformer(); + $transformer = new ProductTypesTransformer(); $expected = [ 'id' => $type->get('prt_id'), 'type' => Resources::PRODUCT_TYPES, @@ -34,6 +35,13 @@ public function checkTransformer(IntegrationTester $I) 'name' => $type->get('prt_name'), 'description' => $type->get('prt_description'), ], + 'links' => [ + 'self' => sprintf( + '%s/producttypes/%s', + envValue('APP_URL', 'localhost'), + $type->get('prt_id') + ), + ] ]; $I->assertEquals($expected, $transformer->transform($type)); From 9e5c1a35d91e1bae43804611735f5136a6fb9b37 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 18:58:14 -0400 Subject: [PATCH 34/70] Changed slightly the url for types --- library/Providers/RouterProvider.php | 23 ++++++++++++--------- tests/_support/Page/Data.php | 4 ++-- tests/unit/library/Providers/RouterCest.php | 12 ++++++----- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index 4c010a91..8dc9aac3 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -7,6 +7,7 @@ use Niden\Api\Controllers\Companies\AddController as CompaniesAddController; use Niden\Api\Controllers\Companies\GetController as CompaniesGetController; use Niden\Api\Controllers\IndividualTypes\GetController as IndividualTypesGetController; +use Niden\Api\Controllers\Products\GetController as ProductsGetController; use Niden\Api\Controllers\ProductTypes\GetController as ProductTypesGetController; use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; @@ -107,16 +108,18 @@ private function getRoutes(): array { return [ // Class, Method, Route, Handler - [LoginController::class, '/login', 'post', '/'], - [CompaniesAddController::class, '/companies', 'post', '/'], - [CompaniesGetController::class, '/companies', 'get', '/'], - [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], - [IndividualTypesGetController::class, '/individualtypes', 'get', '/'], - [IndividualTypesGetController::class, '/individualtypes', 'get', '/{typeId:[0-9]+}'], - [ProductTypesGetController::class, '/producttypes', 'get', '/'], - [ProductTypesGetController::class, '/producttypes', 'get', '/{typeId:[0-9]+}'], - [UsersGetController::class, '/users', 'get', '/'], - [UsersGetController::class, '/users', 'get', '/{userId:[0-9]+}'], + [LoginController::class, '/login', 'post', '/'], + [CompaniesAddController::class, '/companies', 'post', '/'], + [CompaniesGetController::class, '/companies', 'get', '/'], + [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], + [IndividualTypesGetController::class, '/individual-types', 'get', '/'], + [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}'], + [ProductsGetController::class, '/products', 'get', '/'], + [ProductsGetController::class, '/products', 'get', '/{productId:[0-9]+}'], + [ProductTypesGetController::class, '/product-types', 'get', '/'], + [ProductTypesGetController::class, '/product-types', 'get', '/{typeId:[0-9]+}'], + [UsersGetController::class, '/users', 'get', '/'], + [UsersGetController::class, '/users', 'get', '/{userId:[0-9]+}'], ]; } } diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index fb80c1cb..d9d56664 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -6,8 +6,8 @@ class Data { public static $companiesUrl = '/companies'; public static $loginUrl = '/login'; - public static $individualTypesUrl = '/individualtypes'; - public static $productTypesUrl = '/producttypes'; + public static $individualTypesUrl = '/individual-types'; + public static $productTypesUrl = '/product-types'; public static $usersUrl = '/users'; public static $wrongUrl = '/sommething'; diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 37d15bbc..9cd1f1ff 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -34,15 +34,17 @@ public function checkRegistration(UnitTester $I) ['POST', '/companies'], ['GET', '/companies'], ['GET', '/companies/{companyId:[0-9]+}'], - ['GET', '/individualtypes'], - ['GET', '/individualtypes/{typeId:[0-9]+}'], - ['GET', '/producttypes'], - ['GET', '/producttypes/{typeId:[0-9]+}'], + ['GET', '/individual-types'], + ['GET', '/individual-types/{typeId:[0-9]+}'], + ['GET', '/products'], + ['GET', '/products/{productId:[0-9]+}'], + ['GET', '/product-types'], + ['GET', '/product-types/{typeId:[0-9]+}'], ['GET', '/users'], ['GET', '/users/{userId:[0-9]+}'], ]; - $I->assertEquals(10, count($routes)); + $I->assertEquals(12, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); From 0cf79694bb38edfa13ad93f289b1d00799778a8e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 18:58:28 -0400 Subject: [PATCH 35/70] Docblock correction; Added products controller and transformer --- api/controllers/Companies/GetController.php | 2 +- api/controllers/Products/GetController.php | 35 +++++++++++++++ library/Transformers/ProductsTransformer.php | 47 ++++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 api/controllers/Products/GetController.php create mode 100644 library/Transformers/ProductsTransformer.php diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php index 105cb2bb..76256bd6 100644 --- a/api/controllers/Companies/GetController.php +++ b/api/controllers/Companies/GetController.php @@ -16,7 +16,7 @@ class GetController extends BaseController { /** - * Get the individual types + * Get the company/companies * * @param int $companyId * diff --git a/api/controllers/Products/GetController.php b/api/controllers/Products/GetController.php new file mode 100644 index 00000000..b8d0bf04 --- /dev/null +++ b/api/controllers/Products/GetController.php @@ -0,0 +1,35 @@ +processCall( + Products::class, + 'prd_id', + ProductsTransformer::class, + $productId, + 'prd_name' + ); + } +} diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php new file mode 100644 index 00000000..0d60c8ba --- /dev/null +++ b/library/Transformers/ProductsTransformer.php @@ -0,0 +1,47 @@ + $product->get('prd_id'), + 'type' => Resources::PRODUCTS, + 'attributes' => [ + 'name' => $product->get('prd_name'), + 'description' => $product->get('prd_description'), + 'quantity' => $product->get('prd_quantity'), + 'price' => $product->get('prd_price'), + + + + + ], + 'links' => [ + 'self' => sprintf( + '%s/products/%s', + envValue('APP_URL', 'localhost'), + $product->get('prd_id') + ), + ] + ]; + } +} From 41d28b14e6eeb93a19d923a3ce66947a5d762496 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 19:19:53 -0400 Subject: [PATCH 36/70] Added product tests --- library/Transformers/CompaniesTransformer.php | 3 +- library/Transformers/ProductsTransformer.php | 7 +- tests/_support/Page/Data.php | 1 + tests/api/Products/GetCest.php | 156 ++++++++++++++++++ .../Transformers/ProductsTransformerCest.php | 52 ++++++ 5 files changed, 213 insertions(+), 6 deletions(-) create mode 100644 tests/api/Products/GetCest.php create mode 100644 tests/integration/library/Transformers/ProductsTransformerCest.php diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php index 7f506c81..f4f56de9 100644 --- a/library/Transformers/CompaniesTransformer.php +++ b/library/Transformers/CompaniesTransformer.php @@ -7,6 +7,7 @@ use League\Fractal\TransformerAbstract; use Niden\Constants\Resources; use function Niden\Core\envValue; +use Niden\Exception\ModelException; use Niden\Models\Companies; /** @@ -18,7 +19,7 @@ class CompaniesTransformer extends TransformerAbstract * @param Companies $company * * @return array - * @throws \Niden\Exception\ModelException + * @throws ModelException */ public function transform(Companies $company) { diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php index 0d60c8ba..122c99d9 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php @@ -4,6 +4,7 @@ namespace Niden\Transformers; +use League\Fractal\TransformerAbstract; use Niden\Constants\Resources; use function Niden\Core\envValue; use Niden\Exception\ModelException; @@ -12,7 +13,7 @@ /** * Class ProductsTransformer */ -class ProductsTransformer extends TypesTransformer +class ProductsTransformer extends TransformerAbstract { /** * @param Products $product @@ -30,10 +31,6 @@ public function transform(Products $product) 'description' => $product->get('prd_description'), 'quantity' => $product->get('prd_quantity'), 'price' => $product->get('prd_price'), - - - - ], 'links' => [ 'self' => sprintf( diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index d9d56664..b2c71574 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -7,6 +7,7 @@ class Data public static $companiesUrl = '/companies'; public static $loginUrl = '/login'; public static $individualTypesUrl = '/individual-types'; + public static $productsUrl = '/products'; public static $productTypesUrl = '/product-types'; public static $usersUrl = '/users'; public static $wrongUrl = '/sommething'; diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php new file mode 100644 index 00000000..64c969ce --- /dev/null +++ b/tests/api/Products/GetCest.php @@ -0,0 +1,156 @@ +addRecord($I); + $token = $I->apiLogin(); + + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('prt-a-'), + 'prt_description' => uniqid(), + ] + ); + + /** @var Products $product */ + $product = $I->haveRecordWithFields( + Products::class, + [ + 'prd_name' => uniqid('prd-a-'), + 'prd_prt_id' => $productType->get('prt_id'), + 'prd_description' => uniqid(), + 'prd_quantity' => 25, + 'prd_price' => 19.99, + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productsUrl . '/' . $product->get('prd_id')); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $product->get('prd_id'), + 'type' => Resources::PRODUCTS, + 'attributes' => [ + 'name' => $product->get('prd_name'), + 'description' => $product->get('prd_description'), + 'quantity' => $product->get('prd_quantity'), + 'price' => $product->get('prd_price'), + ], + ], + ] + ); + } + + public function getProducts(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('prt-a-'), + 'prt_description' => uniqid(), + ] + ); + + /** @var Products $productOne */ + $productOne = $I->haveRecordWithFields( + Products::class, + [ + 'prd_name' => uniqid('prd-a-'), + 'prd_prt_id' => $productType->get('prt_id'), + 'prd_description' => uniqid(), + 'prd_quantity' => 25, + 'prd_price' => 19.99, + ] + ); + + /** @var Products $productTwo */ + $productTwo = $I->haveRecordWithFields( + Products::class, + [ + 'prd_name' => uniqid('prd-b-'), + 'prd_prt_id' => $productType->get('prt_id'), + 'prd_description' => uniqid(), + 'prd_quantity' => 25, + 'prd_price' => 19.99, + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $productOne->get('prd_id'), + 'type' => Resources::PRODUCTS, + 'attributes' => [ + 'name' => $productOne->get('prd_name'), + 'description' => $productOne->get('prd_description'), + 'quantity' => $productOne->get('prd_quantity'), + 'price' => $productOne->get('prd_price'), + ], + ], + [ + 'id' => $productTwo->get('prd_id'), + 'type' => Resources::PRODUCTS, + 'attributes' => [ + 'name' => $productTwo->get('prd_name'), + 'description' => $productTwo->get('prd_description'), + 'quantity' => $productTwo->get('prd_quantity'), + 'price' => $productTwo->get('prd_price'), + ], + ], + ] + ); + } + + public function getProductsNoData(ApiTester $I) + { + $this->addRecord($I); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productsUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function addRecord(ApiTester $I) + { + return $I->haveRecordWithFields( + Users::class, + [ + 'usr_status_flag' => 1, + 'usr_username' => 'testuser', + 'usr_password' => 'testpassword', + 'usr_issuer' => 'https://niden.net', + 'usr_token_password' => '12345', + 'usr_token_id' => '110011', + ] + ); + } +} diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php new file mode 100644 index 00000000..009e21e0 --- /dev/null +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -0,0 +1,52 @@ +haveRecordWithFields( + Products::class, + [ + 'prd_name' => 'test product', + 'prd_description' => 'test product description', + 'prd_quantity' => 25, + 'prd_price' => 19.99, + ] + ); + + $transformer = new ProductsTransformer(); + $expected = [ + 'id' => $product->get('prd_id'), + 'type' => Resources::PRODUCTS, + 'attributes' => [ + 'name' => $product->get('prd_name'), + 'description' => $product->get('prd_description'), + 'quantity' => $product->get('prd_quantity'), + 'price' => $product->get('prd_price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/products/%s', + envValue('APP_URL', 'localhost'), + $product->get('prd_id') + ), + ] + ]; + + $I->assertEquals($expected, $transformer->transform($product)); + } +} From b1ea2b22d6c0db623826552ce3438a70bf692b8c Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 19:27:23 -0400 Subject: [PATCH 37/70] Corrected test --- tests/api/Products/GetCest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 64c969ce..8b98e470 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -98,7 +98,7 @@ public function getProducts(ApiTester $I) ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl); + $I->sendGET(Data::$productsUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( From a82af79e5bc662494d6e1a438c6fc071b9127f40 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 19:34:43 -0400 Subject: [PATCH 38/70] Added related link for products --- library/Transformers/ProductsTransformer.php | 8 +++- tests/api/Products/GetCest.php | 40 +++++++++++++++++++ .../Transformers/ProductsTransformerCest.php | 17 ++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php index 122c99d9..9133a757 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php @@ -28,16 +28,22 @@ public function transform(Products $product) 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $product->get('prd_name'), + 'typeId' => $product->get('prd_prt_id'), 'description' => $product->get('prd_description'), 'quantity' => $product->get('prd_quantity'), 'price' => $product->get('prd_price'), ], - 'links' => [ + 'links' => [ 'self' => sprintf( '%s/products/%s', envValue('APP_URL', 'localhost'), $product->get('prd_id') ), + 'related' => sprintf( + '%s/product-types/%s', + envValue('APP_URL', 'localhost'), + $product->get('prd_prt_id') + ), ] ]; } diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 8b98e470..e53aba48 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -4,6 +4,7 @@ use ApiTester; use Niden\Constants\Resources; +use function Niden\Core\envValue; use Niden\Models\Companies; use Niden\Models\Products; use Niden\Models\ProductTypes; @@ -50,10 +51,23 @@ public function getProduct(ApiTester $I) 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $product->get('prd_name'), + 'typeId' => $productType->get('prt_id'), 'description' => $product->get('prd_description'), 'quantity' => $product->get('prd_quantity'), 'price' => $product->get('prd_price'), ], + 'links' => [ + 'self' => sprintf( + '%s/products/%s', + envValue('APP_URL', 'localhost'), + $product->get('prd_id') + ), + 'related' => sprintf( + '%s/product-types/%s', + envValue('APP_URL', 'localhost'), + $productType->get('prt_id') + ), + ] ], ] ); @@ -108,20 +122,46 @@ public function getProducts(ApiTester $I) 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $productOne->get('prd_name'), + 'typeId' => $productType->get('prt_id'), 'description' => $productOne->get('prd_description'), 'quantity' => $productOne->get('prd_quantity'), 'price' => $productOne->get('prd_price'), ], + 'links' => [ + 'self' => sprintf( + '%s/products/%s', + envValue('APP_URL', 'localhost'), + $productOne->get('prd_id') + ), + 'related' => sprintf( + '%s/product-types/%s', + envValue('APP_URL', 'localhost'), + $productType->get('prt_id') + ), + ] ], [ 'id' => $productTwo->get('prd_id'), 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $productTwo->get('prd_name'), + 'typeId' => $productType->get('prt_id'), 'description' => $productTwo->get('prd_description'), 'quantity' => $productTwo->get('prd_quantity'), 'price' => $productTwo->get('prd_price'), ], + 'links' => [ + 'self' => sprintf( + '%s/products/%s', + envValue('APP_URL', 'localhost'), + $productTwo->get('prd_id') + ), + 'related' => sprintf( + '%s/product-types/%s', + envValue('APP_URL', 'localhost'), + $productType->get('prt_id') + ), + ] ], ] ); diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php index 009e21e0..ee4625a5 100644 --- a/tests/integration/library/Transformers/ProductsTransformerCest.php +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -6,6 +6,7 @@ use Niden\Constants\Resources; use function Niden\Core\envValue; use Niden\Models\Products; +use Niden\Models\ProductTypes; use Niden\Transformers\ProductsTransformer; class ProductsTransformerCest @@ -17,11 +18,21 @@ class ProductsTransformerCest */ public function checkTransformer(IntegrationTester $I) { + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'prt_name' => uniqid('prt-a-'), + 'prt_description' => uniqid(), + ] + ); + /** @var Products $product */ $product = $I->haveRecordWithFields( Products::class, [ 'prd_name' => 'test product', + 'prd_prt_id' => $productType->get('prt_id'), 'prd_description' => 'test product description', 'prd_quantity' => 25, 'prd_price' => 19.99, @@ -34,6 +45,7 @@ public function checkTransformer(IntegrationTester $I) 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $product->get('prd_name'), + 'typeId' => $productType->get('prt_id'), 'description' => $product->get('prd_description'), 'quantity' => $product->get('prd_quantity'), 'price' => $product->get('prd_price'), @@ -44,6 +56,11 @@ public function checkTransformer(IntegrationTester $I) envValue('APP_URL', 'localhost'), $product->get('prd_id') ), + 'related' => sprintf( + '%s/product-types/%s', + envValue('APP_URL', 'localhost'), + $productType->get('prt_id') + ), ] ]; From 407b3618ed13c3838a0f2f665c392a250c9f992d Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 21:52:22 -0400 Subject: [PATCH 39/70] Major refactor, taking advantage of the JSONApi serializer of Fractal --- api/controllers/BaseController.php | 16 ++- api/controllers/Companies/AddController.php | 12 +- api/controllers/Companies/GetController.php | 9 +- .../IndividualTypes/GetController.php | 9 +- .../ProductTypes/GetController.php | 9 +- api/controllers/Products/GetController.php | 9 +- api/controllers/Users/GetController.php | 9 +- library/Constants/Resources.php | 4 +- .../TokenVerificationMiddleware.php | 2 +- library/Models/Companies.php | 28 ++++- library/Models/IndividualTypes.php | 20 ++- library/Models/Individuals.php | 35 ++++-- library/Models/ProductTypes.php | 20 ++- library/Models/Products.php | 29 ++++- library/Models/Users.php | 42 +++++-- library/Traits/FractalTrait.php | 9 +- library/Traits/QueryTrait.php | 12 +- library/Transformers/BaseTransformer.php | 33 +++++ library/Transformers/CompaniesTransformer.php | 44 ------- ...er.php => IndividualTypesTransformer.php_} | 0 ...ormer.php => ProductTypesTransformer.php_} | 0 ...ansformer.php => ProductsTransformer.php_} | 27 ++-- ...sTransformer.php => TypesTransformer.php_} | 0 ...sTransformer.php => UsersTransformer.php_} | 0 tests/_support/ApiTester.php | 15 +++ tests/api/Companies/AddCest.php | 33 ++--- tests/api/Companies/GetCest.php | 77 +++++------- tests/api/IndividualTypes/GetCest.php | 35 ++---- tests/api/LoginCest.php | 10 +- tests/api/ProductTypes/GetCest.php | 35 ++---- tests/api/Products/GetCest.php | 118 +++++++----------- tests/api/Users/GetCest.php | 112 +++++++---------- tests/integration/library/ModelCest.php | 99 +++++++-------- .../library/Models/CompaniesCest.php | 26 ++-- .../library/Models/IndividualTypesCest.php | 6 +- .../library/Models/IndividualsCest.php | 16 +-- .../library/Models/ProductTypesCest.php | 6 +- .../library/Models/ProductsCest.php | 12 +- .../integration/library/Models/UsersCest.php | 26 ++-- .../integration/library/Traits/QueryCest.php | 38 +++--- .../Transformers/BaseTransformerCest.php | 42 +++++++ .../Transformers/CompaniesTransformerCest.php | 52 -------- .../IndividualTypesTransformerCest.php | 49 -------- .../ProductTypesTransformerCest.php | 49 -------- .../Transformers/ProductsTransformerCest.php | 69 ---------- .../Transformers/UsersTransformerCest.php | 47 ------- .../unit/library/Constants/ResourcesCest.php | 4 +- 47 files changed, 541 insertions(+), 813 deletions(-) create mode 100644 library/Transformers/BaseTransformer.php delete mode 100644 library/Transformers/CompaniesTransformer.php rename library/Transformers/{IndividualTypesTransformer.php => IndividualTypesTransformer.php_} (100%) rename library/Transformers/{ProductTypesTransformer.php => ProductTypesTransformer.php_} (100%) rename library/Transformers/{ProductsTransformer.php => ProductsTransformer.php_} (70%) rename library/Transformers/{TypesTransformer.php => TypesTransformer.php_} (100%) rename library/Transformers/{UsersTransformer.php => UsersTransformer.php_} (100%) create mode 100644 tests/integration/library/Transformers/BaseTransformerCest.php delete mode 100644 tests/integration/library/Transformers/CompaniesTransformerCest.php delete mode 100644 tests/integration/library/Transformers/IndividualTypesTransformerCest.php delete mode 100644 tests/integration/library/Transformers/ProductTypesTransformerCest.php delete mode 100644 tests/integration/library/Transformers/ProductsTransformerCest.php delete mode 100644 tests/integration/library/Transformers/UsersTransformerCest.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 79c57ae4..0157a54c 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -11,6 +11,7 @@ use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; +use Niden\Transformers\BaseTransformer; use Phalcon\Filter; use Phalcon\Mvc\Controller; @@ -27,12 +28,11 @@ class BaseController extends Controller /** * Checks the passed id parameter and returns the relevant array back * - * @param string $field * @param int $recordId * * @return array */ - protected function checkIdParameter(string $field, $recordId = 0): array + protected function checkIdParameter($recordId = 0): array { $parameters = []; @@ -40,7 +40,7 @@ protected function checkIdParameter(string $field, $recordId = 0): array $localId = $this->filter->sanitize($recordId, Filter::FILTER_ABSINT); if ($localId > 0) { - $parameters[$field] = $localId; + $parameters['id'] = $localId; } return $parameters; @@ -50,8 +50,7 @@ protected function checkIdParameter(string $field, $recordId = 0): array * Processes getting records as a while or one using an id * * @param string $model - * @param string $field - * @param string $transformer + * @param string $resource * @param int $recordId * @param string $orderBy * @@ -59,14 +58,13 @@ protected function checkIdParameter(string $field, $recordId = 0): array */ protected function processCall( string $model, - string $field, - string $transformer, + string $resource, $recordId = 0, string $orderBy = '' ) { - $parameters = $this->checkIdParameter($field, $recordId); + $parameters = $this->checkIdParameter($recordId); $results = $this->getRecords($model, $parameters, $orderBy); - return $this->format($results, $transformer); + return $this->format($results, BaseTransformer::class, $resource); } } diff --git a/api/controllers/Companies/AddController.php b/api/controllers/Companies/AddController.php index 27a91568..a3f6637b 100644 --- a/api/controllers/Companies/AddController.php +++ b/api/controllers/Companies/AddController.php @@ -8,7 +8,7 @@ use Niden\Http\Response; use Niden\Models\Companies; use Niden\Traits\FractalTrait; -use Niden\Transformers\CompaniesTransformer; +use Niden\Transformers\BaseTransformer; use Niden\Validation\CompaniesValidator; use Phalcon\Filter; use Phalcon\Mvc\Controller; @@ -46,10 +46,10 @@ public function callAction() $company = new Companies(); $result = $company - ->set('com_name', $name) - ->set('com_address', $address) - ->set('com_city', $city) - ->set('com_telephone', $phone) + ->set('name', $name) + ->set('address', $address) + ->set('city', $city) + ->set('phone', $phone) ->save() ; @@ -57,7 +57,7 @@ public function callAction() /** * Everything is fine, return the record back */ - return $this->format([$company], CompaniesTransformer::class); + return $this->format([$company], BaseTransformer::class, 'companies'); } /** diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php index 76256bd6..d4bbc1e1 100644 --- a/api/controllers/Companies/GetController.php +++ b/api/controllers/Companies/GetController.php @@ -6,7 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\Companies; -use Niden\Transformers\CompaniesTransformer; /** * Class GetController @@ -24,12 +23,6 @@ class GetController extends BaseController */ public function callAction($companyId = 0) { - return $this->processCall( - Companies::class, - 'com_id', - CompaniesTransformer::class, - $companyId, - 'com_name' - ); + return $this->processCall(Companies::class, 'companies', $companyId, 'name'); } } diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index de01471e..8bafeb6e 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -6,7 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\IndividualTypes; -use Niden\Transformers\IndividualTypesTransformer; /** * Class GetController @@ -24,12 +23,6 @@ class GetController extends BaseController */ public function callAction($typeId = 0) { - return $this->processCall( - IndividualTypes::class, - 'idt_id', - IndividualTypesTransformer::class, - $typeId, - 'idt_name' - ); + return $this->processCall(IndividualTypes::class, 'individual-types', $typeId, 'name'); } } diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index c17c8511..46f58b59 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -6,7 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\ProductTypes; -use Niden\Transformers\ProductTypesTransformer; /** * Class GetController @@ -24,12 +23,6 @@ class GetController extends BaseController */ public function callAction($typeId = 0) { - return $this->processCall( - ProductTypes::class, - 'prt_id', - ProductTypesTransformer::class, - $typeId, - 'prt_name' - ); + return $this->processCall(ProductTypes::class, 'product-types', $typeId, 'name'); } } diff --git a/api/controllers/Products/GetController.php b/api/controllers/Products/GetController.php index b8d0bf04..8936ea85 100644 --- a/api/controllers/Products/GetController.php +++ b/api/controllers/Products/GetController.php @@ -6,7 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\Products; -use Niden\Transformers\ProductsTransformer; /** * Class GetController @@ -24,12 +23,6 @@ class GetController extends BaseController */ public function callAction($productId = 0) { - return $this->processCall( - Products::class, - 'prd_id', - ProductsTransformer::class, - $productId, - 'prd_name' - ); + return $this->processCall(Products::class, 'products', $productId, 'name'); } } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 8da6fe73..1bdcc8f1 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -6,7 +6,6 @@ use Niden\Api\Controllers\BaseController; use Niden\Models\Users; -use Niden\Transformers\UsersTransformer; /** * Class GetController @@ -24,12 +23,6 @@ class GetController extends BaseController */ public function callAction($userId = 0) { - return $this->processCall( - Users::class, - 'usr_id', - UsersTransformer::class, - $userId, - 'usr_username' - ); + return $this->processCall(Users::class, 'users', $userId, 'username'); } } diff --git a/library/Constants/Resources.php b/library/Constants/Resources.php index 30fe6cff..32f5b7c3 100644 --- a/library/Constants/Resources.php +++ b/library/Constants/Resources.php @@ -7,9 +7,9 @@ class Resources { const COMPANIES = 'companies'; - const INDIVIDUAL_TYPES = 'individualTypes'; + const INDIVIDUAL_TYPES = 'individual-types'; const INDIVIDUALS = 'individuals'; - const PRODUCT_TYPES = 'productTypes'; + const PRODUCT_TYPES = 'product-types'; const PRODUCTS = 'products'; const USERS = 'users'; } diff --git a/library/Middleware/TokenVerificationMiddleware.php b/library/Middleware/TokenVerificationMiddleware.php index a180de26..0eceece8 100755 --- a/library/Middleware/TokenVerificationMiddleware.php +++ b/library/Middleware/TokenVerificationMiddleware.php @@ -39,7 +39,7 @@ public function call(Micro $api) /** @var Users $user */ $user = $this->getUserByToken($token); - if (false === $token->verify($signer, $user->get('usr_token_password'))) { + if (false === $token->verify($signer, $user->get('tokenPassword'))) { $this->halt($api, 'Invalid Token'); } } diff --git a/library/Models/Companies.php b/library/Models/Companies.php index 4171a7fc..be3667b5 100644 --- a/library/Models/Companies.php +++ b/library/Models/Companies.php @@ -45,6 +45,22 @@ public function initialize() parent::initialize(); } + /** + * Column map to help with the API + * + * @return array + */ + public function columnMap(): array + { + return [ + 'com_id' => 'id', + 'com_name' => 'name', + 'com_address' => 'address', + 'com_city' => 'city', + 'com_telephone' => 'phone', + ]; + } + /** * Model filters * @@ -53,11 +69,11 @@ public function initialize() public function getModelFilters(): array { return [ - 'com_id' => Filter::FILTER_ABSINT, - 'com_name' => Filter::FILTER_STRING, - 'com_address' => Filter::FILTER_STRING, - 'com_city' => Filter::FILTER_STRING, - 'com_telephone' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'address' => Filter::FILTER_STRING, + 'city' => Filter::FILTER_STRING, + 'phone' => Filter::FILTER_STRING, ]; } @@ -90,7 +106,7 @@ public function validation() { $validator = new Validation(); $validator->add( - 'com_name', + 'name', new Uniqueness( [ 'message' => 'The company name already exists in the database', diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php index 34c901f5..9fedd5cd 100644 --- a/library/Models/IndividualTypes.php +++ b/library/Models/IndividualTypes.php @@ -33,6 +33,20 @@ public function initialize() parent::initialize(); } + /** + * Column map + * + * @return array + */ + public function columnMap(): array + { + return [ + 'idt_id' => 'id', + 'idt_name' => 'name', + 'idt_description' => 'description', + ]; + } + /** * Model filters * @@ -41,9 +55,9 @@ public function initialize() public function getModelFilters(): array { return [ - 'idt_id' => Filter::FILTER_ABSINT, - 'idt_name' => Filter::FILTER_STRING, - 'idt_description' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, ]; } diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php index 2710620f..3e48dd1d 100644 --- a/library/Models/Individuals.php +++ b/library/Models/Individuals.php @@ -43,6 +43,25 @@ public function initialize() parent::initialize(); } + /** + * Column Map + * + * @return array + */ + public function columnMap(): array + { + return [ + 'ind_id' => 'id', + 'ind_com_id' => 'companyId', + 'ind_idt_id' => 'typeId', + 'ind_name_prefix' => 'prefix', + 'ind_name_first' => 'first', + 'ind_name_middle' => 'middle', + 'ind_name_last' => 'last', + 'ind_name_suffix' => 'suffix', + ]; + } + /** * Model filters * @@ -51,14 +70,14 @@ public function initialize() public function getModelFilters(): array { return [ - 'ind_id' => Filter::FILTER_ABSINT, - 'ind_com_id' => Filter::FILTER_ABSINT, - 'ind_idt_id' => Filter::FILTER_ABSINT, - 'ind_name_prefix' => Filter::FILTER_STRING, - 'ind_name_first' => Filter::FILTER_STRING, - 'ind_name_middle' => Filter::FILTER_STRING, - 'ind_name_last' => Filter::FILTER_STRING, - 'ind_name_suffix' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'companyId' => Filter::FILTER_ABSINT, + 'typeId' => Filter::FILTER_ABSINT, + 'prefix' => Filter::FILTER_STRING, + 'first' => Filter::FILTER_STRING, + 'middle' => Filter::FILTER_STRING, + 'last' => Filter::FILTER_STRING, + 'suffix' => Filter::FILTER_STRING, ]; } diff --git a/library/Models/ProductTypes.php b/library/Models/ProductTypes.php index 09e2ced5..42c1a426 100644 --- a/library/Models/ProductTypes.php +++ b/library/Models/ProductTypes.php @@ -33,6 +33,20 @@ public function initialize() parent::initialize(); } + /** + * Column Map + * + * @return array + */ + public function columnMap(): array + { + return [ + 'prt_id' => 'id', + 'prt_name' => 'name', + 'prt_description' => 'description', + ]; + } + /** * Model filters * @@ -41,9 +55,9 @@ public function initialize() public function getModelFilters(): array { return [ - 'prt_id' => Filter::FILTER_ABSINT, - 'prt_name' => Filter::FILTER_STRING, - 'prt_description' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, ]; } diff --git a/library/Models/Products.php b/library/Models/Products.php index f6ab1a18..3fed133a 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -43,6 +43,23 @@ public function initialize() parent::initialize(); } + /** + * Column Map + * + * @return array + */ + public function columnMap(): array + { + return [ + 'prd_id' => 'id', + 'prd_prt_id' => 'typeId', + 'prd_name' => 'name', + 'prd_description' => 'description', + 'prd_quantity' => 'quantity', + 'prd_price' => 'price', + ]; + } + /** * Model filters * @@ -51,12 +68,12 @@ public function initialize() public function getModelFilters(): array { return [ - 'prd_id' => Filter::FILTER_ABSINT, - 'prd_prt_id' => Filter::FILTER_ABSINT, - 'prd_name' => Filter::FILTER_STRING, - 'prd_description' => Filter::FILTER_STRING, - 'prd_quantity' => Filter::FILTER_ABSINT, - 'prd_price' => Filter::FILTER_FLOAT, + 'id' => Filter::FILTER_ABSINT, + 'typeId' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, + 'quantity' => Filter::FILTER_ABSINT, + 'price' => Filter::FILTER_FLOAT, ]; } diff --git a/library/Models/Users.php b/library/Models/Users.php index 18a663b6..408343d5 100644 --- a/library/Models/Users.php +++ b/library/Models/Users.php @@ -22,6 +22,24 @@ class Users extends AbstractModel { use TokenTrait; + /** + * Column Map + * + * @return array + */ + public function columnMap(): array + { + return [ + 'usr_id' => 'id', + 'usr_status_flag' => 'status', + 'usr_username' => 'username', + 'usr_password' => 'password', + 'usr_issuer' => 'issuer', + 'usr_token_password' => 'tokenPassword', + 'usr_token_id' => 'tokenId', + ]; + } + /** * Model filters * @@ -30,13 +48,13 @@ class Users extends AbstractModel public function getModelFilters(): array { return [ - 'usr_id' => Filter::FILTER_ABSINT, - 'usr_status_flag' => Filter::FILTER_ABSINT, - 'usr_username' => Filter::FILTER_STRING, - 'usr_password' => Filter::FILTER_STRING, - 'usr_issuer' => Filter::FILTER_STRING, - 'usr_token_password' => Filter::FILTER_STRING, - 'usr_token_id' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'status' => Filter::FILTER_ABSINT, + 'username' => Filter::FILTER_STRING, + 'password' => Filter::FILTER_STRING, + 'issuer' => Filter::FILTER_STRING, + 'tokenPassword' => Filter::FILTER_STRING, + 'tokenId' => Filter::FILTER_STRING, ]; } @@ -71,13 +89,13 @@ public function getToken(): string $signer = new Sha512(); $builder = new Builder(); $token = $builder - ->setIssuer($this->get('usr_issuer')) + ->setIssuer($this->get('issuer')) ->setAudience($this->getTokenAudience()) - ->setId($this->get('usr_token_id'), true) + ->setId($this->get('tokenId'), true) ->setIssuedAt($this->getTokenTimeIssuedAt()) ->setNotBefore($this->getTokenTimeNotBefore()) ->setExpiration($this->getTokenTimeExpiration()) - ->sign($signer, $this->get('usr_token_password')) + ->sign($signer, $this->get('tokenPassword')) ->getToken(); return $token->__toString(); @@ -92,9 +110,9 @@ public function getToken(): string public function getValidationData(): ValidationData { $validationData = new ValidationData(); - $validationData->setIssuer($this->get('usr_issuer')); + $validationData->setIssuer($this->get('issuer')); $validationData->setAudience($this->getTokenAudience()); - $validationData->setId($this->get('usr_token_id')); + $validationData->setId($this->get('tokenId')); $validationData->setCurrentTime(time() + 10); return $validationData; diff --git a/library/Traits/FractalTrait.php b/library/Traits/FractalTrait.php index 67b37476..7a0d2572 100644 --- a/library/Traits/FractalTrait.php +++ b/library/Traits/FractalTrait.php @@ -6,6 +6,8 @@ use League\Fractal\Manager; use League\Fractal\Resource\Collection; +use League\Fractal\Serializer\JsonApiSerializer; +use function Niden\Core\envValue; /** * Trait FractalTrait @@ -19,13 +21,16 @@ trait FractalTrait * * @param mixed $results * @param string $transformer + * @param string $resource * * @return array */ - protected function format($results, string $transformer): array + protected function format($results, string $transformer, string $resource): array { + $url = envValue('APP_URL', 'http://localhost'); $manager = new Manager(); - $resource = new Collection($results, new $transformer()); + $manager->setSerializer(new JsonApiSerializer($url)); + $resource = new Collection($results, new $transformer(), $resource); $results = $manager->createData($resource)->toArray(); return $results['data']; diff --git a/library/Traits/QueryTrait.php b/library/Traits/QueryTrait.php index a4b6fe3e..a39a474f 100644 --- a/library/Traits/QueryTrait.php +++ b/library/Traits/QueryTrait.php @@ -28,9 +28,9 @@ trait QueryTrait protected function getUserByToken(Token $token) { $parameters = [ - 'usr_issuer' => $token->getClaim(JWTClaims::CLAIM_ISSUER), - 'usr_token_id' => $token->getClaim(JWTClaims::CLAIM_ID), - 'usr_status_flag' => Flags::ACTIVE, + 'issuer' => $token->getClaim(JWTClaims::CLAIM_ISSUER), + 'tokenId' => $token->getClaim(JWTClaims::CLAIM_ID), + 'status' => Flags::ACTIVE, ]; $result = $this->getRecords(Users::class, $parameters); @@ -49,9 +49,9 @@ protected function getUserByToken(Token $token) protected function getUserByUsernameAndPassword($username, $password) { $parameters = [ - 'usr_username' => $username, - 'usr_password' => $password, - 'usr_status_flag' => Flags::ACTIVE, + 'username' => $username, + 'password' => $password, + 'status' => Flags::ACTIVE, ]; $result = $this->getRecords(Users::class, $parameters); diff --git a/library/Transformers/BaseTransformer.php b/library/Transformers/BaseTransformer.php new file mode 100644 index 00000000..a6efcffc --- /dev/null +++ b/library/Transformers/BaseTransformer.php @@ -0,0 +1,33 @@ +getModelFilters()); + foreach ($filters as $column) { + $data[$column] = $model->get($column); + } + + return $data; + } +} diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php deleted file mode 100644 index f4f56de9..00000000 --- a/library/Transformers/CompaniesTransformer.php +++ /dev/null @@ -1,44 +0,0 @@ - $company->get('com_id'), - 'type' => Resources::COMPANIES, - 'attributes' => [ - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), - ], - 'links' => [ - 'self' => sprintf( - '%s/companies/%s', - envValue('APP_URL', 'localhost'), - $company->get('com_id') - ), - ] - ]; - } -} diff --git a/library/Transformers/IndividualTypesTransformer.php b/library/Transformers/IndividualTypesTransformer.php_ similarity index 100% rename from library/Transformers/IndividualTypesTransformer.php rename to library/Transformers/IndividualTypesTransformer.php_ diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php_ similarity index 100% rename from library/Transformers/ProductTypesTransformer.php rename to library/Transformers/ProductTypesTransformer.php_ diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php_ similarity index 70% rename from library/Transformers/ProductsTransformer.php rename to library/Transformers/ProductsTransformer.php_ index 9133a757..f96c5b24 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php_ @@ -4,7 +4,9 @@ namespace Niden\Transformers; +use League\Fractal\Resource\Item; use League\Fractal\TransformerAbstract; +use Niden\Constants\Relationships; use Niden\Constants\Resources; use function Niden\Core\envValue; use Niden\Exception\ModelException; @@ -15,6 +17,11 @@ */ class ProductsTransformer extends TransformerAbstract { + /** @var array */ + protected $availableIncludes = [ + 'product-types', + ]; + /** * @param Products $product * @@ -28,7 +35,6 @@ public function transform(Products $product) 'type' => Resources::PRODUCTS, 'attributes' => [ 'name' => $product->get('prd_name'), - 'typeId' => $product->get('prd_prt_id'), 'description' => $product->get('prd_description'), 'quantity' => $product->get('prd_quantity'), 'price' => $product->get('prd_price'), @@ -39,12 +45,19 @@ public function transform(Products $product) envValue('APP_URL', 'localhost'), $product->get('prd_id') ), - 'related' => sprintf( - '%s/product-types/%s', - envValue('APP_URL', 'localhost'), - $product->get('prd_prt_id') - ), - ] + ], ]; } + + /** + * @param Products $product + * + * @return Item + */ + public function includeProductTypes(Products $product): Item + { + $productType = $product->getRelated(Relationships::PRODUCT_TYPE); + + return $this->item($productType, new ProductTypesTransformer()); + } } diff --git a/library/Transformers/TypesTransformer.php b/library/Transformers/TypesTransformer.php_ similarity index 100% rename from library/Transformers/TypesTransformer.php rename to library/Transformers/TypesTransformer.php_ diff --git a/library/Transformers/UsersTransformer.php b/library/Transformers/UsersTransformer.php_ similarity index 100% rename from library/Transformers/UsersTransformer.php rename to library/Transformers/UsersTransformer.php_ diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index d551dc89..3879d250 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -93,4 +93,19 @@ public function apiLogin() return $token; } + + public function addApiUserRecord() + { + return $this->haveRecordWithFields( + Users::class, + [ + 'status' => 1, + 'username' => 'testuser', + 'password' => 'testpassword', + 'issuer' => 'https://niden.net', + 'tokenPassword' => '12345', + 'tokenId' => '110011', + ] + ); + } } diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index eac85ed0..519da4a7 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -13,7 +13,7 @@ class AddCest { public function addNewCompany(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $name = uniqid('com'); @@ -33,7 +33,7 @@ public function addNewCompany(ApiTester $I) $company = $I->getRecordWithFields( Companies::class, [ - 'com_name' => $name, + 'name' => $name, ] ); $I->assertNotEquals(false, $company); @@ -41,13 +41,13 @@ public function addNewCompany(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $company->get('com_id'), + 'id' => $company->get('id'), 'type' => Resources::COMPANIES, 'attributes' => [ - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), + 'name' => $company->get('name'), + 'address' => $company->get('address'), + 'city' => $company->get('city'), + 'phone' => $company->get('phone'), ], ], ] @@ -58,13 +58,13 @@ public function addNewCompany(ApiTester $I) public function addNewCompanyWithExistingName(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $name = uniqid('com'); $I->haveRecordWithFields( Companies::class, [ - 'com_name' => $name + 'name' => $name ] ); @@ -81,19 +81,4 @@ public function addNewCompanyWithExistingName(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeErrorJsonResponse('The company name already exists in the database'); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index e6bc0fc2..0e12c4e5 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -13,32 +13,32 @@ class GetCest { public function getCompany(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $comOne = $I->haveRecordWithFields( Companies::class, [ - 'com_name' => uniqid('com-a-'), - 'com_address' => uniqid(), - 'com_city' => uniqid(), - 'com_telephone' => uniqid(), + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('com_id')); + $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id')); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( [ [ - 'id' => $comOne->get('com_id'), + 'id' => $comOne->get('id'), 'type' => Resources::COMPANIES, 'attributes' => [ - 'name' => $comOne->get('com_name'), - 'address' => $comOne->get('com_address'), - 'city' => $comOne->get('com_city'), - 'phone' => $comOne->get('com_telephone'), + 'name' => $comOne->get('name'), + 'address' => $comOne->get('address'), + 'city' => $comOne->get('city'), + 'phone' => $comOne->get('phone'), ], ], ] @@ -47,25 +47,25 @@ public function getCompany(ApiTester $I) public function getCompanies(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $comOne = $I->haveRecordWithFields( Companies::class, [ - 'com_name' => uniqid('com-a-'), - 'com_address' => uniqid(), - 'com_city' => uniqid(), - 'com_telephone' => uniqid(), + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), ] ); $comTwo = $I->haveRecordWithFields( Companies::class, [ - 'com_name' => uniqid('com-b-'), - 'com_address' => uniqid(), - 'com_city' => uniqid(), - 'com_telephone' => uniqid(), + 'name' => uniqid('com-b-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -75,23 +75,23 @@ public function getCompanies(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $comOne->get('com_id'), + 'id' => $comOne->get('id'), 'type' => Resources::COMPANIES, 'attributes' => [ - 'name' => $comOne->get('com_name'), - 'address' => $comOne->get('com_address'), - 'city' => $comOne->get('com_city'), - 'phone' => $comOne->get('com_telephone'), + 'name' => $comOne->get('name'), + 'address' => $comOne->get('address'), + 'city' => $comOne->get('city'), + 'phone' => $comOne->get('phone'), ], ], [ - 'id' => $comTwo->get('com_id'), + 'id' => $comTwo->get('id'), 'type' => Resources::COMPANIES, 'attributes' => [ - 'name' => $comTwo->get('com_name'), - 'address' => $comTwo->get('com_address'), - 'city' => $comTwo->get('com_city'), - 'phone' => $comTwo->get('com_telephone'), + 'name' => $comTwo->get('name'), + 'address' => $comTwo->get('address'), + 'city' => $comTwo->get('city'), + 'phone' => $comTwo->get('phone'), ], ], ] @@ -100,7 +100,7 @@ public function getCompanies(ApiTester $I) public function getCompaniesNoData(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -109,19 +109,4 @@ public function getCompaniesNoData(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index e0b56b5d..f001c5da 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -13,19 +13,19 @@ class GetCest { public function getIndividualTypes(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $typeOne = $I->haveRecordWithFields( IndividualTypes::class, [ - 'idt_name' => uniqid('type-a-'), + 'name' => uniqid('type-a-'), ] ); $typeTwo = $I->haveRecordWithFields( IndividualTypes::class, [ - 'idt_name' => uniqid('type-b-'), + 'name' => uniqid('type-b-'), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -35,19 +35,19 @@ public function getIndividualTypes(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $typeOne->get('idt_id'), + 'id' => $typeOne->get('id'), 'type' => Resources::INDIVIDUAL_TYPES, 'attributes' => [ - 'name' => $typeOne->get('idt_name'), - 'description' => $typeOne->get('idt_description'), + 'name' => $typeOne->get('name'), + 'description' => $typeOne->get('description'), ], ], [ - 'id' => $typeTwo->get('idt_id'), + 'id' => $typeTwo->get('id'), 'type' => Resources::INDIVIDUAL_TYPES, 'attributes' => [ - 'name' => $typeTwo->get('idt_name'), - 'description' => $typeTwo->get('idt_description'), + 'name' => $typeTwo->get('name'), + 'description' => $typeTwo->get('description'), ], ], ] @@ -56,7 +56,7 @@ public function getIndividualTypes(ApiTester $I) public function getIndividualTypesNoData(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -65,19 +65,4 @@ public function getIndividualTypesNoData(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/api/LoginCest.php b/tests/api/LoginCest.php index 0084e50d..792684e7 100644 --- a/tests/api/LoginCest.php +++ b/tests/api/LoginCest.php @@ -29,11 +29,11 @@ public function loginKnownUser(ApiTester $I) $I->haveRecordWithFields( Users::class, [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://phalconphp.com', - 'usr_token_id' => '110011', + 'status' => 1, + 'username' => 'testuser', + 'password' => 'testpassword', + 'issuer' => 'https://phalconphp.com', + 'tokenId' => '110011', ] ); diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index 927479f6..130cf3e9 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -13,19 +13,19 @@ class GetCest { public function getProductTypes(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $typeOne = $I->haveRecordWithFields( ProductTypes::class, [ - 'prt_name' => uniqid('type-a-'), + 'name' => uniqid('type-a-'), ] ); $typeTwo = $I->haveRecordWithFields( ProductTypes::class, [ - 'prt_name' => uniqid('type-b-'), + 'name' => uniqid('type-b-'), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -35,19 +35,19 @@ public function getProductTypes(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $typeOne->get('prt_id'), + 'id' => $typeOne->get('id'), 'type' => Resources::PRODUCT_TYPES, 'attributes' => [ - 'name' => $typeOne->get('prt_name'), - 'description' => $typeOne->get('prt_description'), + 'name' => $typeOne->get('name'), + 'description' => $typeOne->get('description'), ], ], [ - 'id' => $typeTwo->get('prt_id'), + 'id' => $typeTwo->get('id'), 'type' => Resources::PRODUCT_TYPES, 'attributes' => [ - 'name' => $typeTwo->get('prt_name'), - 'description' => $typeTwo->get('prt_description'), + 'name' => $typeTwo->get('name'), + 'description' => $typeTwo->get('description'), ], ], ] @@ -56,7 +56,7 @@ public function getProductTypes(ApiTester $I) public function getProductTypesNoData(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -65,19 +65,4 @@ public function getProductTypesNoData(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index e53aba48..c1beb57d 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -16,15 +16,15 @@ class GetCest { public function getProduct(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); /** @var ProductTypes $productType */ $productType = $I->haveRecordWithFields( ProductTypes::class, [ - 'prt_name' => uniqid('prt-a-'), - 'prt_description' => uniqid(), + 'name' => uniqid('prt-a-'), + 'description' => uniqid(), ] ); @@ -32,40 +32,35 @@ public function getProduct(ApiTester $I) $product = $I->haveRecordWithFields( Products::class, [ - 'prd_name' => uniqid('prd-a-'), - 'prd_prt_id' => $productType->get('prt_id'), - 'prd_description' => uniqid(), - 'prd_quantity' => 25, - 'prd_price' => 19.99, + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productsUrl . '/' . $product->get('prd_id')); + $I->sendGET(Data::$productsUrl . '/' . $product->get('id')); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( [ [ - 'id' => $product->get('prd_id'), + 'id' => $product->get('id'), 'type' => Resources::PRODUCTS, 'attributes' => [ - 'name' => $product->get('prd_name'), - 'typeId' => $productType->get('prt_id'), - 'description' => $product->get('prd_description'), - 'quantity' => $product->get('prd_quantity'), - 'price' => $product->get('prd_price'), + 'name' => $product->get('name'), + 'typeId' => $productType->get('id'), + 'description' => $product->get('description'), + 'quantity' => $product->get('quantity'), + 'price' => $product->get('price'), ], 'links' => [ 'self' => sprintf( '%s/products/%s', envValue('APP_URL', 'localhost'), - $product->get('prd_id') - ), - 'related' => sprintf( - '%s/product-types/%s', - envValue('APP_URL', 'localhost'), - $productType->get('prt_id') + $product->get('id') ), ] ], @@ -75,15 +70,15 @@ public function getProduct(ApiTester $I) public function getProducts(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); /** @var ProductTypes $productType */ $productType = $I->haveRecordWithFields( ProductTypes::class, [ - 'prt_name' => uniqid('prt-a-'), - 'prt_description' => uniqid(), + 'name' => uniqid('prt-a-'), + 'description' => uniqid(), ] ); @@ -91,11 +86,11 @@ public function getProducts(ApiTester $I) $productOne = $I->haveRecordWithFields( Products::class, [ - 'prd_name' => uniqid('prd-a-'), - 'prd_prt_id' => $productType->get('prt_id'), - 'prd_description' => uniqid(), - 'prd_quantity' => 25, - 'prd_price' => 19.99, + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, ] ); @@ -103,11 +98,11 @@ public function getProducts(ApiTester $I) $productTwo = $I->haveRecordWithFields( Products::class, [ - 'prd_name' => uniqid('prd-b-'), - 'prd_prt_id' => $productType->get('prt_id'), - 'prd_description' => uniqid(), - 'prd_quantity' => 25, - 'prd_price' => 19.99, + 'name' => uniqid('prd-b-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, ] ); @@ -118,48 +113,38 @@ public function getProducts(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $productOne->get('prd_id'), + 'id' => $productOne->get('id'), 'type' => Resources::PRODUCTS, 'attributes' => [ - 'name' => $productOne->get('prd_name'), - 'typeId' => $productType->get('prt_id'), - 'description' => $productOne->get('prd_description'), - 'quantity' => $productOne->get('prd_quantity'), - 'price' => $productOne->get('prd_price'), + 'name' => $productOne->get('name'), + 'typeId' => $productType->get('id'), + 'description' => $productOne->get('description'), + 'quantity' => $productOne->get('quantity'), + 'price' => $productOne->get('price'), ], 'links' => [ 'self' => sprintf( '%s/products/%s', envValue('APP_URL', 'localhost'), - $productOne->get('prd_id') - ), - 'related' => sprintf( - '%s/product-types/%s', - envValue('APP_URL', 'localhost'), - $productType->get('prt_id') + $productOne->get('id') ), ] ], [ - 'id' => $productTwo->get('prd_id'), + 'id' => $productTwo->get('id'), 'type' => Resources::PRODUCTS, 'attributes' => [ - 'name' => $productTwo->get('prd_name'), - 'typeId' => $productType->get('prt_id'), - 'description' => $productTwo->get('prd_description'), - 'quantity' => $productTwo->get('prd_quantity'), - 'price' => $productTwo->get('prd_price'), + 'name' => $productTwo->get('name'), + 'typeId' => $productType->get('id'), + 'description' => $productTwo->get('description'), + 'quantity' => $productTwo->get('quantity'), + 'price' => $productTwo->get('price'), ], 'links' => [ 'self' => sprintf( '%s/products/%s', envValue('APP_URL', 'localhost'), - $productTwo->get('prd_id') - ), - 'related' => sprintf( - '%s/product-types/%s', - envValue('APP_URL', 'localhost'), - $productType->get('prt_id') + $productTwo->get('id') ), ] ], @@ -169,7 +154,7 @@ public function getProducts(ApiTester $I) public function getProductsNoData(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -178,19 +163,4 @@ public function getProductsNoData(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 6ab1c732..13b59566 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -24,7 +24,7 @@ public function loginKnownUserNoToken(ApiTester $I) public function loginKnownUserGetUnknownUser(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $I->deleteHeader('Authorization'); $I->sendPOST(Data::$loginUrl, Data::loginJson()); $I->seeResponseIsSuccessful(); @@ -42,7 +42,7 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) public function loginKnownUserIncorrectSignature(ApiTester $I) { - $record = $this->addRecord($I); + $record = $I->addApiUserRecord(); $I->deleteHeader('Authorization'); $I->sendPOST(Data::$loginUrl, Data::loginJson()); $I->seeResponseIsSuccessful(); @@ -63,14 +63,14 @@ public function loginKnownUserIncorrectSignature(ApiTester $I) $wrongToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $wrongToken); - $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); + $I->sendGET(Data::$usersUrl . '/' . $record->get('id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } public function loginKnownUserExpiredToken(ApiTester $I) { - $record = $this->addRecord($I); + $record = $I->addApiUserRecord(); $I->deleteHeader('Authorization'); $I->sendPOST(Data::$loginUrl, Data::loginJson()); $I->seeResponseIsSuccessful(); @@ -91,14 +91,14 @@ public function loginKnownUserExpiredToken(ApiTester $I) $expiredToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $expiredToken); - $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); + $I->sendGET(Data::$usersUrl . '/' . $record->get('id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } public function loginKnownUserInvalidToken(ApiTester $I) { - $record = $this->addRecord($I); + $record = $I->addApiUserRecord(); $I->deleteHeader('Authorization'); $I->sendPOST(Data::$loginUrl, Data::loginJson()); $I->seeResponseIsSuccessful(); @@ -119,14 +119,14 @@ public function loginKnownUserInvalidToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); + $I->sendGET(Data::$usersUrl . '/' . $record->get('id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } public function loginKnownUserInvalidUserInToken(ApiTester $I) { - $record = $this->addRecord($I); + $record = $I->addApiUserRecord(); $I->deleteHeader('Authorization'); $I->sendPOST(Data::$loginUrl, Data::loginJson()); $I->seeResponseIsSuccessful(); @@ -147,37 +147,37 @@ public function loginKnownUserInvalidUserInToken(ApiTester $I) $invalidToken = $token->__toString(); $I->haveHttpHeader('Authorization', 'Bearer ' . $invalidToken); - $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); + $I->sendGET(Data::$usersUrl . '/' . $record->get('id')); $I->seeResponseIsSuccessful(); $I->seeErrorJsonResponse('Invalid Token'); } public function loginKnownUserCorrectToken(ApiTester $I) { - $this->addRecord($I); + $I->addApiUserRecord(); $I->apiLogin(); } public function loginKnownUserValidToken(ApiTester $I) { - $record = $this->addRecord($I); + $record = $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$usersUrl . '/' . $record->get('usr_id')); + $I->sendGET(Data::$usersUrl . '/' . $record->get('id')); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( [ [ - 'id' => $record->get('usr_id'), + 'id' => $record->get('id'), 'type' => Resources::USERS, 'attributes' => [ - 'status' => $record->get('usr_status_flag'), - 'username' => $record->get('usr_username'), - 'issuer' => $record->get('usr_issuer'), - 'tokenPassword' => $record->get('usr_token_password'), - 'tokenId' => $record->get('usr_token_id'), + 'status' => $record->get('status'), + 'username' => $record->get('username'), + 'issuer' => $record->get('issuer'), + 'tokenPassword' => $record->get('tokenPassword'), + 'tokenId' => $record->get('tokenId'), ], ], ] @@ -189,24 +189,24 @@ public function getManyUsers(ApiTester $I) $userOne = $I->haveRecordWithFields( Users::class, [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', + 'status' => 1, + 'username' => 'testuser', + 'password' => 'testpassword', + 'issuer' => 'https://niden.net', + 'tokenPassword' => '12345', + 'tokenId' => '110011', ] ); $userTwo = $I->haveRecordWithFields( Users::class, [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser1', - 'usr_password' => 'testpassword1', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '789789', - 'usr_token_id' => '001100', + 'status' => 1, + 'username' => 'testuser1', + 'password' => 'testpassword1', + 'issuer' => 'https://niden.net', + 'tokenPassword' => '789789', + 'tokenId' => '001100', ] ); @@ -219,25 +219,25 @@ public function getManyUsers(ApiTester $I) $I->seeSuccessJsonResponse( [ [ - 'id' => $userOne->get('usr_id'), + 'id' => $userOne->get('id'), 'type' => Resources::USERS, 'attributes' => [ - 'status' => $userOne->get('usr_status_flag'), - 'username' => $userOne->get('usr_username'), - 'issuer' => $userOne->get('usr_issuer'), - 'tokenPassword' => $userOne->get('usr_token_password'), - 'tokenId' => $userOne->get('usr_token_id'), + 'status' => $userOne->get('status'), + 'username' => $userOne->get('username'), + 'issuer' => $userOne->get('issuer'), + 'tokenPassword' => $userOne->get('tokenPassword'), + 'tokenId' => $userOne->get('tokenId'), ], ], [ - 'id' => $userTwo->get('usr_id'), + 'id' => $userTwo->get('id'), 'type' => Resources::USERS, 'attributes' => [ - 'status' => $userTwo->get('usr_status_flag'), - 'username' => $userTwo->get('usr_username'), - 'issuer' => $userTwo->get('usr_issuer'), - 'tokenPassword' => $userTwo->get('usr_token_password'), - 'tokenId' => $userTwo->get('usr_token_id'), + 'status' => $userTwo->get('status'), + 'username' => $userTwo->get('username'), + 'issuer' => $userTwo->get('issuer'), + 'tokenPassword' => $userTwo->get('tokenPassword'), + 'tokenId' => $userTwo->get('tokenId'), ], ], ] @@ -246,18 +246,7 @@ public function getManyUsers(ApiTester $I) public function getManyUsersWithNoData(ApiTester $I) { - $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -265,19 +254,4 @@ public function getManyUsersWithNoData(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); } - - private function addRecord(ApiTester $I) - { - return $I->haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - } } diff --git a/tests/integration/library/ModelCest.php b/tests/integration/library/ModelCest.php index e65c1cf7..02a33f8e 100644 --- a/tests/integration/library/ModelCest.php +++ b/tests/integration/library/ModelCest.php @@ -5,7 +5,7 @@ use function Niden\Core\appPath; use Codeception\Stub; use \IntegrationTester; -use Niden\Logger; +use Monolog\Logger; use Niden\Models\Users; use Niden\Exception\ModelException; use Phalcon\Mvc\Model\Message; @@ -26,13 +26,12 @@ public function modelGetTablePrefix(IntegrationTester $I) $user = $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_password' => '12345', - 'usr_token_id' => '00110011', + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenPassword' => '12345', + 'tokenId' => '00110011', ] ); @@ -47,20 +46,17 @@ public function modelGetTablePrefix(IntegrationTester $I) */ public function modelGetSetFields(IntegrationTester $I) { - $user = $I->haveRecordWithFields( + $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_password' => '12345', - 'usr_token_id' => '00110011', + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenPassword' => '12345', + 'tokenId' => '00110011', ] ); - - $I->assertEquals(1000, $user->get('usr_id')); } /** @@ -74,7 +70,7 @@ public function modelSetNonExistingFields(IntegrationTester $I) ModelException::class, function () { $fixture = new Users(); - $fixture->set('usr_id', 1000) + $fixture->set('id', 1000) ->set('some_field', true) ->save() ; @@ -93,14 +89,12 @@ public function modelGetNonExistingFields(IntegrationTester $I) $user = $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_password' => '12345', - 'usr_token_id' => '00110011', - + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenPassword' => '12345', + 'tokenId' => '00110011', ] ); @@ -125,26 +119,24 @@ public function modelUpdateFields(IntegrationTester $I) $user = $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_password' => '12345', - 'usr_token_id' => '00110011', - + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenPassword' => '12345', + 'tokenId' => '00110011', ] ); - $user->set('usr_username', 'testusername') + $user->set('username', 'testusername') ->save() ; - $I->assertEquals($user->get('usr_username'), 'testusername'); - $I->assertEquals($user->get('usr_password'), 'testpass'); - $I->assertEquals($user->get('usr_issuer'), 'phalconphp.com'); - $I->assertEquals($user->get('usr_token_password'), '12345'); - $I->assertEquals($user->get('usr_token_id'), '00110011'); + $I->assertEquals($user->get('username'), 'testusername'); + $I->assertEquals($user->get('password'), 'testpass'); + $I->assertEquals($user->get('issuer'), 'phalconphp.com'); + $I->assertEquals($user->get('tokenPassword'), '12345'); + $I->assertEquals($user->get('tokenId'), '00110011'); } /** @@ -158,27 +150,26 @@ public function modelUpdateFieldsNotSanitized(IntegrationTester $I) $user = $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_password' => '12345', - 'usr_token_id' => '00110011', + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenPassword' => '12345', + 'tokenId' => '00110011', ] ); - $user->set('usr_password', 'abcde\nfg') + $user->set('password', 'abcde\nfg') ->save() ; - $I->assertEquals($user->get('usr_password'), 'abcde\nfg'); + $I->assertEquals($user->get('password'), 'abcde\nfg'); /** Not sanitized */ - $user->set('usr_password', 'abcde\nfg', false) + $user->set('password', 'abcde\nfg', false) ->save() ; - $I->assertEquals($user->get('usr_password'), 'abcde\nfg'); + $I->assertEquals($user->get('password'), 'abcde\nfg'); } /** @@ -199,7 +190,7 @@ public function checkModelMessages(IntegrationTester $I) ); $result = $user - ->set('usr_username', 'test') + ->set('username', 'test') ->save(); $I->assertFalse($result); @@ -227,7 +218,7 @@ public function checkModelMessagesWithLogger(IntegrationTester $I) $fileName = appPath('storage/logs/api.log'); $result = $user - ->set('usr_username', 'test') + ->set('username', 'test') ->save(); $I->assertFalse($result); $I->assertEquals('error 1
error 2
', $user->getModelMessages()); diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index 4d690534..ee99f461 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -29,11 +29,11 @@ public function validateFilters(IntegrationTester $I) { $model = new Companies(); $expected = [ - 'com_id' => Filter::FILTER_ABSINT, - 'com_name' => Filter::FILTER_STRING, - 'com_address' => Filter::FILTER_STRING, - 'com_city' => Filter::FILTER_STRING, - 'com_telephone' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'address' => Filter::FILTER_STRING, + 'city' => Filter::FILTER_STRING, + 'phone' => Filter::FILTER_STRING, ]; $I->assertEquals($expected, $model->getModelFilters()); } @@ -59,10 +59,10 @@ public function validateUniqueName(IntegrationTester $I) $companyOne = new Companies(); /** @var Companies $companyOne */ $result = $companyOne - ->set('com_name', 'acme') - ->set('com_address', '123 Phalcon way') - ->set('com_city', 'World') - ->set('com_telephone', '555-999-4444') + ->set('name', 'acme') + ->set('address', '123 Phalcon way') + ->set('city', 'World') + ->set('phone', '555-999-4444') ->save() ; $I->assertNotEquals(false, $result); @@ -70,10 +70,10 @@ public function validateUniqueName(IntegrationTester $I) $companyTwo = new Companies(); /** @var Companies $companyTwo */ $result = $companyTwo - ->set('com_name', 'acme') - ->set('com_address', '123 Phalcon way') - ->set('com_city', 'World') - ->set('com_telephone', '555-999-4444') + ->set('name', 'acme') + ->set('address', '123 Phalcon way') + ->set('city', 'World') + ->set('phone', '555-999-4444') ->save() ; $I->assertEquals(false, $result); diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index 2bee0418..7eb164b6 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -26,9 +26,9 @@ public function validateFilters(IntegrationTester $I) { $model = new IndividualTypes(); $expected = [ - 'idt_id' => Filter::FILTER_ABSINT, - 'idt_name' => Filter::FILTER_STRING, - 'idt_description' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, ]; $I->assertEquals($expected, $model->getModelFilters()); } diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php index ecb9b605..ae4d59e0 100644 --- a/tests/integration/library/Models/IndividualsCest.php +++ b/tests/integration/library/Models/IndividualsCest.php @@ -32,14 +32,14 @@ public function validateFilters(IntegrationTester $I) { $model = new Individuals(); $expected = [ - 'ind_id' => Filter::FILTER_ABSINT, - 'ind_com_id' => Filter::FILTER_ABSINT, - 'ind_idt_id' => Filter::FILTER_ABSINT, - 'ind_name_prefix' => Filter::FILTER_STRING, - 'ind_name_first' => Filter::FILTER_STRING, - 'ind_name_middle' => Filter::FILTER_STRING, - 'ind_name_last' => Filter::FILTER_STRING, - 'ind_name_suffix' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'companyId' => Filter::FILTER_ABSINT, + 'typeId' => Filter::FILTER_ABSINT, + 'prefix' => Filter::FILTER_STRING, + 'first' => Filter::FILTER_STRING, + 'middle' => Filter::FILTER_STRING, + 'last' => Filter::FILTER_STRING, + 'suffix' => Filter::FILTER_STRING, ]; $I->assertEquals($expected, $model->getModelFilters()); } diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index a1ad72ab..70871f3e 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -26,9 +26,9 @@ public function validateFilters(IntegrationTester $I) { $model = new ProductTypes(); $expected = [ - 'prt_id' => Filter::FILTER_ABSINT, - 'prt_name' => Filter::FILTER_STRING, - 'prt_description' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, ]; $I->assertEquals($expected, $model->getModelFilters()); } diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index 5f0bd038..2cbd38b1 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -30,12 +30,12 @@ public function validateFilters(IntegrationTester $I) { $model = new Products(); $expected = [ - 'prd_id' => Filter::FILTER_ABSINT, - 'prd_prt_id' => Filter::FILTER_ABSINT, - 'prd_name' => Filter::FILTER_STRING, - 'prd_description' => Filter::FILTER_STRING, - 'prd_quantity' => Filter::FILTER_ABSINT, - 'prd_price' => Filter::FILTER_FLOAT, + 'id' => Filter::FILTER_ABSINT, + 'typeId' => Filter::FILTER_ABSINT, + 'name' => Filter::FILTER_STRING, + 'description' => Filter::FILTER_STRING, + 'quantity' => Filter::FILTER_ABSINT, + 'price' => Filter::FILTER_FLOAT, ]; $I->assertEquals($expected, $model->getModelFilters()); } diff --git a/tests/integration/library/Models/UsersCest.php b/tests/integration/library/Models/UsersCest.php index 58a212ff..7869c14f 100644 --- a/tests/integration/library/Models/UsersCest.php +++ b/tests/integration/library/Models/UsersCest.php @@ -32,13 +32,13 @@ public function validateFilters(IntegrationTester $I) { $model = new Users(); $expected = [ - 'usr_id' => Filter::FILTER_ABSINT, - 'usr_status_flag' => Filter::FILTER_ABSINT, - 'usr_username' => Filter::FILTER_STRING, - 'usr_password' => Filter::FILTER_STRING, - 'usr_issuer' => Filter::FILTER_STRING, - 'usr_token_password' => Filter::FILTER_STRING, - 'usr_token_id' => Filter::FILTER_STRING, + 'id' => Filter::FILTER_ABSINT, + 'status' => Filter::FILTER_ABSINT, + 'username' => Filter::FILTER_STRING, + 'password' => Filter::FILTER_STRING, + 'issuer' => Filter::FILTER_STRING, + 'tokenPassword' => Filter::FILTER_STRING, + 'tokenId' => Filter::FILTER_STRING, ]; $I->assertEquals($expected, $model->getModelFilters()); } @@ -55,12 +55,12 @@ public function checkValidationData(IntegrationTester $I) $user = $I->haveRecordWithFields( Users::class, [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', + 'username' => 'testuser', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'https://niden.net', + 'tokenPassword' => '12345', + 'tokenId' => '110011', ] ); diff --git a/tests/integration/library/Traits/QueryCest.php b/tests/integration/library/Traits/QueryCest.php index f5bd68a6..12e3a1d2 100644 --- a/tests/integration/library/Traits/QueryCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -29,19 +29,17 @@ public function checkGetUserByUsernameAndPassword(IntegrationTester $I) $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1000, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_id' => '00110011', - + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenId' => '00110011', ] ); $dbUser = $this->getUserByUsernameAndPassword('testusername', 'testpass'); - $I->assertEquals(1000, $dbUser->get('usr_id')); + $I->assertNotEquals(false, $dbUser); } /** @@ -55,13 +53,11 @@ public function checkGetUserByWrongUsernameAndPasswordReturnsFalse(IntegrationTe $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1001, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_id' => '00110011', - + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenId' => '00110011', ] ); @@ -79,13 +75,11 @@ public function checkGetUserByWrongTokenReturnsFalse(IntegrationTester $I) $I->haveRecordWithFields( Users::class, [ - 'usr_id' => 1003, - 'usr_username' => 'testusername', - 'usr_password' => 'testpass', - 'usr_status_flag' => 1, - 'usr_issuer' => 'phalconphp.com', - 'usr_token_id' => '00110011', - + 'username' => 'testusername', + 'password' => 'testpass', + 'status' => 1, + 'issuer' => 'phalconphp.com', + 'tokenId' => '00110011', ] ); diff --git a/tests/integration/library/Transformers/BaseTransformerCest.php b/tests/integration/library/Transformers/BaseTransformerCest.php new file mode 100644 index 00000000..13b3ddf7 --- /dev/null +++ b/tests/integration/library/Transformers/BaseTransformerCest.php @@ -0,0 +1,42 @@ +haveRecordWithFields( + Companies::class, + [ + 'name' => 'acme', + 'address' => '123 Phalcon way', + 'city' => 'World', + 'phone' => '555-999-4444', + ] + ); + + $transformer = new BaseTransformer(); + $expected = [ + 'id' => $company->get('id'), + 'name' => $company->get('name'), + 'address' => $company->get('address'), + 'city' => $company->get('city'), + 'phone' => $company->get('phone'), + ]; + + $I->assertEquals($expected, $transformer->transform($company)); + } +} diff --git a/tests/integration/library/Transformers/CompaniesTransformerCest.php b/tests/integration/library/Transformers/CompaniesTransformerCest.php deleted file mode 100644 index 6cd0587d..00000000 --- a/tests/integration/library/Transformers/CompaniesTransformerCest.php +++ /dev/null @@ -1,52 +0,0 @@ -haveRecordWithFields( - Companies::class, - [ - 'com_name' => 'acme', - 'com_address' => '123 Phalcon way', - 'com_city' => 'World', - 'com_telephone' => '555-999-4444', - ] - ); - - $transformer = new CompaniesTransformer(); - $expected = [ - 'id' => $company->get('com_id'), - 'type' => Resources::COMPANIES, - 'attributes' => [ - 'name' => $company->get('com_name'), - 'address' => $company->get('com_address'), - 'city' => $company->get('com_city'), - 'phone' => $company->get('com_telephone'), - ], - 'links' => [ - 'self' => sprintf( - '%s/companies/%s', - envValue('APP_URL', 'localhost'), - $company->get('com_id') - ), - ] - ]; - - $I->assertEquals($expected, $transformer->transform($company)); - } -} diff --git a/tests/integration/library/Transformers/IndividualTypesTransformerCest.php b/tests/integration/library/Transformers/IndividualTypesTransformerCest.php deleted file mode 100644 index 52469fb9..00000000 --- a/tests/integration/library/Transformers/IndividualTypesTransformerCest.php +++ /dev/null @@ -1,49 +0,0 @@ -haveRecordWithFields( - IndividualTypes::class, - [ - 'idt_name' => uniqid('type-n-'), - 'idt_description' => uniqid('type-d-'), - ] - ); - - $transformer = new IndividualTypesTransformer(); - $expected = [ - 'id' => $type->get('idt_id'), - 'type' => Resources::INDIVIDUAL_TYPES, - 'attributes' => [ - 'name' => $type->get('idt_name'), - 'description' => $type->get('idt_description'), - ], - 'links' => [ - 'self' => sprintf( - '%s/individualtypes/%s', - envValue('APP_URL', 'localhost'), - $type->get('idt_id') - ), - ] - ]; - - $I->assertEquals($expected, $transformer->transform($type)); - } -} diff --git a/tests/integration/library/Transformers/ProductTypesTransformerCest.php b/tests/integration/library/Transformers/ProductTypesTransformerCest.php deleted file mode 100644 index c0ff28e7..00000000 --- a/tests/integration/library/Transformers/ProductTypesTransformerCest.php +++ /dev/null @@ -1,49 +0,0 @@ -haveRecordWithFields( - ProductTypes::class, - [ - 'prt_name' => uniqid('type-n-'), - 'prt_description' => uniqid('type-d-'), - ] - ); - - $transformer = new ProductTypesTransformer(); - $expected = [ - 'id' => $type->get('prt_id'), - 'type' => Resources::PRODUCT_TYPES, - 'attributes' => [ - 'name' => $type->get('prt_name'), - 'description' => $type->get('prt_description'), - ], - 'links' => [ - 'self' => sprintf( - '%s/producttypes/%s', - envValue('APP_URL', 'localhost'), - $type->get('prt_id') - ), - ] - ]; - - $I->assertEquals($expected, $transformer->transform($type)); - } -} diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php deleted file mode 100644 index ee4625a5..00000000 --- a/tests/integration/library/Transformers/ProductsTransformerCest.php +++ /dev/null @@ -1,69 +0,0 @@ -haveRecordWithFields( - ProductTypes::class, - [ - 'prt_name' => uniqid('prt-a-'), - 'prt_description' => uniqid(), - ] - ); - - /** @var Products $product */ - $product = $I->haveRecordWithFields( - Products::class, - [ - 'prd_name' => 'test product', - 'prd_prt_id' => $productType->get('prt_id'), - 'prd_description' => 'test product description', - 'prd_quantity' => 25, - 'prd_price' => 19.99, - ] - ); - - $transformer = new ProductsTransformer(); - $expected = [ - 'id' => $product->get('prd_id'), - 'type' => Resources::PRODUCTS, - 'attributes' => [ - 'name' => $product->get('prd_name'), - 'typeId' => $productType->get('prt_id'), - 'description' => $product->get('prd_description'), - 'quantity' => $product->get('prd_quantity'), - 'price' => $product->get('prd_price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/products/%s', - envValue('APP_URL', 'localhost'), - $product->get('prd_id') - ), - 'related' => sprintf( - '%s/product-types/%s', - envValue('APP_URL', 'localhost'), - $productType->get('prt_id') - ), - ] - ]; - - $I->assertEquals($expected, $transformer->transform($product)); - } -} diff --git a/tests/integration/library/Transformers/UsersTransformerCest.php b/tests/integration/library/Transformers/UsersTransformerCest.php deleted file mode 100644 index 9d3f35c5..00000000 --- a/tests/integration/library/Transformers/UsersTransformerCest.php +++ /dev/null @@ -1,47 +0,0 @@ -haveRecordWithFields( - Users::class, - [ - 'usr_status_flag' => 1, - 'usr_username' => 'testuser', - 'usr_password' => 'testpassword', - 'usr_issuer' => 'https://niden.net', - 'usr_token_password' => '12345', - 'usr_token_id' => '110011', - ] - ); - - $transformer = new UsersTransformer(); - $expected = [ - 'id' => $user->get('usr_id'), - 'type' => Resources::USERS, - 'attributes' => [ - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), - ], - ]; - - $I->assertEquals($expected, $transformer->transform($user)); - } -} diff --git a/tests/unit/library/Constants/ResourcesCest.php b/tests/unit/library/Constants/ResourcesCest.php index 70c564ed..041f6cf8 100644 --- a/tests/unit/library/Constants/ResourcesCest.php +++ b/tests/unit/library/Constants/ResourcesCest.php @@ -10,9 +10,9 @@ class ResourcesCest public function checkConstants(CliTester $I) { $I->assertEquals('companies', Resources::COMPANIES); - $I->assertEquals('individualTypes', Resources::INDIVIDUAL_TYPES); + $I->assertEquals('individual-types', Resources::INDIVIDUAL_TYPES); $I->assertEquals('individuals', Resources::INDIVIDUALS); - $I->assertEquals('productTypes', Resources::PRODUCT_TYPES); + $I->assertEquals('product-types', Resources::PRODUCT_TYPES); $I->assertEquals('products', Resources::PRODUCTS); $I->assertEquals('users', Resources::USERS); } From c9d6b048c998d36c0aa69e538e5be29ac244499c Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 21:57:25 -0400 Subject: [PATCH 40/70] Removed obsolete files --- .../IndividualTypesTransformer.php_ | 17 ----- .../Transformers/ProductTypesTransformer.php_ | 17 ----- library/Transformers/ProductsTransformer.php_ | 63 ------------------- library/Transformers/TypesTransformer.php_ | 51 --------------- library/Transformers/UsersTransformer.php_ | 36 ----------- .../Transformers/BaseTransformerCest.php | 2 - 6 files changed, 186 deletions(-) delete mode 100644 library/Transformers/IndividualTypesTransformer.php_ delete mode 100644 library/Transformers/ProductTypesTransformer.php_ delete mode 100644 library/Transformers/ProductsTransformer.php_ delete mode 100644 library/Transformers/TypesTransformer.php_ delete mode 100644 library/Transformers/UsersTransformer.php_ diff --git a/library/Transformers/IndividualTypesTransformer.php_ b/library/Transformers/IndividualTypesTransformer.php_ deleted file mode 100644 index fe18b534..00000000 --- a/library/Transformers/IndividualTypesTransformer.php_ +++ /dev/null @@ -1,17 +0,0 @@ - $product->get('prd_id'), - 'type' => Resources::PRODUCTS, - 'attributes' => [ - 'name' => $product->get('prd_name'), - 'description' => $product->get('prd_description'), - 'quantity' => $product->get('prd_quantity'), - 'price' => $product->get('prd_price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/products/%s', - envValue('APP_URL', 'localhost'), - $product->get('prd_id') - ), - ], - ]; - } - - /** - * @param Products $product - * - * @return Item - */ - public function includeProductTypes(Products $product): Item - { - $productType = $product->getRelated(Relationships::PRODUCT_TYPE); - - return $this->item($productType, new ProductTypesTransformer()); - } -} diff --git a/library/Transformers/TypesTransformer.php_ b/library/Transformers/TypesTransformer.php_ deleted file mode 100644 index 1ad20aa1..00000000 --- a/library/Transformers/TypesTransformer.php_ +++ /dev/null @@ -1,51 +0,0 @@ - $model->get(sprintf('%s_id', $this->prefix)), - 'type' => $this->type, - 'attributes' => [ - 'name' => $model->get(sprintf('%s_name', $this->prefix)), - 'description' => $model->get(sprintf('%s_description', $this->prefix)), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL', 'localhost'), - $this->url, - $model->get($this->prefix . '_id') - ), - ] - ]; - } -} diff --git a/library/Transformers/UsersTransformer.php_ b/library/Transformers/UsersTransformer.php_ deleted file mode 100644 index b9eae7dc..00000000 --- a/library/Transformers/UsersTransformer.php_ +++ /dev/null @@ -1,36 +0,0 @@ - $user->get('usr_id'), - 'type' => Resources::USERS, - 'attributes' => [ - 'status' => $user->get('usr_status_flag'), - 'username' => $user->get('usr_username'), - 'issuer' => $user->get('usr_issuer'), - 'tokenPassword' => $user->get('usr_token_password'), - 'tokenId' => $user->get('usr_token_id'), - ], - ]; - } -} diff --git a/tests/integration/library/Transformers/BaseTransformerCest.php b/tests/integration/library/Transformers/BaseTransformerCest.php index 13b3ddf7..7e99eef1 100644 --- a/tests/integration/library/Transformers/BaseTransformerCest.php +++ b/tests/integration/library/Transformers/BaseTransformerCest.php @@ -3,8 +3,6 @@ namespace Niden\Tests\integration\library\Transformers; use IntegrationTester; -use Niden\Constants\Resources; -use function Niden\Core\envValue; use Niden\Models\Companies; use Niden\Transformers\BaseTransformer; From 0e4cfde59a18adabc7651a0c8a2cf3424805b64a Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 22:26:35 -0400 Subject: [PATCH 41/70] Corrected relationships in models. Added Cross model --- library/Constants/Relationships.php | 1 + library/Models/Companies.php | 13 ++-- library/Models/CompaniesXProducts.php | 78 +++++++++++++++++++ library/Models/IndividualTypes.php | 4 +- library/Models/Individuals.php | 8 +- library/Models/ProductTypes.php | 4 +- library/Models/Products.php | 17 ++-- library/Transformers/BaseTransformer.php | 2 +- .../Transformers/ProductTypesTransformer.php | 12 +++ library/Transformers/ProductsTransformer.php | 28 +++++++ .../library/Models/CompaniesCest.php | 3 +- .../library/Models/IndividualTypesCest.php | 2 +- .../library/Models/IndividualsCest.php | 4 +- .../library/Models/ProductTypesCest.php | 2 +- .../library/Models/ProductsCest.php | 3 +- .../library/Constants/RelationshipsCest.php | 1 + 16 files changed, 153 insertions(+), 29 deletions(-) create mode 100644 library/Models/CompaniesXProducts.php create mode 100644 library/Transformers/ProductTypesTransformer.php create mode 100644 library/Transformers/ProductsTransformer.php diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php index b63eb44e..305a35dc 100644 --- a/library/Constants/Relationships.php +++ b/library/Constants/Relationships.php @@ -7,6 +7,7 @@ class Relationships { const COMPANY = 'company'; + const COMPANIES = 'companies'; const INDIVIDUAL = 'individual'; const INDIVIDUAL_TYPE = 'individualType'; const INDIVIDUALS = 'individuals'; diff --git a/library/Models/Companies.php b/library/Models/Companies.php index be3667b5..44742d7d 100644 --- a/library/Models/Companies.php +++ b/library/Models/Companies.php @@ -23,19 +23,22 @@ class Companies extends AbstractModel public function initialize() { $this->hasMany( - 'com_id', + 'id', Individuals::class, - 'ind_com_id', + 'companyId', [ 'alias' => Relationships::INDIVIDUALS, 'reusable' => true, ] ); - $this->hasMany( - 'com_id', + $this->hasManyToMany( + 'id', + CompaniesXProducts::class, + 'cxp_com_id', + 'cxp_prd_id', Products::class, - 'prd_com_id', + 'id', [ 'alias' => Relationships::PRODUCTS, 'reusable' => true, diff --git a/library/Models/CompaniesXProducts.php b/library/Models/CompaniesXProducts.php new file mode 100644 index 00000000..7fbb287a --- /dev/null +++ b/library/Models/CompaniesXProducts.php @@ -0,0 +1,78 @@ +belongsTo( + 'cxp_com_id', + Companies::class, + 'id', + [ + 'alias' => Relationships::COMPANY, + 'reusable' => true, + ] + ); + + $this->belongsTo( + 'cxp_prd_id', + Products::class, + 'id', + [ + 'alias' => Relationships::PRODUCT, + 'reusable' => true, + ] + ); + + parent::initialize(); + } + + /** + * Model filters + * + * @return array + */ + public function getModelFilters(): array + { + return [ + 'cxp_com_id' => Filter::FILTER_ABSINT, + 'cxp_prd_id' => Filter::FILTER_ABSINT, + ]; + } + + /** + * Returns the source table from the database + * + * @return string + */ + public function getSource(): string + { + return 'co_companies_x_products'; + } + + /** + * Table prefix + * + * @return string + */ + public function getTablePrefix(): string + { + return 'cxp'; + } +} diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php index 9fedd5cd..5abe80d9 100644 --- a/library/Models/IndividualTypes.php +++ b/library/Models/IndividualTypes.php @@ -21,9 +21,9 @@ class IndividualTypes extends AbstractModel public function initialize() { $this->belongsTo( - 'idt_id', + 'id', Individuals::class, - 'ind_idt_id', + 'typeId', [ 'alias' => Relationships::INDIVIDUAL, 'reusable' => true, diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php index 3e48dd1d..90d27cc1 100644 --- a/library/Models/Individuals.php +++ b/library/Models/Individuals.php @@ -21,9 +21,9 @@ class Individuals extends AbstractModel public function initialize() { $this->belongsTo( - 'ind_com_id', + 'companyId', Companies::class, - 'com_id', + 'id', [ 'alias' => Relationships::COMPANY, 'reusable' => true, @@ -31,9 +31,9 @@ public function initialize() ); $this->hasOne( - 'ind_idt_id', + 'typeId', IndividualTypes::class, - 'idt_id', + 'id', [ 'alias' => Relationships::INDIVIDUAL_TYPE, 'reusable' => true, diff --git a/library/Models/ProductTypes.php b/library/Models/ProductTypes.php index 42c1a426..b7abf2b5 100644 --- a/library/Models/ProductTypes.php +++ b/library/Models/ProductTypes.php @@ -21,9 +21,9 @@ class ProductTypes extends AbstractModel public function initialize() { $this->belongsTo( - 'prt_id', + 'id', Products::class, - 'prd_prt_id', + 'typeId', [ 'alias' => Relationships::PRODUCT, 'reusable' => true, diff --git a/library/Models/Products.php b/library/Models/Products.php index 3fed133a..a267daa5 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -20,20 +20,23 @@ class Products extends AbstractModel */ public function initialize() { - $this->belongsTo( - 'prd_com_id', - Companies::class, - 'com_id', + $this->hasManyToMany( + 'id', + Products::class, + 'cxp_prd_id', + 'cxp_com_id', + CompaniesXProducts::class, + 'id', [ - 'alias' => Relationships::COMPANY, + 'alias' => Relationships::COMPANIES, 'reusable' => true, ] ); $this->hasOne( - 'prd_prt_id', + 'typeId', ProductTypes::class, - 'prt_id', + 'id', [ 'alias' => Relationships::PRODUCT_TYPE, 'reusable' => true, diff --git a/library/Transformers/BaseTransformer.php b/library/Transformers/BaseTransformer.php index a6efcffc..4e9200f7 100644 --- a/library/Transformers/BaseTransformer.php +++ b/library/Transformers/BaseTransformer.php @@ -10,7 +10,7 @@ use Niden\Mvc\Model\AbstractModel; /** - * Class CompaniesTransformer + * Class BaseTransformer */ class BaseTransformer extends TransformerAbstract { diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php new file mode 100644 index 00000000..c3121f23 --- /dev/null +++ b/library/Transformers/ProductTypesTransformer.php @@ -0,0 +1,12 @@ +getRelated(Relationships::PRODUCT_TYPE); + + return $this->item($productType, new ProductTypesTransformer(), Resources::PRODUCT_TYPES); + } +} diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index ee99f461..bc4949e1 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -48,8 +48,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Companies::class); $expected = [ - [2, 'com_id', Individuals::class, 'ind_com_id', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], - [2, 'com_id', Products::class, 'prd_com_id', ['alias' => Relationships::PRODUCTS, 'reusable' => true]], + [2, 'id', Individuals::class, 'companyId', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index 7eb164b6..4ec23611 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -43,7 +43,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(IndividualTypes::class); $expected = [ - [0, 'idt_id', Individuals::class, 'ind_idt_id', ['alias' => Relationships::INDIVIDUAL, 'reusable' => true]], + [0, 'id', Individuals::class, 'typeId', ['alias' => Relationships::INDIVIDUAL, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php index ae4d59e0..86f3b376 100644 --- a/tests/integration/library/Models/IndividualsCest.php +++ b/tests/integration/library/Models/IndividualsCest.php @@ -54,8 +54,8 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Individuals::class); $expected = [ - [0, 'ind_com_id', Companies::class, 'com_id', ['alias' => Relationships::COMPANY, 'reusable' => true]], - [1, 'ind_idt_id', IndividualTypes::class, 'idt_id', ['alias' => Relationships::INDIVIDUAL_TYPE, 'reusable' => true]], + [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [1, 'typeId', IndividualTypes::class, 'id', ['alias' => Relationships::INDIVIDUAL_TYPE, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index 70871f3e..998d1dc7 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -43,7 +43,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(ProductTypes::class); $expected = [ - [0, 'prt_id', Products::class, 'prd_prt_id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + [0, 'id', Products::class, 'typeId', ['alias' => Relationships::PRODUCT, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index 2cbd38b1..19f4f8f8 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -50,8 +50,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Products::class); $expected = [ - [0, 'prd_com_id', Companies::class, 'com_id', ['alias' => Relationships::COMPANY, 'reusable' => true]], - [1, 'prd_prt_id', ProductTypes::class, 'prt_id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], + [1, 'typeId', ProductTypes::class, 'id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/unit/library/Constants/RelationshipsCest.php b/tests/unit/library/Constants/RelationshipsCest.php index 9312e3e4..42613d78 100644 --- a/tests/unit/library/Constants/RelationshipsCest.php +++ b/tests/unit/library/Constants/RelationshipsCest.php @@ -10,6 +10,7 @@ class RelationshipsCest public function checkConstants(CliTester $I) { $I->assertEquals('company', Relationships::COMPANY); + $I->assertEquals('companies', Relationships::COMPANIES); $I->assertEquals('individual', Relationships::INDIVIDUAL); $I->assertEquals('individualType', Relationships::INDIVIDUAL_TYPE); $I->assertEquals('individuals', Relationships::INDIVIDUALS); From 2328ca32adedcdbc0b2d4d7bbc91675796bac8e6 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sun, 22 Jul 2018 22:30:15 -0400 Subject: [PATCH 42/70] Added test for the cross model --- .../library/Models/CompaniesXProductsCest.php | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 tests/integration/library/Models/CompaniesXProductsCest.php diff --git a/tests/integration/library/Models/CompaniesXProductsCest.php b/tests/integration/library/Models/CompaniesXProductsCest.php new file mode 100644 index 00000000..003736f1 --- /dev/null +++ b/tests/integration/library/Models/CompaniesXProductsCest.php @@ -0,0 +1,51 @@ +haveModelDefinition( + CompaniesXProducts::class, + [ + 'cxp_com_id', + 'cxp_prd_id', + ] + ); + } + + public function validateFilters(IntegrationTester $I) + { + $model = new CompaniesXProducts(); + $expected = [ + 'cxp_com_id' => Filter::FILTER_ABSINT, + 'cxp_prd_id' => Filter::FILTER_ABSINT, + ]; + $I->assertEquals($expected, $model->getModelFilters()); + } + + public function validatePrefix(IntegrationTester $I) + { + $model = new CompaniesXProducts(); + $I->assertEquals('cxp', $model->getTablePrefix()); + } + + public function validateRelationships(IntegrationTester $I) + { + $actual = $I->getModelRelationships(CompaniesXProducts::class); + $expected = [ + [0, 'cxp_com_id', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [0, 'cxp_prd_id', Products::class, 'id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + ]; + $I->assertEquals($expected, $actual); + } +} From 5da59b8b912e7fa168e10ae288a93250e0a25d07 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 23 Jul 2018 11:50:05 -0400 Subject: [PATCH 43/70] Renamed fields; Removed column map from models to simplify code; Restructured models; controllers and transformers --- api/controllers/BaseController.php | 46 +++--- api/controllers/Companies/GetController.php | 19 +-- .../IndividualTypes/GetController.php | 20 ++- .../ProductTypes/GetController.php | 22 ++- api/controllers/Products/GetController.php | 21 ++- api/controllers/Users/GetController.php | 21 ++- library/Models/Companies.php | 26 ---- library/Models/CompaniesXProducts.php | 18 +-- library/Models/IndividualTypes.php | 24 --- library/Models/Individuals.php | 29 ---- library/Models/ProductTypes.php | 24 --- library/Models/Products.php | 27 ---- library/Models/Users.php | 28 ---- library/Mvc/Model/AbstractModel.php | 5 - .../Transformers/ProductTypesTransformer.php | 12 -- library/Transformers/ProductsTransformer.php | 2 +- .../20180723152114_rename_table_fields.php | 137 ++++++++++++++++++ .../library/Models/CompaniesCest.php | 16 +- .../library/Models/CompaniesXProductsCest.php | 19 +-- .../library/Models/IndividualTypesCest.php | 12 +- .../library/Models/IndividualsCest.php | 22 +-- .../library/Models/PrefixesCest.php | 31 ---- .../library/Models/ProductTypesCest.php | 12 +- .../library/Models/ProductsCest.php | 18 +-- .../integration/library/Models/UsersCest.php | 20 +-- 25 files changed, 250 insertions(+), 381 deletions(-) delete mode 100644 library/Transformers/ProductTypesTransformer.php create mode 100644 storage/db/migrations/20180723152114_rename_table_fields.php delete mode 100644 tests/integration/library/Models/PrefixesCest.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 0157a54c..72d9db30 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -25,6 +25,30 @@ class BaseController extends Controller use FractalTrait; use QueryTrait; + /** @var string */ + protected $model = ''; + /** @var string */ + protected $resource = ''; + /** @var string */ + protected $transformer = ''; + /** @var string */ + protected $orderBy = 'name'; + + /** + * Get the company/companies + * + * @param int $id + * + * @return array + */ + public function callAction($id = 0) + { + $parameters = $this->checkIdParameter($id); + $results = $this->getRecords($this->model, $parameters, $this->orderBy); + + return $this->format($results, $this->transformer, $this->resource); + } + /** * Checks the passed id parameter and returns the relevant array back * @@ -45,26 +69,4 @@ protected function checkIdParameter($recordId = 0): array return $parameters; } - - /** - * Processes getting records as a while or one using an id - * - * @param string $model - * @param string $resource - * @param int $recordId - * @param string $orderBy - * - * @return array - */ - protected function processCall( - string $model, - string $resource, - $recordId = 0, - string $orderBy = '' - ) { - $parameters = $this->checkIdParameter($recordId); - $results = $this->getRecords($model, $parameters, $orderBy); - - return $this->format($results, BaseTransformer::class, $resource); - } } diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php index d4bbc1e1..354e8723 100644 --- a/api/controllers/Companies/GetController.php +++ b/api/controllers/Companies/GetController.php @@ -5,7 +5,9 @@ namespace Niden\Api\Controllers\Companies; use Niden\Api\Controllers\BaseController; +use Niden\Constants\Resources; use Niden\Models\Companies; +use Niden\Transformers\BaseTransformer; /** * Class GetController @@ -14,15 +16,10 @@ */ class GetController extends BaseController { - /** - * Get the company/companies - * - * @param int $companyId - * - * @return array - */ - public function callAction($companyId = 0) - { - return $this->processCall(Companies::class, 'companies', $companyId, 'name'); - } + /** @var string */ + protected $model = Companies::class; + /** @var string */ + protected $resource = Resources::COMPANIES; + /** @var string */ + protected $transformer = BaseTransformer::class; } diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index 8bafeb6e..f87a93df 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -5,7 +5,9 @@ namespace Niden\Api\Controllers\IndividualTypes; use Niden\Api\Controllers\BaseController; +use Niden\Constants\Resources; use Niden\Models\IndividualTypes; +use Niden\Transformers\BaseTransformer; /** * Class GetController @@ -14,15 +16,11 @@ */ class GetController extends BaseController { - /** - * Get the individual types - * - * @param int $typeId - * - * @return array - */ - public function callAction($typeId = 0) - { - return $this->processCall(IndividualTypes::class, 'individual-types', $typeId, 'name'); - } + /** @var string */ + protected $model = IndividualTypes::class; + /** @var string */ + protected $resource = Resources::INDIVIDUAL_TYPES; + /** @var string */ + protected $transformer = BaseTransformer::class; } + diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 46f58b59..07291505 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -5,24 +5,22 @@ namespace Niden\Api\Controllers\ProductTypes; use Niden\Api\Controllers\BaseController; +use Niden\Constants\Resources; use Niden\Models\ProductTypes; +use Niden\Transformers\BaseTransformer; /** * Class GetController * - * @package Niden\Api\Controllers\ProductTypes + * @package Niden\Api\Controllers\IndividualTypes */ class GetController extends BaseController { - /** - * Get product types - * - * @param int $typeId - * - * @return array - */ - public function callAction($typeId = 0) - { - return $this->processCall(ProductTypes::class, 'product-types', $typeId, 'name'); - } + /** @var string */ + protected $model = ProductTypes::class; + /** @var string */ + protected $resource = Resources::PRODUCT_TYPES; + /** @var string */ + protected $transformer = BaseTransformer::class; } + diff --git a/api/controllers/Products/GetController.php b/api/controllers/Products/GetController.php index 8936ea85..50ae35f9 100644 --- a/api/controllers/Products/GetController.php +++ b/api/controllers/Products/GetController.php @@ -5,24 +5,21 @@ namespace Niden\Api\Controllers\Products; use Niden\Api\Controllers\BaseController; +use Niden\Constants\Resources; use Niden\Models\Products; +use Niden\Transformers\BaseTransformer; /** * Class GetController * - * @package Niden\Api\Controllers\Products + * @package Niden\Api\Controllers\Companies */ class GetController extends BaseController { - /** - * Get products - * - * @param int $productId - * - * @return array - */ - public function callAction($productId = 0) - { - return $this->processCall(Products::class, 'products', $productId, 'name'); - } + /** @var string */ + protected $model = Products::class; + /** @var string */ + protected $resource = Resources::PRODUCTS; + /** @var string */ + protected $transformer = BaseTransformer::class; } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index 1bdcc8f1..ed6d859f 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -5,7 +5,9 @@ namespace Niden\Api\Controllers\Users; use Niden\Api\Controllers\BaseController; +use Niden\Constants\Resources; use Niden\Models\Users; +use Niden\Transformers\BaseTransformer; /** * Class GetController @@ -14,15 +16,12 @@ */ class GetController extends BaseController { - /** - * Gets users - * - * @param int $userId - * - * @return array - */ - public function callAction($userId = 0) - { - return $this->processCall(Users::class, 'users', $userId, 'username'); - } + /** @var string */ + protected $model = Users::class; + /** @var string */ + protected $resource = Resources::USERS; + /** @var string */ + protected $transformer = BaseTransformer::class; + /** @var string */ + protected $orderBy = 'username'; } diff --git a/library/Models/Companies.php b/library/Models/Companies.php index 44742d7d..f167be79 100644 --- a/library/Models/Companies.php +++ b/library/Models/Companies.php @@ -48,22 +48,6 @@ public function initialize() parent::initialize(); } - /** - * Column map to help with the API - * - * @return array - */ - public function columnMap(): array - { - return [ - 'com_id' => 'id', - 'com_name' => 'name', - 'com_address' => 'address', - 'com_city' => 'city', - 'com_telephone' => 'phone', - ]; - } - /** * Model filters * @@ -90,16 +74,6 @@ public function getSource(): string return 'co_companies'; } - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'com'; - } - /** * Validates the company name * diff --git a/library/Models/CompaniesXProducts.php b/library/Models/CompaniesXProducts.php index 7fbb287a..0417871b 100644 --- a/library/Models/CompaniesXProducts.php +++ b/library/Models/CompaniesXProducts.php @@ -21,7 +21,7 @@ class CompaniesXProducts extends AbstractModel public function initialize() { $this->belongsTo( - 'cxp_com_id', + 'companyId', Companies::class, 'id', [ @@ -31,7 +31,7 @@ public function initialize() ); $this->belongsTo( - 'cxp_prd_id', + 'productId', Products::class, 'id', [ @@ -51,8 +51,8 @@ public function initialize() public function getModelFilters(): array { return [ - 'cxp_com_id' => Filter::FILTER_ABSINT, - 'cxp_prd_id' => Filter::FILTER_ABSINT, + 'companyId' => Filter::FILTER_ABSINT, + 'productId' => Filter::FILTER_ABSINT, ]; } @@ -65,14 +65,4 @@ public function getSource(): string { return 'co_companies_x_products'; } - - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'cxp'; - } } diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php index 5abe80d9..8d1fd98e 100644 --- a/library/Models/IndividualTypes.php +++ b/library/Models/IndividualTypes.php @@ -33,20 +33,6 @@ public function initialize() parent::initialize(); } - /** - * Column map - * - * @return array - */ - public function columnMap(): array - { - return [ - 'idt_id' => 'id', - 'idt_name' => 'name', - 'idt_description' => 'description', - ]; - } - /** * Model filters * @@ -70,14 +56,4 @@ public function getSource(): string { return 'co_individual_types'; } - - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'idt'; - } } diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php index 90d27cc1..e13f7538 100644 --- a/library/Models/Individuals.php +++ b/library/Models/Individuals.php @@ -43,25 +43,6 @@ public function initialize() parent::initialize(); } - /** - * Column Map - * - * @return array - */ - public function columnMap(): array - { - return [ - 'ind_id' => 'id', - 'ind_com_id' => 'companyId', - 'ind_idt_id' => 'typeId', - 'ind_name_prefix' => 'prefix', - 'ind_name_first' => 'first', - 'ind_name_middle' => 'middle', - 'ind_name_last' => 'last', - 'ind_name_suffix' => 'suffix', - ]; - } - /** * Model filters * @@ -90,14 +71,4 @@ public function getSource(): string { return 'co_individuals'; } - - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'ind'; - } } diff --git a/library/Models/ProductTypes.php b/library/Models/ProductTypes.php index b7abf2b5..8ffe1495 100644 --- a/library/Models/ProductTypes.php +++ b/library/Models/ProductTypes.php @@ -33,20 +33,6 @@ public function initialize() parent::initialize(); } - /** - * Column Map - * - * @return array - */ - public function columnMap(): array - { - return [ - 'prt_id' => 'id', - 'prt_name' => 'name', - 'prt_description' => 'description', - ]; - } - /** * Model filters * @@ -70,14 +56,4 @@ public function getSource(): string { return 'co_product_types'; } - - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'prt'; - } } diff --git a/library/Models/Products.php b/library/Models/Products.php index a267daa5..a7ad9368 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -46,23 +46,6 @@ public function initialize() parent::initialize(); } - /** - * Column Map - * - * @return array - */ - public function columnMap(): array - { - return [ - 'prd_id' => 'id', - 'prd_prt_id' => 'typeId', - 'prd_name' => 'name', - 'prd_description' => 'description', - 'prd_quantity' => 'quantity', - 'prd_price' => 'price', - ]; - } - /** * Model filters * @@ -89,14 +72,4 @@ public function getSource(): string { return 'co_products'; } - - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'prd'; - } } diff --git a/library/Models/Users.php b/library/Models/Users.php index 408343d5..a29b6dd9 100644 --- a/library/Models/Users.php +++ b/library/Models/Users.php @@ -22,24 +22,6 @@ class Users extends AbstractModel { use TokenTrait; - /** - * Column Map - * - * @return array - */ - public function columnMap(): array - { - return [ - 'usr_id' => 'id', - 'usr_status_flag' => 'status', - 'usr_username' => 'username', - 'usr_password' => 'password', - 'usr_issuer' => 'issuer', - 'usr_token_password' => 'tokenPassword', - 'usr_token_id' => 'tokenId', - ]; - } - /** * Model filters * @@ -68,16 +50,6 @@ public function getSource(): string return 'co_users'; } - /** - * Table prefix - * - * @return string - */ - public function getTablePrefix(): string - { - return 'usr'; - } - /** * Returns the string token * diff --git a/library/Mvc/Model/AbstractModel.php b/library/Mvc/Model/AbstractModel.php index 8c6aa04f..8d2f0149 100644 --- a/library/Mvc/Model/AbstractModel.php +++ b/library/Mvc/Model/AbstractModel.php @@ -69,11 +69,6 @@ public function getModelMessages(Logger $logger = null): string return $error; } - /** - * @return string - */ - abstract public function getTablePrefix(): string; - /** * Sets a field in the model sanitized * diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php deleted file mode 100644 index c3121f23..00000000 --- a/library/Transformers/ProductTypesTransformer.php +++ /dev/null @@ -1,12 +0,0 @@ -getRelated(Relationships::PRODUCT_TYPE); - return $this->item($productType, new ProductTypesTransformer(), Resources::PRODUCT_TYPES); + return $this->item($productType, new BaseTransformer(), Resources::PRODUCT_TYPES); } } diff --git a/storage/db/migrations/20180723152114_rename_table_fields.php b/storage/db/migrations/20180723152114_rename_table_fields.php new file mode 100644 index 00000000..c3328545 --- /dev/null +++ b/storage/db/migrations/20180723152114_rename_table_fields.php @@ -0,0 +1,137 @@ +table('co_companies'); + $table + ->renameColumn('com_id', 'id') + ->renameColumn('com_name', 'name') + ->renameColumn('com_address', 'address') + ->renameColumn('com_city', 'city') + ->renameColumn('com_telephone', 'phone') + ->save(); + + $table = $this->table('co_companies_x_products'); + $table + ->renameColumn('cxp_com_id', 'companyId') + ->renameColumn('cxp_prd_id', 'productId') + ->save(); + + $table = $this->table('co_individual_types'); + $table + ->renameColumn('idt_id', 'id') + ->renameColumn('idt_name', 'name') + ->renameColumn('idt_description', 'description') + ->save(); + + $table = $this->table('co_individuals'); + $table + ->renameColumn('ind_id', 'id') + ->renameColumn('ind_com_id', 'companyId') + ->renameColumn('ind_idt_id', 'typeId') + ->renameColumn('ind_name_prefix', 'prefix') + ->renameColumn('ind_name_first', 'first') + ->renameColumn('ind_name_middle', 'middle') + ->renameColumn('ind_name_last', 'last') + ->renameColumn('ind_name_suffix', 'suffix') + ->save(); + + $table = $this->table('co_product_types'); + $table + ->renameColumn('prt_id', 'id') + ->renameColumn('prt_name', 'name') + ->renameColumn('prt_description', 'description') + ->save(); + + $table = $this->table('co_products'); + $table + ->renameColumn('prd_id', 'id') + ->renameColumn('prd_prt_id', 'typeId') + ->renameColumn('prd_name', 'name') + ->renameColumn('prd_description', 'description') + ->renameColumn('prd_quantity', 'quantity') + ->renameColumn('prd_price', 'price') + ->save(); + + $table = $this->table('co_users'); + $table + ->renameColumn('usr_id', 'id') + ->renameColumn('usr_status_flag', 'status') + ->renameColumn('usr_username', 'username') + ->renameColumn('usr_password', 'password') + ->renameColumn('usr_issuer', 'issuer') + ->renameColumn('usr_token_password', 'tokenPassword') + ->renameColumn('usr_token_id', 'tokenId') + ->save(); + } + + public function down() + { + $table = $this->table('co_companies'); + $table + ->renameColumn('id', 'com_id') + ->renameColumn('name', 'com_name') + ->renameColumn('address', 'com_address') + ->renameColumn('city', 'com_city') + ->renameColumn('phone', 'com_telephone') + ->save(); + + $table = $this->table('co_companies_x_products'); + $table + ->renameColumn('companyId', 'cxp_com_id') + ->renameColumn('productId', 'cxp_prd_id') + ->save(); + + $table = $this->table('co_individual_types'); + $table + ->renameColumn('id', 'idt_id') + ->renameColumn('name', 'idt_name') + ->renameColumn('description', 'idt_description') + ->save(); + + $table = $this->table('co_individuals'); + $table + ->renameColumn('id', 'ind_id') + ->renameColumn('companyId', 'ind_com_id') + ->renameColumn('typeId', 'ind_idt_id') + ->renameColumn('prefix', 'ind_name_prefix') + ->renameColumn('first', 'ind_name_first') + ->renameColumn('middle', 'ind_name_middle') + ->renameColumn('last', 'ind_name_last') + ->renameColumn('suffix', 'ind_name_suffix') + ->save(); + + $table = $this->table('co_product_types'); + $table + ->renameColumn('id', 'prt_id') + ->renameColumn('name', 'prt_name') + ->renameColumn('description', 'prt_description') + ->save(); + + $table = $this->table('co_products'); + $table + ->renameColumn('id', 'prd_id') + ->renameColumn('typeId', 'prd_prt_id') + ->renameColumn('name', 'prd_name') + ->renameColumn('description', 'prd_description') + ->renameColumn('quantity', 'prd_quantity') + ->renameColumn('price', 'prd_price') + ->save(); + + $table = $this->table('co_users'); + $table + ->renameColumn('id', 'usr_id') + ->renameColumn('status', 'usr_status_flag') + ->renameColumn('username', 'usr_username') + ->renameColumn('password', 'usr_password') + ->renameColumn('issuer', 'usr_issuer') + ->renameColumn('tokenPassword', 'usr_token_password') + ->renameColumn('tokenId', 'usr_token_id') + ->save(); + } +} diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index bc4949e1..1eb93477 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -16,11 +16,11 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( Companies::class, [ - 'com_id', - 'com_name', - 'com_address', - 'com_city', - 'com_telephone', + 'id', + 'name', + 'address', + 'city', + 'phone', ] ); } @@ -38,12 +38,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new Companies(); - $I->assertEquals('com', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Companies::class); diff --git a/tests/integration/library/Models/CompaniesXProductsCest.php b/tests/integration/library/Models/CompaniesXProductsCest.php index 003736f1..0bf96cb8 100644 --- a/tests/integration/library/Models/CompaniesXProductsCest.php +++ b/tests/integration/library/Models/CompaniesXProductsCest.php @@ -6,7 +6,6 @@ use Niden\Constants\Relationships; use Niden\Models\Companies; use Niden\Models\CompaniesXProducts; -use Niden\Models\Individuals; use Niden\Models\Products; use Phalcon\Filter; @@ -17,8 +16,8 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( CompaniesXProducts::class, [ - 'cxp_com_id', - 'cxp_prd_id', + 'companyId', + 'productId', ] ); } @@ -27,24 +26,18 @@ public function validateFilters(IntegrationTester $I) { $model = new CompaniesXProducts(); $expected = [ - 'cxp_com_id' => Filter::FILTER_ABSINT, - 'cxp_prd_id' => Filter::FILTER_ABSINT, + 'companyId' => Filter::FILTER_ABSINT, + 'productId' => Filter::FILTER_ABSINT, ]; $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new CompaniesXProducts(); - $I->assertEquals('cxp', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(CompaniesXProducts::class); $expected = [ - [0, 'cxp_com_id', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], - [0, 'cxp_prd_id', Products::class, 'id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [0, 'productId', Products::class, 'id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index 4ec23611..47bb24ce 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -15,9 +15,9 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( IndividualTypes::class, [ - 'idt_id', - 'idt_name', - 'idt_description', + 'id', + 'name', + 'description', ] ); } @@ -33,12 +33,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new IndividualTypes(); - $I->assertEquals('idt', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(IndividualTypes::class); diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php index 86f3b376..a9f7582c 100644 --- a/tests/integration/library/Models/IndividualsCest.php +++ b/tests/integration/library/Models/IndividualsCest.php @@ -16,14 +16,14 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( Individuals::class, [ - 'ind_id', - 'ind_com_id', - 'ind_idt_id', - 'ind_name_prefix', - 'ind_name_first', - 'ind_name_middle', - 'ind_name_last', - 'ind_name_suffix', + 'id', + 'companyId', + 'typeId', + 'prefix', + 'first', + 'middle', + 'last', + 'suffix', ] ); } @@ -44,12 +44,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new Individuals(); - $I->assertEquals('ind', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Individuals::class); diff --git a/tests/integration/library/Models/PrefixesCest.php b/tests/integration/library/Models/PrefixesCest.php deleted file mode 100644 index 069346b0..00000000 --- a/tests/integration/library/Models/PrefixesCest.php +++ /dev/null @@ -1,31 +0,0 @@ -getTablePrefix(); - $count++; - } - - $I->assertEquals($count, count($prefixes)); - } -} diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index 998d1dc7..8e3b6e13 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -15,9 +15,9 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( ProductTypes::class, [ - 'prt_id', - 'prt_name', - 'prt_description', + 'id', + 'name', + 'description', ] ); } @@ -33,12 +33,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new ProductTypes(); - $I->assertEquals('prt', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(ProductTypes::class); diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index 19f4f8f8..269cb423 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -16,12 +16,12 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( Products::class, [ - 'prd_id', - 'prd_prt_id', - 'prd_name', - 'prd_description', - 'prd_quantity', - 'prd_price', + 'id', + 'typeId', + 'name', + 'description', + 'quantity', + 'price', ] ); } @@ -40,12 +40,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new Products(); - $I->assertEquals('prd', $model->getTablePrefix()); - } - public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Products::class); diff --git a/tests/integration/library/Models/UsersCest.php b/tests/integration/library/Models/UsersCest.php index 7869c14f..d7e45f49 100644 --- a/tests/integration/library/Models/UsersCest.php +++ b/tests/integration/library/Models/UsersCest.php @@ -17,13 +17,13 @@ public function validateModel(IntegrationTester $I) $I->haveModelDefinition( Users::class, [ - 'usr_id', - 'usr_status_flag', - 'usr_username', - 'usr_password', - 'usr_issuer', - 'usr_token_password', - 'usr_token_id', + 'id', + 'status', + 'username', + 'password', + 'issuer', + 'tokenPassword', + 'tokenId', ] ); } @@ -43,12 +43,6 @@ public function validateFilters(IntegrationTester $I) $I->assertEquals($expected, $model->getModelFilters()); } - public function validatePrefix(IntegrationTester $I) - { - $model = new Users(); - $I->assertEquals('usr', $model->getTablePrefix()); - } - public function checkValidationData(IntegrationTester $I) { /** @var Users $user */ From aa094192e944301ebe15a0acde2c6f2596e1ac66 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 23 Jul 2018 11:56:35 -0400 Subject: [PATCH 44/70] Removed obsolete test --- tests/integration/library/ModelCest.php | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/tests/integration/library/ModelCest.php b/tests/integration/library/ModelCest.php index 02a33f8e..14b51545 100644 --- a/tests/integration/library/ModelCest.php +++ b/tests/integration/library/ModelCest.php @@ -15,30 +15,6 @@ */ class ModelCest { - /** - * @param IntegrationTester $I - * - * @throws ModelException - */ - public function modelGetTablePrefix(IntegrationTester $I) - { - /** @var Users $result */ - $user = $I->haveRecordWithFields( - Users::class, - [ - 'username' => 'testusername', - 'password' => 'testpass', - 'status' => 1, - 'issuer' => 'phalconphp.com', - 'tokenPassword' => '12345', - 'tokenId' => '00110011', - - ] - ); - - $I->assertEquals('usr', $user->getTablePrefix()); - } - /** * @param IntegrationTester $I * From ed5868aa99f81746d971e76cb50ea07974244521 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 23 Jul 2018 12:41:40 -0400 Subject: [PATCH 45/70] Added more tests --- .../Transformers/ProductsTransformerCest.php | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 tests/integration/library/Transformers/ProductsTransformerCest.php diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php new file mode 100644 index 00000000..a62d4a53 --- /dev/null +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -0,0 +1,121 @@ +haveRecordWithFields( + ProductTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Products $product */ + $product = $I->haveRecordWithFields( + Products::class, + [ + 'name' => 'my product', + 'typeId' => $productType->get('id'), + 'description' => 'my product description', + 'quantity' => 99, + 'price' => 19.99, + ] + ); + + $url = envValue('APP_URL', 'http://localhost'); + $manager = new Manager(); + $manager->setSerializer(new JsonApiSerializer($url)); + $manager->parseIncludes(Resources::PRODUCT_TYPES); + $resource = new Collection([$product], new ProductsTransformer(), Resources::PRODUCTS); + $results = $manager->createData($resource)->toArray(); + $expected = [ + 'data' => [ + [ + 'type' => Resources::PRODUCTS, + 'id' => $product->get('id'), + 'attributes' => [ + 'typeId' => $productType->get('id'), + 'name' => $product->get('name'), + 'description' => $product->get('description'), + 'quantity' => $product->get('quantity'), + 'price' => $product->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + $url, + Resources::PRODUCTS, + $product->get('id') + ), + ], + 'relationships' => [ + Resources::PRODUCT_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + $url, + Resources::PRODUCTS, + $product->get('id'), + Resources::PRODUCT_TYPES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + $url, + Resources::PRODUCTS, + $product->get('id'), + Resources::PRODUCT_TYPES + ), + ], + 'data' => [ + 'type' => Resources::PRODUCT_TYPES, + 'id' => $productType->get('id'), + ], + ], + ], + ], + ], + 'included' => [ + [ + 'type' => Resources::PRODUCT_TYPES, + 'id' => $productType->get('id'), + 'attributes' => [ + 'name' => $productType->get('name'), + 'description' => $productType->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + $url, + Resources::PRODUCT_TYPES, + $productType->get('id') + ), + ], + ], + ], + ]; + + $I->assertEquals($expected, $results); + } +} From c485d82e4b8aab00d6c3f735a1dc9111f4477650 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 24 Jul 2018 16:46:01 -0400 Subject: [PATCH 46/70] Get on unknown record returns 404; Refactor for relationships; Added relationship route for companies --- api/controllers/BaseController.php | 55 ++++++++++++++++--- api/controllers/Companies/GetController.php | 14 ++++- .../Middleware/AuthenticationMiddleware.php | 3 +- library/Middleware/NotFoundMiddleware.php | 2 +- library/Middleware/TokenUserMiddleware.php | 2 +- .../Middleware/TokenValidationMiddleware.php | 2 +- .../TokenVerificationMiddleware.php | 2 +- library/Providers/ResponseProvider.php | 9 ++- library/Providers/RouterProvider.php | 1 + library/Traits/FractalTrait.php | 11 +++- library/Traits/ResponseTrait.php | 8 ++- tests/_support/ApiTester.php | 27 +++++++++ tests/api/Companies/GetCest.php | 11 ++++ tests/api/NotFoundCest.php | 3 +- tests/api/Users/GetCest.php | 3 +- tests/unit/BootstrapCest.php | 2 +- tests/unit/library/Providers/RouterCest.php | 3 +- 17 files changed, 132 insertions(+), 26 deletions(-) diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 72d9db30..28aff507 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -4,49 +4,80 @@ namespace Niden\Api\Controllers; +use function explode; +use function in_array; use Niden\Exception\ModelException; use Niden\Http\Request; use Niden\Http\Response; use Niden\Models\Users; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; +use Niden\Traits\ResponseTrait; use Niden\Traits\TokenTrait; use Niden\Transformers\BaseTransformer; use Phalcon\Filter; use Phalcon\Mvc\Controller; +use Phalcon\Mvc\Micro; +use Phalcon\Mvc\Model\ResultsetInterface; +use function strtolower; +use function trim; /** * Class BaseController * * @package Niden\Api\Controllers + * + * @property Micro $application + * @property Response $response */ class BaseController extends Controller { use FractalTrait; use QueryTrait; + use ResponseTrait; /** @var string */ - protected $model = ''; + protected $model = ''; + /** @var array */ + protected $relationships = []; /** @var string */ - protected $resource = ''; + protected $resource = ''; /** @var string */ - protected $transformer = ''; + protected $transformer = ''; /** @var string */ - protected $orderBy = 'name'; + protected $orderBy = 'name'; /** * Get the company/companies * - * @param int $id + * @param int $id + * @param string $relationships * * @return array */ - public function callAction($id = 0) + public function callAction($id = 0, $relationships = '') { $parameters = $this->checkIdParameter($id); + $parameter = $this->filter->sanitize($relationships, [Filter::FILTER_STRING, Filter::FILTER_TRIM]); $results = $this->getRecords($this->model, $parameters, $this->orderBy); + $related = []; + + if (count($parameters) > 0 && 0 === count($results)) { + return $this->send404(); + } else { + if (true !== empty($parameter)) { + $allRelationships = explode(',', $relationships); + foreach ($allRelationships as $relationship) { + if (true !== in_array($relationship, $this->relationships)) { + return $this->send404(); + } - return $this->format($results, $this->transformer, $this->resource); + $results[] = strtolower($relationship); + } + } + } + + return $this->format($results, $this->transformer, $this->resource, $related); } /** @@ -56,7 +87,7 @@ public function callAction($id = 0) * * @return array */ - protected function checkIdParameter($recordId = 0): array + private function checkIdParameter($recordId = 0): array { $parameters = []; @@ -69,4 +100,12 @@ protected function checkIdParameter($recordId = 0): array return $parameters; } + + /** + * Sends a 404 back + */ + private function send404() + { + $this->response->setPayloadError('Not Found')->setStatusCode(404); + } } diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php index 354e8723..eb9f2335 100644 --- a/api/controllers/Companies/GetController.php +++ b/api/controllers/Companies/GetController.php @@ -17,9 +17,17 @@ class GetController extends BaseController { /** @var string */ - protected $model = Companies::class; + protected $model = Companies::class; + + /** @var array */ + protected $relationships = [ + Resources::INDIVIDUALS, + Resources::PRODUCTS, + ]; + /** @var string */ - protected $resource = Resources::COMPANIES; + protected $resource = Resources::COMPANIES; + /** @var string */ - protected $transformer = BaseTransformer::class; + protected $transformer = BaseTransformer::class; } diff --git a/library/Middleware/AuthenticationMiddleware.php b/library/Middleware/AuthenticationMiddleware.php index b08e48f5..9dcd762f 100755 --- a/library/Middleware/AuthenticationMiddleware.php +++ b/library/Middleware/AuthenticationMiddleware.php @@ -5,6 +5,7 @@ namespace Niden\Middleware; use Niden\Http\Request; +use Niden\Http\Response; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Phalcon\Mvc\Micro; @@ -34,7 +35,7 @@ public function call(Micro $api) if (true !== $request->isLoginPage() && true === $request->isEmptyBearerToken()) { - $this->halt($api, 'Invalid Token'); + $this->halt($api, 200, 'Invalid Token'); return false; } diff --git a/library/Middleware/NotFoundMiddleware.php b/library/Middleware/NotFoundMiddleware.php index 4545dbef..8940e1f6 100755 --- a/library/Middleware/NotFoundMiddleware.php +++ b/library/Middleware/NotFoundMiddleware.php @@ -27,7 +27,7 @@ class NotFoundMiddleware extends Plugin implements MiddlewareInterface */ public function beforeNotFound() { - $this->halt($this->application, '404 Not Found'); + $this->halt($this->application, 404, 'Not Found'); return false; } diff --git a/library/Middleware/TokenUserMiddleware.php b/library/Middleware/TokenUserMiddleware.php index 4f096314..0e030456 100755 --- a/library/Middleware/TokenUserMiddleware.php +++ b/library/Middleware/TokenUserMiddleware.php @@ -34,7 +34,7 @@ public function call(Micro $api) /** @var Users|false $user */ $user = $this->getUserByToken($token); if (false === $user) { - $this->halt($api, 'Invalid Token'); + $this->halt($api, 200, 'Invalid Token'); return false; } diff --git a/library/Middleware/TokenValidationMiddleware.php b/library/Middleware/TokenValidationMiddleware.php index a5830aba..f8e7b054 100755 --- a/library/Middleware/TokenValidationMiddleware.php +++ b/library/Middleware/TokenValidationMiddleware.php @@ -38,7 +38,7 @@ public function call(Micro $api) /** @var Users $user */ $user = $this->getUserByToken($token); if (false === $token->validate($user->getValidationData())) { - $this->halt($api, 'Invalid Token'); + $this->halt($api, 200, 'Invalid Token'); return false; } diff --git a/library/Middleware/TokenVerificationMiddleware.php b/library/Middleware/TokenVerificationMiddleware.php index 0eceece8..e92ecd2f 100755 --- a/library/Middleware/TokenVerificationMiddleware.php +++ b/library/Middleware/TokenVerificationMiddleware.php @@ -40,7 +40,7 @@ public function call(Micro $api) /** @var Users $user */ $user = $this->getUserByToken($token); if (false === $token->verify($signer, $user->get('tokenPassword'))) { - $this->halt($api, 'Invalid Token'); + $this->halt($api, 200, 'Invalid Token'); } } diff --git a/library/Providers/ResponseProvider.php b/library/Providers/ResponseProvider.php index 0a071764..95239ea8 100644 --- a/library/Providers/ResponseProvider.php +++ b/library/Providers/ResponseProvider.php @@ -15,6 +15,13 @@ class ResponseProvider implements ServiceProviderInterface */ public function register(DiInterface $container) { - $container->setShared('response', new Response()); + $response = new Response(); + + /** + * Assume success. We will work with the edge cases in the code + */ + $response->setStatusCode(200); + + $container->setShared('response', $response); } } diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index 8dc9aac3..4552e2d7 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -112,6 +112,7 @@ private function getRoutes(): array [CompaniesAddController::class, '/companies', 'post', '/'], [CompaniesGetController::class, '/companies', 'get', '/'], [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], + [CompaniesGetController::class, '/companies', 'get', '/relationships/{relationships:[a-zA-Z,.}'], [IndividualTypesGetController::class, '/individual-types', 'get', '/'], [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}'], [ProductsGetController::class, '/products', 'get', '/'], diff --git a/library/Traits/FractalTrait.php b/library/Traits/FractalTrait.php index 7a0d2572..2f35b4bb 100644 --- a/library/Traits/FractalTrait.php +++ b/library/Traits/FractalTrait.php @@ -22,14 +22,23 @@ trait FractalTrait * @param mixed $results * @param string $transformer * @param string $resource + * @param array $relationships * * @return array */ - protected function format($results, string $transformer, string $resource): array + protected function format($results, string $transformer, string $resource, array $relationships = []): array { $url = envValue('APP_URL', 'http://localhost'); $manager = new Manager(); $manager->setSerializer(new JsonApiSerializer($url)); + + /** + * Process relationships + */ + foreach ($relationships as $relationship) { + $manager->parseIncludes($relationship); + } + $resource = new Collection($results, new $transformer(), $resource); $results = $manager->createData($resource)->toArray(); diff --git a/library/Traits/ResponseTrait.php b/library/Traits/ResponseTrait.php index 787c86f7..cc2a939c 100644 --- a/library/Traits/ResponseTrait.php +++ b/library/Traits/ResponseTrait.php @@ -18,16 +18,18 @@ trait ResponseTrait * Halt execution after setting the message in the response * * @param Micro $api + * @param int $status * @param string $message * * @return mixed */ - protected function halt(Micro $api, string $message) + protected function halt(Micro $api, int $status, string $message) { /** @var Response $response */ $response = $api->getService('response'); $response ->setPayloadError($message) + ->setStatusCode($status) ->send(); $api->stop(); @@ -38,7 +40,9 @@ public function process(Micro $api) /** @var Response $response */ $response = $api->getService('response'); $data = $api->getReturnedValue(); - $response->setPayloadSuccess($data); + if (200 === $response->getStatusCode()) { + $response->setPayloadSuccess($data); + } if (true !== $response->isSent()) { $response->send(); diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index 3879d250..2dde6da8 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -54,6 +54,33 @@ public function seeResponseIsSuccessful() $this->assertEquals($hash, sha1($timestamp . json_encode($response[$section]))); } + /** + * Checks if the response was successful + */ + public function seeResponseIs404() + { + $this->seeResponseIsJson(); + $this->seeResponseCodeIs(HttpCode::NOT_FOUND); + $this->seeResponseMatchesJsonType( + [ + 'jsonapi' => [ + 'version' => 'string' + ], + 'meta' => [ + 'timestamp' => 'string:date', + 'hash' => 'string', + ] + ] + ); + + $response = $this->grabResponse(); + $response = json_decode($response, true); + $timestamp = $response['meta']['timestamp']; + $hash = $response['meta']['hash']; + $this->assertEquals('Not Found', $response['errors'][0]); + $this->assertEquals($hash, sha1($timestamp . json_encode($response['errors']))); + } + public function seeErrorJsonResponse(string $message) { $this->seeResponseContainsJson( diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 0e12c4e5..2b19a3b7 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -45,6 +45,17 @@ public function getCompany(ApiTester $I) ); } + public function getUnknownCompany(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl . '/9999'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + public function getCompanies(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/NotFoundCest.php b/tests/api/NotFoundCest.php index aa25932d..9696808f 100644 --- a/tests/api/NotFoundCest.php +++ b/tests/api/NotFoundCest.php @@ -12,7 +12,6 @@ class NotFoundCest public function checkNotFoundRoute(ApiTester $I) { $I->sendGET(Data::$wrongUrl); - $I->seeResponseIsSuccessful(); - $I->seeErrorJsonResponse('404 Not Found'); + $I->seeResponseIs404(); } } diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 13b59566..636f4a97 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -36,8 +36,7 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$usersUrl . '/1'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse(); + $I->seeResponseIs404(); } public function loginKnownUserIncorrectSignature(ApiTester $I) diff --git a/tests/unit/BootstrapCest.php b/tests/unit/BootstrapCest.php index adf82bed..2465c589 100644 --- a/tests/unit/BootstrapCest.php +++ b/tests/unit/BootstrapCest.php @@ -17,6 +17,6 @@ public function checkBootstrap(CliTester $I) $results = json_decode($actual, true); $I->assertEquals('1.0', $results['jsonapi']['version']); $I->assertEmpty($results['data']); - $I->assertEquals('404 Not Found', $results['errors'][0]); + $I->assertEquals('Not Found', $results['errors'][0]); } } diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 9cd1f1ff..a99d0f78 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -34,6 +34,7 @@ public function checkRegistration(UnitTester $I) ['POST', '/companies'], ['GET', '/companies'], ['GET', '/companies/{companyId:[0-9]+}'], + ['GET', '/companies/relationships/{relationships:[a-zA-Z,.}'], ['GET', '/individual-types'], ['GET', '/individual-types/{typeId:[0-9]+}'], ['GET', '/products'], @@ -44,7 +45,7 @@ public function checkRegistration(UnitTester $I) ['GET', '/users/{userId:[0-9]+}'], ]; - $I->assertEquals(12, count($routes)); + $I->assertEquals(13, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); From d38a2759966104532a52e5428a4f62ee45cf2072 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 24 Jul 2018 18:49:21 -0400 Subject: [PATCH 47/70] Reformatted tests; Added tests for companies->products --- api/controllers/BaseController.php | 23 +- api/controllers/Companies/GetController.php | 12 +- .../IndividualTypes/GetController.php | 4 +- .../ProductTypes/GetController.php | 16 +- api/controllers/Products/GetController.php | 17 +- api/controllers/Users/GetController.php | 4 +- library/Constants/Relationships.php | 19 +- library/Constants/Resources.php | 15 -- library/Models/Companies.php | 4 +- library/Models/Products.php | 4 +- library/Providers/RouterProvider.php | 5 +- library/Transformers/CompaniesTransformer.php | 33 +++ library/Transformers/ProductsTransformer.php | 31 ++- tests/_support/ApiTester.php | 6 +- tests/api/Companies/AddCest.php | 7 +- tests/api/Companies/GetCest.php | 207 +++++++++++++++++- tests/api/IndividualTypes/GetCest.php | 18 +- tests/api/LoginCest.php | 4 +- tests/api/NotFoundCest.php | 2 - tests/api/ProductTypes/GetCest.php | 18 +- tests/api/Products/GetCest.php | 29 ++- tests/api/Users/GetCest.php | 34 +-- tests/cli/CheckHelpTaskCest.php | 2 +- tests/integration/library/ModelCest.php | 12 +- .../library/Models/CompaniesCest.php | 15 +- .../library/Models/ProductsCest.php | 1 - .../integration/library/Traits/QueryCest.php | 7 +- .../Transformers/BaseTransformerCest.php | 2 +- .../Transformers/ProductsTransformerCest.php | 42 ++-- .../Validation/CompaniesValidatorCest.php | 4 +- tests/unit/BootstrapCest.php | 2 +- tests/unit/cli/BaseCest.php | 6 +- tests/unit/cli/BootstrapCest.php | 2 +- tests/unit/cli/ClearCacheCest.php | 10 +- tests/unit/config/ConfigCest.php | 2 +- tests/unit/config/FunctionsCest.php | 2 +- tests/unit/config/ProvidersCest.php | 4 +- tests/unit/library/BootstrapCest.php | 2 +- tests/unit/library/Constants/FlagsCest.php | 2 +- .../unit/library/Constants/JWTClaimsCest.php | 2 +- .../library/Constants/RelationshipsCest.php | 9 +- .../unit/library/Constants/ResourcesCest.php | 19 -- tests/unit/library/ErrorHandlerCest.php | 14 +- tests/unit/library/Http/ResponseCest.php | 44 ++-- tests/unit/library/Providers/ConfigCest.php | 3 +- tests/unit/library/Providers/DatabaseCest.php | 4 +- .../library/Providers/ErrorHandlerCest.php | 12 +- .../library/Providers/EventsManagerCest.php | 2 +- tests/unit/library/Providers/LoggerCest.php | 4 +- tests/unit/library/Providers/ResponseCest.php | 2 +- tests/unit/library/Providers/RouterCest.php | 40 ++-- 51 files changed, 523 insertions(+), 261 deletions(-) delete mode 100644 library/Constants/Resources.php create mode 100644 library/Transformers/CompaniesTransformer.php delete mode 100644 tests/unit/library/Constants/ResourcesCest.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 28aff507..e2edee65 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -4,23 +4,16 @@ namespace Niden\Api\Controllers; -use function explode; -use function in_array; -use Niden\Exception\ModelException; -use Niden\Http\Request; use Niden\Http\Response; -use Niden\Models\Users; use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; -use Niden\Traits\TokenTrait; -use Niden\Transformers\BaseTransformer; use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; -use Phalcon\Mvc\Model\ResultsetInterface; +use function explode; +use function in_array; use function strtolower; -use function trim; /** * Class BaseController @@ -37,15 +30,15 @@ class BaseController extends Controller use ResponseTrait; /** @var string */ - protected $model = ''; + protected $model = ''; /** @var array */ protected $relationships = []; /** @var string */ - protected $resource = ''; + protected $resource = ''; /** @var string */ - protected $transformer = ''; + protected $transformer = ''; /** @var string */ - protected $orderBy = 'name'; + protected $orderBy = 'name'; /** * Get the company/companies @@ -72,7 +65,7 @@ public function callAction($id = 0, $relationships = '') return $this->send404(); } - $results[] = strtolower($relationship); + $related[] = strtolower($relationship); } } } @@ -83,7 +76,7 @@ public function callAction($id = 0, $relationships = '') /** * Checks the passed id parameter and returns the relevant array back * - * @param int $recordId + * @param int $recordId * * @return array */ diff --git a/api/controllers/Companies/GetController.php b/api/controllers/Companies/GetController.php index eb9f2335..050eb7fc 100644 --- a/api/controllers/Companies/GetController.php +++ b/api/controllers/Companies/GetController.php @@ -5,9 +5,9 @@ namespace Niden\Api\Controllers\Companies; use Niden\Api\Controllers\BaseController; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\Companies; -use Niden\Transformers\BaseTransformer; +use Niden\Transformers\CompaniesTransformer; /** * Class GetController @@ -21,13 +21,13 @@ class GetController extends BaseController /** @var array */ protected $relationships = [ - Resources::INDIVIDUALS, - Resources::PRODUCTS, + Relationships::INDIVIDUALS, + Relationships::PRODUCTS, ]; /** @var string */ - protected $resource = Resources::COMPANIES; + protected $resource = Relationships::COMPANIES; /** @var string */ - protected $transformer = BaseTransformer::class; + protected $transformer = CompaniesTransformer::class; } diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index f87a93df..4c45e591 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -5,7 +5,7 @@ namespace Niden\Api\Controllers\IndividualTypes; use Niden\Api\Controllers\BaseController; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\IndividualTypes; use Niden\Transformers\BaseTransformer; @@ -19,7 +19,7 @@ class GetController extends BaseController /** @var string */ protected $model = IndividualTypes::class; /** @var string */ - protected $resource = Resources::INDIVIDUAL_TYPES; + protected $resource = Relationships::INDIVIDUAL_TYPES; /** @var string */ protected $transformer = BaseTransformer::class; } diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index 07291505..ad9bd5b3 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -5,22 +5,28 @@ namespace Niden\Api\Controllers\ProductTypes; use Niden\Api\Controllers\BaseController; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\ProductTypes; -use Niden\Transformers\BaseTransformer; /** * Class GetController * - * @package Niden\Api\Controllers\IndividualTypes + * @package Niden\Api\Controllers\ProductTypes */ class GetController extends BaseController { /** @var string */ protected $model = ProductTypes::class; + + /** @var array */ + protected $relationships = [ + Relationships::PRODUCTS, + ]; + /** @var string */ - protected $resource = Resources::PRODUCT_TYPES; + protected $resource = Relationships::PRODUCT_TYPES; + /** @var string */ - protected $transformer = BaseTransformer::class; + protected $transformer = ProductTypes::class; } diff --git a/api/controllers/Products/GetController.php b/api/controllers/Products/GetController.php index 50ae35f9..cf778c29 100644 --- a/api/controllers/Products/GetController.php +++ b/api/controllers/Products/GetController.php @@ -5,21 +5,28 @@ namespace Niden\Api\Controllers\Products; use Niden\Api\Controllers\BaseController; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\Products; -use Niden\Transformers\BaseTransformer; +use Niden\Transformers\ProductsTransformer; /** * Class GetController * - * @package Niden\Api\Controllers\Companies + * @package Niden\Api\Controllers\Products */ class GetController extends BaseController { /** @var string */ protected $model = Products::class; + + /** @var array */ + protected $relationships = [ + Relationships::COMPANIES, + Relationships::PRODUCT_TYPES, + ]; + /** @var string */ - protected $resource = Resources::PRODUCTS; + protected $resource = Relationships::PRODUCTS; /** @var string */ - protected $transformer = BaseTransformer::class; + protected $transformer = ProductsTransformer::class; } diff --git a/api/controllers/Users/GetController.php b/api/controllers/Users/GetController.php index ed6d859f..409fda58 100644 --- a/api/controllers/Users/GetController.php +++ b/api/controllers/Users/GetController.php @@ -5,7 +5,7 @@ namespace Niden\Api\Controllers\Users; use Niden\Api\Controllers\BaseController; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\Users; use Niden\Transformers\BaseTransformer; @@ -19,7 +19,7 @@ class GetController extends BaseController /** @var string */ protected $model = Users::class; /** @var string */ - protected $resource = Resources::USERS; + protected $resource = Relationships::USERS; /** @var string */ protected $transformer = BaseTransformer::class; /** @var string */ diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php index 305a35dc..a3e88df0 100644 --- a/library/Constants/Relationships.php +++ b/library/Constants/Relationships.php @@ -6,12 +6,15 @@ class Relationships { - const COMPANY = 'company'; - const COMPANIES = 'companies'; - const INDIVIDUAL = 'individual'; - const INDIVIDUAL_TYPE = 'individualType'; - const INDIVIDUALS = 'individuals'; - const PRODUCT = 'product'; - const PRODUCT_TYPE = 'productType'; - const PRODUCTS = 'products'; + const COMPANY = 'company'; + const COMPANIES = 'companies'; + const INDIVIDUAL = 'individual'; + const INDIVIDUAL_TYPE = 'individual-type'; + const INDIVIDUAL_TYPES = 'individual-types'; + const INDIVIDUALS = 'individuals'; + const PRODUCT = 'product'; + const PRODUCT_TYPE = 'product-type'; + const PRODUCT_TYPES = 'product-types'; + const PRODUCTS = 'products'; + const USERS = 'users'; } diff --git a/library/Constants/Resources.php b/library/Constants/Resources.php deleted file mode 100644 index 32f5b7c3..00000000 --- a/library/Constants/Resources.php +++ /dev/null @@ -1,15 +0,0 @@ -hasManyToMany( 'id', CompaniesXProducts::class, - 'cxp_com_id', - 'cxp_prd_id', + 'companyId', + 'productId', Products::class, 'id', [ diff --git a/library/Models/Products.php b/library/Models/Products.php index a7ad9368..d9131d78 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -23,8 +23,8 @@ public function initialize() $this->hasManyToMany( 'id', Products::class, - 'cxp_prd_id', - 'cxp_com_id', + 'productId', + 'companyId', CompaniesXProducts::class, 'id', [ diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index 4552e2d7..db6d48db 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -112,13 +112,16 @@ private function getRoutes(): array [CompaniesAddController::class, '/companies', 'post', '/'], [CompaniesGetController::class, '/companies', 'get', '/'], [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], - [CompaniesGetController::class, '/companies', 'get', '/relationships/{relationships:[a-zA-Z,.}'], + [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], [IndividualTypesGetController::class, '/individual-types', 'get', '/'], [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}'], + [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], [ProductsGetController::class, '/products', 'get', '/'], [ProductsGetController::class, '/products', 'get', '/{productId:[0-9]+}'], + [ProductsGetController::class, '/products', 'get', '/{productId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], [ProductTypesGetController::class, '/product-types', 'get', '/'], [ProductTypesGetController::class, '/product-types', 'get', '/{typeId:[0-9]+}'], + [ProductTypesGetController::class, '/product-types', 'get', '/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], [UsersGetController::class, '/users', 'get', '/'], [UsersGetController::class, '/users', 'get', '/{userId:[0-9]+}'], ]; diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php new file mode 100644 index 00000000..fc51eefc --- /dev/null +++ b/library/Transformers/CompaniesTransformer.php @@ -0,0 +1,33 @@ +getRelated(Relationships::PRODUCTS); + + return $this->collection($products, new ProductsTransformer(), Relationships::PRODUCTS); + } +} diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php index 1140aa04..7b392250 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php @@ -4,8 +4,10 @@ namespace Niden\Transformers; +use League\Fractal\Resource\Collection; +use League\Fractal\Resource\Item; use Niden\Constants\Relationships; -use Niden\Constants\Resources; +use Niden\Models\Companies; use Niden\Models\Products; use Niden\Models\ProductTypes; @@ -15,14 +17,37 @@ class ProductsTransformer extends BaseTransformer { protected $availableIncludes = [ - Resources::PRODUCT_TYPES, + Relationships::COMPANIES, + Relationships::PRODUCT_TYPES, ]; + /** + * Includes the companies + * + * @param Products $product + * + * @return Collection + */ + public function includeCompanies(Products $product) + { + /** @var Companies $companies */ + $companies = $product->getRelated(Relationships::COMPANIES); + + return $this->collection($companies, new CompaniesTransformer(), Relationships::PRODUCT_TYPES); + } + + /** + * Includes the product types + * + * @param Products $product + * + * @return Item + */ public function includeProductTypes(Products $product) { /** @var ProductTypes $productType */ $productType = $product->getRelated(Relationships::PRODUCT_TYPE); - return $this->item($productType, new BaseTransformer(), Resources::PRODUCT_TYPES); + return $this->item($productType, new BaseTransformer(), Relationships::PRODUCT_TYPES); } } diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index 2dde6da8..8a168ecc 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -95,7 +95,7 @@ public function seeErrorJsonResponse(string $message) ); } - public function seeSuccessJsonResponse(array $data = []) + public function seeSuccessJsonResponse(array $data = [], array $extra = []) { $contents = [ 'jsonapi' => [ @@ -104,6 +104,10 @@ public function seeSuccessJsonResponse(array $data = []) 'data' => $data, ]; + if (true !== empty($extra)) { + $contents = $contents + $extra; + } + $this->seeResponseContainsJson($contents); } diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index 519da4a7..d2dde284 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -3,9 +3,8 @@ namespace Niden\Tests\api\Companies; use ApiTester; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\Companies; -use Niden\Models\Users; use Page\Data; use function uniqid; @@ -42,7 +41,7 @@ public function addNewCompany(ApiTester $I) [ [ 'id' => $company->get('id'), - 'type' => Resources::COMPANIES, + 'type' => Relationships::COMPANIES, 'attributes' => [ 'name' => $company->get('name'), 'address' => $company->get('address'), @@ -64,7 +63,7 @@ public function addNewCompanyWithExistingName(ApiTester $I) $I->haveRecordWithFields( Companies::class, [ - 'name' => $name + 'name' => $name, ] ); diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 2b19a3b7..74aed64b 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -3,9 +3,12 @@ namespace Niden\Tests\api\Companies; use ApiTester; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; +use function Niden\Core\envValue; use Niden\Models\Companies; -use Niden\Models\Users; +use Niden\Models\CompaniesXProducts; +use Niden\Models\Products; +use Niden\Models\ProductTypes; use Page\Data; use function uniqid; @@ -33,7 +36,7 @@ public function getCompany(ApiTester $I) [ [ 'id' => $comOne->get('id'), - 'type' => Resources::COMPANIES, + 'type' => Relationships::COMPANIES, 'attributes' => [ 'name' => $comOne->get('name'), 'address' => $comOne->get('address'), @@ -87,7 +90,7 @@ public function getCompanies(ApiTester $I) [ [ 'id' => $comOne->get('id'), - 'type' => Resources::COMPANIES, + 'type' => Relationships::COMPANIES, 'attributes' => [ 'name' => $comOne->get('name'), 'address' => $comOne->get('address'), @@ -97,7 +100,7 @@ public function getCompanies(ApiTester $I) ], [ 'id' => $comTwo->get('id'), - 'type' => Resources::COMPANIES, + 'type' => Relationships::COMPANIES, 'attributes' => [ 'name' => $comTwo->get('name'), 'address' => $comTwo->get('address'), @@ -109,6 +112,200 @@ public function getCompanies(ApiTester $I) ); } + public function getCompaniesWithProducts(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => uniqid('prt-a-'), + 'description' => uniqid(), + ] + ); + + /** @var Products $productOne */ + $productOne = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + /** @var Products $productTwo */ + $productTwo = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-b-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productOne->get('id'), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productTwo->get('id'), + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/' . Relationships::PRODUCTS); + $I->deleteHeader('Authorization'); + + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + [ + [ + 'id' => $comOne->get('id'), + 'type' => Relationships::COMPANIES, + 'attributes' => [ + 'name' => $comOne->get('name'), + 'address' => $comOne->get('address'), + 'city' => $comOne->get('city'), + 'phone' => $comOne->get('phone'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::COMPANIES, + $comOne->get('id') + ), + ], + 'relationships' => [ + Relationships::PRODUCTS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL'), + Relationships::COMPANIES, + $comOne->get('id'), + Relationships::PRODUCTS + + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL'), + Relationships::COMPANIES, + $comOne->get('id'), + Relationships::PRODUCTS + ), + ], + 'data' => [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productOne->get('id'), + ], + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productTwo->get('id'), + ], + ] + ] + ] + ] + ] + ); + } + + public function getCompaniesWithUnknownRelationship(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => uniqid('prt-a-'), + 'description' => uniqid(), + ] + ); + + /** @var Products $productOne */ + $productOne = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + /** @var Products $productTwo */ + $productTwo = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-b-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productOne->get('id'), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productTwo->get('id'), + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/unknown'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + public function getCompaniesNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index f001c5da..6710f367 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -3,9 +3,8 @@ namespace Niden\Tests\api\IndividualTypes; use ApiTester; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\IndividualTypes; -use Niden\Models\Users; use Page\Data; use function uniqid; @@ -36,7 +35,7 @@ public function getIndividualTypes(ApiTester $I) [ [ 'id' => $typeOne->get('id'), - 'type' => Resources::INDIVIDUAL_TYPES, + 'type' => Relationships::INDIVIDUAL_TYPES, 'attributes' => [ 'name' => $typeOne->get('name'), 'description' => $typeOne->get('description'), @@ -44,7 +43,7 @@ public function getIndividualTypes(ApiTester $I) ], [ 'id' => $typeTwo->get('id'), - 'type' => Resources::INDIVIDUAL_TYPES, + 'type' => Relationships::INDIVIDUAL_TYPES, 'attributes' => [ 'name' => $typeTwo->get('name'), 'description' => $typeTwo->get('description'), @@ -54,6 +53,17 @@ public function getIndividualTypes(ApiTester $I) ); } + public function getUnknownIndividualTypes(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$individualTypesUrl . '/1'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + public function getIndividualTypesNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/LoginCest.php b/tests/api/LoginCest.php index 792684e7..43652868 100644 --- a/tests/api/LoginCest.php +++ b/tests/api/LoginCest.php @@ -3,11 +3,9 @@ namespace Niden\Tests\api; use ApiTester; -use function json_decode; -use Niden\Exception\Exception; -use Niden\Http\Response; use Niden\Models\Users; use Page\Data; +use function json_decode; class LoginCest { diff --git a/tests/api/NotFoundCest.php b/tests/api/NotFoundCest.php index 9696808f..3b671fd4 100644 --- a/tests/api/NotFoundCest.php +++ b/tests/api/NotFoundCest.php @@ -3,8 +3,6 @@ namespace Niden\Tests\api; use ApiTester; -use Niden\Exception\Exception; -use Niden\Http\Response; use Page\Data; class NotFoundCest diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index 130cf3e9..453a3355 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -3,9 +3,8 @@ namespace Niden\Tests\api\ProductTypes; use ApiTester; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\ProductTypes; -use Niden\Models\Users; use Page\Data; use function uniqid; @@ -36,7 +35,7 @@ public function getProductTypes(ApiTester $I) [ [ 'id' => $typeOne->get('id'), - 'type' => Resources::PRODUCT_TYPES, + 'type' => Relationships::PRODUCT_TYPES, 'attributes' => [ 'name' => $typeOne->get('name'), 'description' => $typeOne->get('description'), @@ -44,7 +43,7 @@ public function getProductTypes(ApiTester $I) ], [ 'id' => $typeTwo->get('id'), - 'type' => Resources::PRODUCT_TYPES, + 'type' => Relationships::PRODUCT_TYPES, 'attributes' => [ 'name' => $typeTwo->get('name'), 'description' => $typeTwo->get('description'), @@ -54,6 +53,17 @@ public function getProductTypes(ApiTester $I) ); } + public function getUnknownProductTypes(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productTypesUrl . '/1'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + public function getProductTypesNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index c1beb57d..93923a32 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -3,13 +3,11 @@ namespace Niden\Tests\api\Products; use ApiTester; -use Niden\Constants\Resources; -use function Niden\Core\envValue; -use Niden\Models\Companies; +use Niden\Constants\Relationships; use Niden\Models\Products; use Niden\Models\ProductTypes; -use Niden\Models\Users; use Page\Data; +use function Niden\Core\envValue; use function uniqid; class GetCest @@ -48,7 +46,7 @@ public function getProduct(ApiTester $I) [ [ 'id' => $product->get('id'), - 'type' => Resources::PRODUCTS, + 'type' => Relationships::PRODUCTS, 'attributes' => [ 'name' => $product->get('name'), 'typeId' => $productType->get('id'), @@ -62,12 +60,23 @@ public function getProduct(ApiTester $I) envValue('APP_URL', 'localhost'), $product->get('id') ), - ] + ], ], ] ); } + public function getUnknownProduct(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productsUrl . '/1'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + public function getProducts(ApiTester $I) { $I->addApiUserRecord(); @@ -114,7 +123,7 @@ public function getProducts(ApiTester $I) [ [ 'id' => $productOne->get('id'), - 'type' => Resources::PRODUCTS, + 'type' => Relationships::PRODUCTS, 'attributes' => [ 'name' => $productOne->get('name'), 'typeId' => $productType->get('id'), @@ -128,11 +137,11 @@ public function getProducts(ApiTester $I) envValue('APP_URL', 'localhost'), $productOne->get('id') ), - ] + ], ], [ 'id' => $productTwo->get('id'), - 'type' => Resources::PRODUCTS, + 'type' => Relationships::PRODUCTS, 'attributes' => [ 'name' => $productTwo->get('name'), 'typeId' => $productType->get('id'), @@ -146,7 +155,7 @@ public function getProducts(ApiTester $I) envValue('APP_URL', 'localhost'), $productTwo->get('id') ), - ] + ], ], ] ); diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 636f4a97..0a2a182c 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -5,7 +5,7 @@ use ApiTester; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Signer\Hmac\Sha512; -use Niden\Constants\Resources; +use Niden\Constants\Relationships; use Niden\Models\Users; use Niden\Traits\TokenTrait; use Page\Data; @@ -30,9 +30,9 @@ public function loginKnownUserGetUnknownUser(ApiTester $I) $I->seeResponseIsSuccessful(); $response = $I->grabResponse(); - $response = json_decode($response, true); - $data = $response['data']; - $token = $data['token']; + $response = json_decode($response, true); + $data = $response['data']; + $token = $data['token']; $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$usersUrl . '/1'); @@ -49,7 +49,7 @@ public function loginKnownUserIncorrectSignature(ApiTester $I) $signer = new Sha512(); $builder = new Builder(); - $token = $builder + $token = $builder ->setIssuer('https://niden.net') ->setAudience($this->getTokenAudience()) ->setId('110011', true) @@ -57,7 +57,8 @@ public function loginKnownUserIncorrectSignature(ApiTester $I) ->setNotBefore(time() - 3590) ->setExpiration(time() - 3000) ->sign($signer, '123456') - ->getToken(); + ->getToken() + ; $wrongToken = $token->__toString(); @@ -77,7 +78,7 @@ public function loginKnownUserExpiredToken(ApiTester $I) $signer = new Sha512(); $builder = new Builder(); - $token = $builder + $token = $builder ->setIssuer('https://niden.net') ->setAudience($this->getTokenAudience()) ->setId('110011', true) @@ -85,7 +86,8 @@ public function loginKnownUserExpiredToken(ApiTester $I) ->setNotBefore(time() - 3590) ->setExpiration(time() - 3000) ->sign($signer, '12345') - ->getToken(); + ->getToken() + ; $expiredToken = $token->__toString(); @@ -105,7 +107,7 @@ public function loginKnownUserInvalidToken(ApiTester $I) $signer = new Sha512(); $builder = new Builder(); - $token = $builder + $token = $builder ->setIssuer('https://niden.net') ->setAudience($this->getTokenAudience()) ->setId('110011', true) @@ -113,7 +115,8 @@ public function loginKnownUserInvalidToken(ApiTester $I) ->setNotBefore(time() - 3590) ->setExpiration(time() - 3000) ->sign($signer, '12345') - ->getToken(); + ->getToken() + ; $invalidToken = $token->__toString(); @@ -133,7 +136,7 @@ public function loginKnownUserInvalidUserInToken(ApiTester $I) $signer = new Sha512(); $builder = new Builder(); - $token = $builder + $token = $builder ->setIssuer('https://niden.com') ->setAudience($this->getTokenAudience()) ->setId('110011', true) @@ -141,7 +144,8 @@ public function loginKnownUserInvalidUserInToken(ApiTester $I) ->setNotBefore(time() - 3590) ->setExpiration(time() - 3000) ->sign($signer, '12345') - ->getToken(); + ->getToken() + ; $invalidToken = $token->__toString(); @@ -170,7 +174,7 @@ public function loginKnownUserValidToken(ApiTester $I) [ [ 'id' => $record->get('id'), - 'type' => Resources::USERS, + 'type' => Relationships::USERS, 'attributes' => [ 'status' => $record->get('status'), 'username' => $record->get('username'), @@ -219,7 +223,7 @@ public function getManyUsers(ApiTester $I) [ [ 'id' => $userOne->get('id'), - 'type' => Resources::USERS, + 'type' => Relationships::USERS, 'attributes' => [ 'status' => $userOne->get('status'), 'username' => $userOne->get('username'), @@ -230,7 +234,7 @@ public function getManyUsers(ApiTester $I) ], [ 'id' => $userTwo->get('id'), - 'type' => Resources::USERS, + 'type' => Relationships::USERS, 'attributes' => [ 'status' => $userTwo->get('status'), 'username' => $userTwo->get('username'), diff --git a/tests/cli/CheckHelpTaskCest.php b/tests/cli/CheckHelpTaskCest.php index f1677905..f1f8350f 100644 --- a/tests/cli/CheckHelpTaskCest.php +++ b/tests/cli/CheckHelpTaskCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\cli; -use \CliTester; +use CliTester; class CheckHelpTaskCest { diff --git a/tests/integration/library/ModelCest.php b/tests/integration/library/ModelCest.php index 14b51545..fbe7b9b8 100644 --- a/tests/integration/library/ModelCest.php +++ b/tests/integration/library/ModelCest.php @@ -2,13 +2,13 @@ namespace Niden\Tests\integration\library; -use function Niden\Core\appPath; use Codeception\Stub; -use \IntegrationTester; +use IntegrationTester; use Monolog\Logger; -use Niden\Models\Users; use Niden\Exception\ModelException; +use Niden\Models\Users; use Phalcon\Mvc\Model\Message; +use function Niden\Core\appPath; /** * Class ModelCest @@ -167,7 +167,8 @@ public function checkModelMessages(IntegrationTester $I) $result = $user ->set('username', 'test') - ->save(); + ->save() + ; $I->assertFalse($result); $I->assertEquals('error 1
error 2
', $user->getModelMessages()); @@ -195,7 +196,8 @@ public function checkModelMessagesWithLogger(IntegrationTester $I) $fileName = appPath('storage/logs/api.log'); $result = $user ->set('username', 'test') - ->save(); + ->save() + ; $I->assertFalse($result); $I->assertEquals('error 1
error 2
', $user->getModelMessages()); diff --git a/tests/integration/library/Models/CompaniesCest.php b/tests/integration/library/Models/CompaniesCest.php index 1eb93477..5c2ebf81 100644 --- a/tests/integration/library/Models/CompaniesCest.php +++ b/tests/integration/library/Models/CompaniesCest.php @@ -6,7 +6,6 @@ use Niden\Constants\Relationships; use Niden\Models\Companies; use Niden\Models\Individuals; -use Niden\Models\Products; use Phalcon\Filter; class CompaniesCest @@ -51,18 +50,18 @@ public function validateUniqueName(IntegrationTester $I) { $companyOne = new Companies(); /** @var Companies $companyOne */ - $result = $companyOne - ->set('name', 'acme') - ->set('address', '123 Phalcon way') - ->set('city', 'World') - ->set('phone', '555-999-4444') - ->save() + $result = $companyOne + ->set('name', 'acme') + ->set('address', '123 Phalcon way') + ->set('city', 'World') + ->set('phone', '555-999-4444') + ->save() ; $I->assertNotEquals(false, $result); $companyTwo = new Companies(); /** @var Companies $companyTwo */ - $result = $companyTwo + $result = $companyTwo ->set('name', 'acme') ->set('address', '123 Phalcon way') ->set('city', 'World') diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index 269cb423..d0dac7a6 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -4,7 +4,6 @@ use IntegrationTester; use Niden\Constants\Relationships; -use Niden\Models\Companies; use Niden\Models\Products; use Niden\Models\ProductTypes; use Phalcon\Filter; diff --git a/tests/integration/library/Traits/QueryCest.php b/tests/integration/library/Traits/QueryCest.php index 12e3a1d2..36237f8f 100644 --- a/tests/integration/library/Traits/QueryCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -2,11 +2,11 @@ namespace Niden\Tests\integration\library\Traits; +use IntegrationTester; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Signer\Hmac\Sha512; -use \IntegrationTester; -use Niden\Models\Users; use Niden\Exception\ModelException; +use Niden\Models\Users; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; @@ -90,7 +90,8 @@ public function checkGetUserByWrongTokenReturnsFalse(IntegrationTester $I) ->setAudience($this->getTokenAudience()) ->setId('123456', true) ->sign($signer, '110011') - ->getToken(); + ->getToken() + ; $I->assertFalse($this->getUserByToken($token)); } diff --git a/tests/integration/library/Transformers/BaseTransformerCest.php b/tests/integration/library/Transformers/BaseTransformerCest.php index 7e99eef1..0d7093a0 100644 --- a/tests/integration/library/Transformers/BaseTransformerCest.php +++ b/tests/integration/library/Transformers/BaseTransformerCest.php @@ -27,7 +27,7 @@ public function checkTransformer(IntegrationTester $I) ); $transformer = new BaseTransformer(); - $expected = [ + $expected = [ 'id' => $company->get('id'), 'name' => $company->get('name'), 'address' => $company->get('address'), diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php index a62d4a53..f3f3e582 100644 --- a/tests/integration/library/Transformers/ProductsTransformerCest.php +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -6,13 +6,11 @@ use League\Fractal\Manager; use League\Fractal\Resource\Collection; use League\Fractal\Serializer\JsonApiSerializer; -use Niden\Constants\Resources; -use function Niden\Core\envValue; -use Niden\Models\Companies; +use Niden\Constants\Relationships; use Niden\Models\Products; use Niden\Models\ProductTypes; -use Niden\Transformers\BaseTransformer; use Niden\Transformers\ProductsTransformer; +use function Niden\Core\envValue; class ProductsTransformerCest { @@ -44,52 +42,52 @@ public function checkTransformer(IntegrationTester $I) ] ); - $url = envValue('APP_URL', 'http://localhost'); - $manager = new Manager(); + $url = envValue('APP_URL', 'http://localhost'); + $manager = new Manager(); $manager->setSerializer(new JsonApiSerializer($url)); - $manager->parseIncludes(Resources::PRODUCT_TYPES); - $resource = new Collection([$product], new ProductsTransformer(), Resources::PRODUCTS); + $manager->parseIncludes(Relationships::PRODUCT_TYPES); + $resource = new Collection([$product], new ProductsTransformer(), Relationships::PRODUCTS); $results = $manager->createData($resource)->toArray(); $expected = [ - 'data' => [ + 'data' => [ [ - 'type' => Resources::PRODUCTS, - 'id' => $product->get('id'), - 'attributes' => [ + 'type' => Relationships::PRODUCTS, + 'id' => $product->get('id'), + 'attributes' => [ 'typeId' => $productType->get('id'), 'name' => $product->get('name'), 'description' => $product->get('description'), 'quantity' => $product->get('quantity'), 'price' => $product->get('price'), ], - 'links' => [ + 'links' => [ 'self' => sprintf( '%s/%s/%s', $url, - Resources::PRODUCTS, + Relationships::PRODUCTS, $product->get('id') ), ], 'relationships' => [ - Resources::PRODUCT_TYPES => [ + Relationships::PRODUCT_TYPES => [ 'links' => [ 'self' => sprintf( '%s/%s/%s/relationships/%s', $url, - Resources::PRODUCTS, + Relationships::PRODUCTS, $product->get('id'), - Resources::PRODUCT_TYPES + Relationships::PRODUCT_TYPES ), 'related' => sprintf( '%s/%s/%s/%s', $url, - Resources::PRODUCTS, + Relationships::PRODUCTS, $product->get('id'), - Resources::PRODUCT_TYPES + Relationships::PRODUCT_TYPES ), ], 'data' => [ - 'type' => Resources::PRODUCT_TYPES, + 'type' => Relationships::PRODUCT_TYPES, 'id' => $productType->get('id'), ], ], @@ -98,7 +96,7 @@ public function checkTransformer(IntegrationTester $I) ], 'included' => [ [ - 'type' => Resources::PRODUCT_TYPES, + 'type' => Relationships::PRODUCT_TYPES, 'id' => $productType->get('id'), 'attributes' => [ 'name' => $productType->get('name'), @@ -108,7 +106,7 @@ public function checkTransformer(IntegrationTester $I) 'self' => sprintf( '%s/%s/%s', $url, - Resources::PRODUCT_TYPES, + Relationships::PRODUCT_TYPES, $productType->get('id') ), ], diff --git a/tests/integration/library/Validation/CompaniesValidatorCest.php b/tests/integration/library/Validation/CompaniesValidatorCest.php index c7db40b7..69e0e681 100644 --- a/tests/integration/library/Validation/CompaniesValidatorCest.php +++ b/tests/integration/library/Validation/CompaniesValidatorCest.php @@ -15,13 +15,13 @@ class CompaniesValidatorCest public function checkTransformer(IntegrationTester $I) { $validation = new CompaniesValidator(); - $_POST = [ + $_POST = [ 'name' => '', 'address' => '123 Phalcon way', 'city' => 'World', 'phone' => '555-999-4444', ]; - $messages = $validation->validate($_POST); + $messages = $validation->validate($_POST); $I->assertEquals(1, count($messages)); $I->assertEquals('The company name is required', $messages[0]->getMessage()); } diff --git a/tests/unit/BootstrapCest.php b/tests/unit/BootstrapCest.php index 2465c589..6a49c12e 100644 --- a/tests/unit/BootstrapCest.php +++ b/tests/unit/BootstrapCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\unit; -use \CliTester; +use CliTester; use function Niden\Core\appPath; class BootstrapCest diff --git a/tests/unit/cli/BaseCest.php b/tests/unit/cli/BaseCest.php index 961d5b12..03fbaccc 100755 --- a/tests/unit/cli/BaseCest.php +++ b/tests/unit/cli/BaseCest.php @@ -2,12 +2,12 @@ namespace Niden\Tests\unit\cli; +use Niden\Cli\Tasks\MainTask; +use Phalcon\Di\FactoryDefault\Cli; +use UnitTester; use function ob_end_clean; use function ob_get_contents; use function ob_start; -use Niden\Cli\Tasks\MainTask; -use Phalcon\Di\FactoryDefault\Cli; -use \UnitTester; class BaseCest { diff --git a/tests/unit/cli/BootstrapCest.php b/tests/unit/cli/BootstrapCest.php index bdbefd97..cdb6e691 100644 --- a/tests/unit/cli/BootstrapCest.php +++ b/tests/unit/cli/BootstrapCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\unit\cli; -use \CliTester; +use CliTester; use function Niden\Core\appPath; class BootstrapCest diff --git a/tests/unit/cli/ClearCacheCest.php b/tests/unit/cli/ClearCacheCest.php index 449348d6..311208e7 100755 --- a/tests/unit/cli/ClearCacheCest.php +++ b/tests/unit/cli/ClearCacheCest.php @@ -2,6 +2,10 @@ namespace Niden\Tests\unit\cli; +use FilesystemIterator; +use Niden\Cli\Tasks\ClearcacheTask; +use Phalcon\Di\FactoryDefault\Cli; +use UnitTester; use function fclose; use function iterator_count; use function Niden\Core\appPath; @@ -9,10 +13,6 @@ use function ob_get_contents; use function ob_start; use function uniqid; -use FilesystemIterator; -use Niden\Cli\Tasks\ClearcacheTask; -use Phalcon\Di\FactoryDefault\Cli; -use \UnitTester; class ClearCacheCest { @@ -50,7 +50,7 @@ public function checkClearCache(UnitTester $I) private function createFile() { - $name = appPath('/storage/cache/data/') . uniqid('tmp_') . '.cache'; + $name = appPath('/storage/cache/data/') . uniqid('tmp_') . '.cache'; $pointer = fopen($name, 'wb'); fwrite($pointer, 'test'); fclose($pointer); diff --git a/tests/unit/config/ConfigCest.php b/tests/unit/config/ConfigCest.php index d8ef5d85..eaaf279d 100755 --- a/tests/unit/config/ConfigCest.php +++ b/tests/unit/config/ConfigCest.php @@ -2,9 +2,9 @@ namespace Niden\Tests\unit\config; +use UnitTester; use function is_array; use function Niden\Core\appPath; -use \UnitTester; class ConfigCest { diff --git a/tests/unit/config/FunctionsCest.php b/tests/unit/config/FunctionsCest.php index 41f12b8f..8e30da4f 100755 --- a/tests/unit/config/FunctionsCest.php +++ b/tests/unit/config/FunctionsCest.php @@ -2,9 +2,9 @@ namespace Niden\Tests\unit\config; +use UnitTester; use function Niden\Core\appPath; use function Niden\Core\envValue; -use \UnitTester; class FunctionsCest { diff --git a/tests/unit/config/ProvidersCest.php b/tests/unit/config/ProvidersCest.php index e313ed26..bd9efded 100755 --- a/tests/unit/config/ProvidersCest.php +++ b/tests/unit/config/ProvidersCest.php @@ -2,7 +2,6 @@ namespace Niden\Tests\unit\config; -use function Niden\Core\appPath; use Niden\Providers\CliDispatcherProvider; use Niden\Providers\ConfigProvider; use Niden\Providers\DatabaseProvider; @@ -12,7 +11,8 @@ use Niden\Providers\RequestProvider; use Niden\Providers\ResponseProvider; use Niden\Providers\RouterProvider; -use \UnitTester; +use UnitTester; +use function Niden\Core\appPath; class ProvidersCest { diff --git a/tests/unit/library/BootstrapCest.php b/tests/unit/library/BootstrapCest.php index 4f578b5f..1b8eb283 100755 --- a/tests/unit/library/BootstrapCest.php +++ b/tests/unit/library/BootstrapCest.php @@ -6,7 +6,7 @@ use Niden\Http\Response; use Phalcon\Di\FactoryDefault; use Phalcon\Mvc\Micro; -use \UnitTester; +use UnitTester; class BootstrapCest { diff --git a/tests/unit/library/Constants/FlagsCest.php b/tests/unit/library/Constants/FlagsCest.php index 72e7fff5..3a68478f 100644 --- a/tests/unit/library/Constants/FlagsCest.php +++ b/tests/unit/library/Constants/FlagsCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\unit\library\Constants; -use \CliTester; +use CliTester; use Niden\Constants\Flags; class FlagsCest diff --git a/tests/unit/library/Constants/JWTClaimsCest.php b/tests/unit/library/Constants/JWTClaimsCest.php index 35d1df70..cb5c1c23 100644 --- a/tests/unit/library/Constants/JWTClaimsCest.php +++ b/tests/unit/library/Constants/JWTClaimsCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\unit\library\Constants; -use \CliTester; +use CliTester; use Niden\Constants\JWTClaims; class JWTClaimsCest diff --git a/tests/unit/library/Constants/RelationshipsCest.php b/tests/unit/library/Constants/RelationshipsCest.php index 42613d78..2b8ead2a 100644 --- a/tests/unit/library/Constants/RelationshipsCest.php +++ b/tests/unit/library/Constants/RelationshipsCest.php @@ -2,7 +2,7 @@ namespace Niden\Tests\unit\library\Constants; -use \CliTester; +use CliTester; use Niden\Constants\Relationships; class RelationshipsCest @@ -12,10 +12,13 @@ public function checkConstants(CliTester $I) $I->assertEquals('company', Relationships::COMPANY); $I->assertEquals('companies', Relationships::COMPANIES); $I->assertEquals('individual', Relationships::INDIVIDUAL); - $I->assertEquals('individualType', Relationships::INDIVIDUAL_TYPE); + $I->assertEquals('individual-type', Relationships::INDIVIDUAL_TYPE); + $I->assertEquals('individual-types', Relationships::INDIVIDUAL_TYPES); $I->assertEquals('individuals', Relationships::INDIVIDUALS); $I->assertEquals('product', Relationships::PRODUCT); - $I->assertEquals('productType', Relationships::PRODUCT_TYPE); + $I->assertEquals('product-type', Relationships::PRODUCT_TYPE); + $I->assertEquals('product-types', Relationships::PRODUCT_TYPES); $I->assertEquals('products', Relationships::PRODUCTS); + $I->assertEquals('users', Relationships::USERS); } } diff --git a/tests/unit/library/Constants/ResourcesCest.php b/tests/unit/library/Constants/ResourcesCest.php deleted file mode 100644 index 041f6cf8..00000000 --- a/tests/unit/library/Constants/ResourcesCest.php +++ /dev/null @@ -1,19 +0,0 @@ -assertEquals('companies', Resources::COMPANIES); - $I->assertEquals('individual-types', Resources::INDIVIDUAL_TYPES); - $I->assertEquals('individuals', Resources::INDIVIDUALS); - $I->assertEquals('product-types', Resources::PRODUCT_TYPES); - $I->assertEquals('products', Resources::PRODUCTS); - $I->assertEquals('users', Resources::USERS); - } -} diff --git a/tests/unit/library/ErrorHandlerCest.php b/tests/unit/library/ErrorHandlerCest.php index 6ecf9770..90431aac 100755 --- a/tests/unit/library/ErrorHandlerCest.php +++ b/tests/unit/library/ErrorHandlerCest.php @@ -2,16 +2,14 @@ namespace Niden\Tests\unit\library; -use const E_USER_NOTICE; use Niden\ErrorHandler; -use function Niden\Core\appPath; use Niden\Logger; use Niden\Providers\ConfigProvider; use Niden\Providers\LoggerProvider; use Phalcon\Config; use Phalcon\Di\FactoryDefault; -use function trigger_error; -use \UnitTester; +use UnitTester; +use function Niden\Core\appPath; class ErrorHandlerCest { @@ -20,11 +18,11 @@ public function logErrorOnError(UnitTester $I) $diContainer = new FactoryDefault(); $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new LoggerProvider(); + $provider = new LoggerProvider(); $provider->register($diContainer); /** @var Config $config */ - $config = $diContainer->getShared('config'); + $config = $diContainer->getShared('config'); /** @var Logger $logger */ $logger = $diContainer->getShared('logger'); $handler = new ErrorHandler($logger, $config); @@ -41,11 +39,11 @@ public function logErrorOnShutdown(UnitTester $I) $diContainer = new FactoryDefault(); $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new LoggerProvider(); + $provider = new LoggerProvider(); $provider->register($diContainer); /** @var Config $config */ - $config = $diContainer->getShared('config'); + $config = $diContainer->getShared('config'); /** @var Logger $logger */ $logger = $diContainer->getShared('logger'); $handler = new ErrorHandler($logger, $config); diff --git a/tests/unit/library/Http/ResponseCest.php b/tests/unit/library/Http/ResponseCest.php index 838f8fe8..73c21738 100755 --- a/tests/unit/library/Http/ResponseCest.php +++ b/tests/unit/library/Http/ResponseCest.php @@ -2,13 +2,13 @@ namespace Niden\Tests\unit\library\Http; -use function is_string; -use function json_decode; use Niden\Http\Response; use Phalcon\Mvc\Model\Message as ModelMessage; use Phalcon\Validation\Message as ValidationMessage; use Phalcon\Validation\Message\Group as ValidationGroup; -use \UnitTester; +use UnitTester; +use function is_string; +use function json_decode; class ResponseCest { @@ -28,6 +28,24 @@ public function checkResponseWithStringPayload(UnitTester $I) $I->assertEquals(['test'], $payload['data']); } + private function checkPayload(UnitTester $I, Response $response, bool $error = false) + : array { + $contents = $response->getContent(); + $I->assertTrue(is_string($contents)); + + $payload = json_decode($contents, true); + $I->assertEquals(3, count($payload)); + $I->assertTrue(isset($payload['jsonapi'])); + if (true === $error) { + $I->assertTrue(isset($payload['errors'])); + } else { + $I->assertTrue(isset($payload['data'])); + } + $I->assertTrue(isset($payload['meta'])); + + return $payload; + } + public function checkResponseWithArrayPayload(UnitTester $I) { $response = new Response(); @@ -74,7 +92,7 @@ public function checkResponseWithModelErrors(UnitTester $I) public function checkResponseWithValidationErrors(UnitTester $I) { - $group = new ValidationGroup(); + $group = new ValidationGroup(); $message = new ValidationMessage('hello'); $group->appendMessage($message); $message = new ValidationMessage('goodbye'); @@ -91,22 +109,4 @@ public function checkResponseWithValidationErrors(UnitTester $I) $I->assertEquals('hello', $payload['errors'][0]); $I->assertEquals('goodbye', $payload['errors'][1]); } - - private function checkPayload(UnitTester $I, Response $response, bool $error = false): array - { - $contents = $response->getContent(); - $I->assertTrue(is_string($contents)); - - $payload = json_decode($contents, true); - $I->assertEquals(3, count($payload)); - $I->assertTrue(isset($payload['jsonapi'])); - if (true === $error) { - $I->assertTrue(isset($payload['errors'])); - } else { - $I->assertTrue(isset($payload['data'])); - } - $I->assertTrue(isset($payload['meta'])); - - return $payload; - } } diff --git a/tests/unit/library/Providers/ConfigCest.php b/tests/unit/library/Providers/ConfigCest.php index ae925030..db21ef5a 100644 --- a/tests/unit/library/Providers/ConfigCest.php +++ b/tests/unit/library/Providers/ConfigCest.php @@ -5,8 +5,7 @@ use Niden\Providers\ConfigProvider; use Phalcon\Config; use Phalcon\Di\FactoryDefault; - -use \UnitTester; +use UnitTester; class ConfigCest { diff --git a/tests/unit/library/Providers/DatabaseCest.php b/tests/unit/library/Providers/DatabaseCest.php index 7e79fd62..9459e1d2 100644 --- a/tests/unit/library/Providers/DatabaseCest.php +++ b/tests/unit/library/Providers/DatabaseCest.php @@ -6,7 +6,7 @@ use Niden\Providers\DatabaseProvider; use Phalcon\Db\Adapter\Pdo\Mysql; use Phalcon\Di\FactoryDefault; -use \UnitTester; +use UnitTester; class DatabaseCest { @@ -18,7 +18,7 @@ public function checkRegistration(UnitTester $I) $diContainer = new FactoryDefault(); $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new DatabaseProvider(); + $provider = new DatabaseProvider(); $provider->register($diContainer); $I->assertTrue($diContainer->has('db')); diff --git a/tests/unit/library/Providers/ErrorHandlerCest.php b/tests/unit/library/Providers/ErrorHandlerCest.php index ebd6763e..767560b1 100644 --- a/tests/unit/library/Providers/ErrorHandlerCest.php +++ b/tests/unit/library/Providers/ErrorHandlerCest.php @@ -2,16 +2,12 @@ namespace Niden\Tests\unit\library\Providers; -use function date_default_timezone_get; -use const E_NOTICE; -use const E_USER_NOTICE; -use function Niden\Core\appPath; use Niden\Providers\ConfigProvider; use Niden\Providers\ErrorHandlerProvider; use Niden\Providers\LoggerProvider; use Phalcon\Di\FactoryDefault; -use function trigger_error; -use \UnitTester; +use UnitTester; +use function date_default_timezone_get; class ErrorHandlerCest { @@ -23,9 +19,9 @@ public function checkRegistration(UnitTester $I) $diContainer = new FactoryDefault(); $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new LoggerProvider(); + $provider = new LoggerProvider(); $provider->register($diContainer); - $provider = new ErrorHandlerProvider(); + $provider = new ErrorHandlerProvider(); $provider->register($diContainer); $config = $diContainer->getShared('config'); diff --git a/tests/unit/library/Providers/EventsManagerCest.php b/tests/unit/library/Providers/EventsManagerCest.php index 8340eabf..0fe020b5 100644 --- a/tests/unit/library/Providers/EventsManagerCest.php +++ b/tests/unit/library/Providers/EventsManagerCest.php @@ -5,7 +5,7 @@ use Niden\Providers\EventsManagerProvider; use Phalcon\Di\FactoryDefault; use Phalcon\Events\Manager; -use \UnitTester; +use UnitTester; class EventsManagerCest { diff --git a/tests/unit/library/Providers/LoggerCest.php b/tests/unit/library/Providers/LoggerCest.php index 141939ac..1b65a691 100644 --- a/tests/unit/library/Providers/LoggerCest.php +++ b/tests/unit/library/Providers/LoggerCest.php @@ -6,7 +6,7 @@ use Niden\Providers\ConfigProvider; use Niden\Providers\LoggerProvider; use Phalcon\Di\FactoryDefault; -use \UnitTester; +use UnitTester; class LoggerCest { @@ -18,7 +18,7 @@ public function checkRegistration(UnitTester $I) $diContainer = new FactoryDefault(); $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new LoggerProvider(); + $provider = new LoggerProvider(); $provider->register($diContainer); $I->assertTrue($diContainer->has('logger')); diff --git a/tests/unit/library/Providers/ResponseCest.php b/tests/unit/library/Providers/ResponseCest.php index e5ab2257..d56506ae 100644 --- a/tests/unit/library/Providers/ResponseCest.php +++ b/tests/unit/library/Providers/ResponseCest.php @@ -5,7 +5,7 @@ use Niden\Http\Response; use Niden\Providers\ResponseProvider; use Phalcon\Di\FactoryDefault; -use \UnitTester; +use UnitTester; class ResponseCest { diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index a99d0f78..8fd530c0 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -4,12 +4,11 @@ use Niden\Logger; use Niden\Providers\ConfigProvider; -use Niden\Providers\LoggerProvider; use Niden\Providers\RouterProvider; use Phalcon\Di\FactoryDefault; use Phalcon\Mvc\Micro; use Phalcon\Mvc\RouterInterface; -use \UnitTester; +use UnitTester; class RouterCest { @@ -21,34 +20,37 @@ public function checkRegistration(UnitTester $I) $diContainer = new FactoryDefault(); $application = new Micro($diContainer); $diContainer->setShared('application', $application); - $provider = new ConfigProvider(); + $provider = new ConfigProvider(); $provider->register($diContainer); - $provider = new RouterProvider(); + $provider = new RouterProvider(); $provider->register($diContainer); /** @var RouterInterface $router */ - $router = $application->getRouter(); - $routes = $router->getRoutes(); + $router = $application->getRouter(); + $routes = $router->getRoutes(); $expected = [ ['POST', '/login'], ['POST', '/companies'], - ['GET', '/companies'], - ['GET', '/companies/{companyId:[0-9]+}'], - ['GET', '/companies/relationships/{relationships:[a-zA-Z,.}'], - ['GET', '/individual-types'], - ['GET', '/individual-types/{typeId:[0-9]+}'], - ['GET', '/products'], - ['GET', '/products/{productId:[0-9]+}'], - ['GET', '/product-types'], - ['GET', '/product-types/{typeId:[0-9]+}'], - ['GET', '/users'], - ['GET', '/users/{userId:[0-9]+}'], + ['GET', '/companies'], + ['GET', '/companies/{companyId:[0-9]+}'], + ['GET', '/companies/{companyId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individual-types'], + ['GET', '/individual-types/{typeId:[0-9]+}'], + ['GET', '/individual-types/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/products'], + ['GET', '/products/{productId:[0-9]+}'], + ['GET', '/products/{productId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/product-types'], + ['GET', '/product-types/{typeId:[0-9]+}'], + ['GET', '/product-types/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/users'], + ['GET', '/users/{userId:[0-9]+}'], ]; - $I->assertEquals(13, count($routes)); + $I->assertEquals(16, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); } - } + } } From 3ff0a7f0e09864c417bb843ddb343e93ee14d572 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Tue, 24 Jul 2018 18:51:34 -0400 Subject: [PATCH 48/70] Fixing scrutinizer issue --- api/controllers/BaseController.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index e2edee65..3bef6a06 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -31,12 +31,16 @@ class BaseController extends Controller /** @var string */ protected $model = ''; + /** @var array */ protected $relationships = []; + /** @var string */ protected $resource = ''; + /** @var string */ protected $transformer = ''; + /** @var string */ protected $orderBy = 'name'; @@ -95,10 +99,14 @@ private function checkIdParameter($recordId = 0): array } /** - * Sends a 404 back + * Sets the response with a 404 and returns an empty string back + * + * @return string */ - private function send404() + private function send404(): string { $this->response->setPayloadError('Not Found')->setStatusCode(404); + + return ''; } } From 57b22ada7a10719d096f72b91d30cc7b02c89f48 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 26 Jul 2018 19:04:45 -0400 Subject: [PATCH 49/70] Added product types transformer; Reorganized hash calculation; payloads sent back --- api/controllers/BaseController.php | 8 +- api/controllers/LoginController.php | 5 +- .../ProductTypes/GetController.php | 3 +- library/Http/Response.php | 7 +- library/Providers/ResponseProvider.php | 5 +- library/Traits/FractalTrait.php | 2 +- library/Traits/ResponseTrait.php | 23 +++- library/Transformers/CompaniesTransformer.php | 1 + library/Transformers/PayloadTransformer.php | 19 ++-- .../Transformers/ProductTypesTransformer.php | 34 ++++++ tests/_support/ApiTester.php | 8 +- tests/api/Products/GetCest.php | 102 ++++++++++++++++++ tests/unit/library/Http/ResponseCest.php | 6 +- 13 files changed, 195 insertions(+), 28 deletions(-) create mode 100644 library/Transformers/ProductTypesTransformer.php diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 3bef6a06..212cc1c3 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -99,14 +99,14 @@ private function checkIdParameter($recordId = 0): array } /** - * Sets the response with a 404 and returns an empty string back + * Sets the response with a 404 and returns an empty array back * - * @return string + * @return array */ - private function send404(): string + private function send404(): array { $this->response->setPayloadError('Not Found')->setStatusCode(404); - return ''; + return []; } } diff --git a/api/controllers/LoginController.php b/api/controllers/LoginController.php index 90b6fb51..7c8a03d2 100644 --- a/api/controllers/LoginController.php +++ b/api/controllers/LoginController.php @@ -45,7 +45,10 @@ public function callAction() */ return ['token' => $user->getToken()]; } else { - $this->response->setPayloadError('Incorrect credentials'); + $this + ->response + ->setPayloadError('Incorrect credentials') + ; } } } diff --git a/api/controllers/ProductTypes/GetController.php b/api/controllers/ProductTypes/GetController.php index ad9bd5b3..e1017473 100644 --- a/api/controllers/ProductTypes/GetController.php +++ b/api/controllers/ProductTypes/GetController.php @@ -7,6 +7,7 @@ use Niden\Api\Controllers\BaseController; use Niden\Constants\Relationships; use Niden\Models\ProductTypes; +use Niden\Transformers\ProductTypesTransformer; /** * Class GetController @@ -27,6 +28,6 @@ class GetController extends BaseController protected $resource = Relationships::PRODUCT_TYPES; /** @var string */ - protected $transformer = ProductTypes::class; + protected $transformer = ProductTypesTransformer::class; } diff --git a/library/Http/Response.php b/library/Http/Response.php index df01d0a1..114127fe 100644 --- a/library/Http/Response.php +++ b/library/Http/Response.php @@ -58,9 +58,10 @@ public function setPayloadErrors($errors): Response */ public function setPayloadSuccess($content = []): Response { - $data = (true === is_array($content)) ? $content : [$content]; + $data = (true === is_array($content)) ? $content : ['data' => $content]; + $data = (true === isset($data['data'])) ? $data : ['data' => $data]; - $this->content['data'] = $data; + $this->content = $data; $this->setPayloadContent(); return $this; @@ -77,8 +78,6 @@ public function setPayloadContent(): Response { parent::setJsonContent($this->processPayload()); - $this->setStatusCode(200); - $this->setContentType('application/vnd.api+json', 'UTF-8'); $this->setHeader('E-Tag', sha1($this->getContent())); return $this; diff --git a/library/Providers/ResponseProvider.php b/library/Providers/ResponseProvider.php index 95239ea8..8818be56 100644 --- a/library/Providers/ResponseProvider.php +++ b/library/Providers/ResponseProvider.php @@ -20,7 +20,10 @@ public function register(DiInterface $container) /** * Assume success. We will work with the edge cases in the code */ - $response->setStatusCode(200); + $response + ->setStatusCode(200) + ->setContentType('application/vnd.api+json', 'UTF-8') + ; $container->setShared('response', $response); } diff --git a/library/Traits/FractalTrait.php b/library/Traits/FractalTrait.php index 2f35b4bb..128f731f 100644 --- a/library/Traits/FractalTrait.php +++ b/library/Traits/FractalTrait.php @@ -42,6 +42,6 @@ protected function format($results, string $transformer, string $resource, array $resource = new Collection($results, new $transformer(), $resource); $results = $manager->createData($resource)->toArray(); - return $results['data']; + return $results; } } diff --git a/library/Traits/ResponseTrait.php b/library/Traits/ResponseTrait.php index cc2a939c..e216d62f 100644 --- a/library/Traits/ResponseTrait.php +++ b/library/Traits/ResponseTrait.php @@ -39,13 +39,30 @@ public function process(Micro $api) { /** @var Response $response */ $response = $api->getService('response'); - $data = $api->getReturnedValue(); - if (200 === $response->getStatusCode()) { - $response->setPayloadSuccess($data); + if (200 === $response->getStatusCode() && true !== $this->checkCurrentContent($response)) { + $returned = $api->getReturnedValue(); + $response->setPayloadSuccess($returned); } if (true !== $response->isSent()) { $response->send(); } } + + /** + * @param Response $response + * + * @return bool + */ + private function checkCurrentContent(Response $response): bool + { + $return = false; + $content = $response->getContent(); + if (true !== empty($content)) { + $content = json_decode($content, true); + $return = isset($content['errors']); + } + + return $return; + } } diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php index fc51eefc..a1fea3c0 100644 --- a/library/Transformers/CompaniesTransformer.php +++ b/library/Transformers/CompaniesTransformer.php @@ -16,6 +16,7 @@ class CompaniesTransformer extends BaseTransformer { protected $availableIncludes = [ Relationships::PRODUCTS, + Relationships::INDIVIDUALS, ]; /** diff --git a/library/Transformers/PayloadTransformer.php b/library/Transformers/PayloadTransformer.php index 88ac5559..61cc159a 100644 --- a/library/Transformers/PayloadTransformer.php +++ b/library/Transformers/PayloadTransformer.php @@ -4,6 +4,7 @@ namespace Niden\Transformers; +use function array_merge; use function date; use function json_encode; use function sha1; @@ -21,19 +22,25 @@ class PayloadTransformer extends TransformerAbstract */ public function transform(array $content) { - $section = (true === isset($content['errors'])) ? 'errors' : 'data'; $timestamp = date('c'); - $result = [ + $jsonApi = [ 'jsonapi' => [ 'version' => '1.0', - ], - $section => $content[$section], - 'meta' => [ + ] + ]; + $meta = [ + 'meta' => [ 'timestamp' => $timestamp, - 'hash' => sha1($timestamp . json_encode($content[$section])), + 'hash' => sha1($timestamp . json_encode($content)), ], ]; + $result = array_merge( + $jsonApi, + $content, + $meta + ); + return $result; } } diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php new file mode 100644 index 00000000..54380f57 --- /dev/null +++ b/library/Transformers/ProductTypesTransformer.php @@ -0,0 +1,34 @@ +getRelated(Relationships::PRODUCTS); + + return $this->collection($products, new ProductsTransformer(), Relationships::PRODUCTS); + } +} diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index 8a168ecc..c1e041c3 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -47,11 +47,10 @@ public function seeResponseIsSuccessful() $response = $this->grabResponse(); $response = json_decode($response, true); - $errors = $response['errors'] ?? []; - $section = (count($errors) > 0) ? 'errors' : 'data'; $timestamp = $response['meta']['timestamp']; $hash = $response['meta']['hash']; - $this->assertEquals($hash, sha1($timestamp . json_encode($response[$section]))); + unset($response['meta'], $response['jsonapi']); + $this->assertEquals($hash, sha1($timestamp . json_encode($response))); } /** @@ -78,7 +77,8 @@ public function seeResponseIs404() $timestamp = $response['meta']['timestamp']; $hash = $response['meta']['hash']; $this->assertEquals('Not Found', $response['errors'][0]); - $this->assertEquals($hash, sha1($timestamp . json_encode($response['errors']))); + unset($response['jsonapi'], $response['meta']); + $this->assertEquals($hash, sha1($timestamp . json_encode($response))); } public function seeErrorJsonResponse(string $message) diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 93923a32..6b79aa87 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -161,6 +161,108 @@ public function getProducts(ApiTester $I) ); } + public function getProductsWithProductTypes(ApiTester $I) + { + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Products $product */ + $product = $I->haveRecordWithFields( + Products::class, + [ + 'name' => 'my product', + 'typeId' => $productType->get('id'), + 'description' => 'my product description', + 'quantity' => 99, + 'price' => 19.99, + ] + ); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productsUrl . '/' . $product->get('id') . '/relationships/' . Relationships::PRODUCT_TYPES); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $url = envValue('APP_URL', 'http://localhost'); + $response = json_decode($I->grabResponse(), true); + $expected = [ + 'data' => [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $product->get('id'), + 'attributes' => [ + 'typeId' => $productType->get('id'), + 'name' => $product->get('name'), + 'description' => $product->get('description'), + 'quantity' => $product->get('quantity'), + 'price' => $product->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + $url, + Relationships::PRODUCTS, + $product->get('id') + ), + ], + 'relationships' => [ + Relationships::PRODUCT_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + $url, + Relationships::PRODUCTS, + $product->get('id'), + Relationships::PRODUCT_TYPES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + $url, + Relationships::PRODUCTS, + $product->get('id'), + Relationships::PRODUCT_TYPES + ), + ], + 'data' => [ + 'type' => Relationships::PRODUCT_TYPES, + 'id' => $productType->get('id'), + ], + ], + ], + ], + ], + 'included' => [ + [ + 'type' => Relationships::PRODUCT_TYPES, + 'id' => $productType->get('id'), + 'attributes' => [ + 'name' => $productType->get('name'), + 'description' => $productType->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + $url, + Relationships::PRODUCT_TYPES, + $productType->get('id') + ), + ], + ], + ], + ]; + + $I->assertEquals($expected['data'], $response['data']); + $I->assertEquals($expected['included'], $response['included']); + } + public function getProductsNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/unit/library/Http/ResponseCest.php b/tests/unit/library/Http/ResponseCest.php index 73c21738..377e8ad9 100755 --- a/tests/unit/library/Http/ResponseCest.php +++ b/tests/unit/library/Http/ResponseCest.php @@ -25,11 +25,11 @@ public function checkResponseWithStringPayload(UnitTester $I) $payload = $this->checkPayload($I, $response); $I->assertFalse(isset($payload['errors'])); - $I->assertEquals(['test'], $payload['data']); + $I->assertEquals('test', $payload['data']); } - private function checkPayload(UnitTester $I, Response $response, bool $error = false) - : array { + private function checkPayload(UnitTester $I, Response $response, bool $error = false): array + { $contents = $response->getContent(); $I->assertTrue(is_string($contents)); From 6898506039432cccd107201a57b4cec77a88f0aa Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 26 Jul 2018 20:11:57 -0400 Subject: [PATCH 50/70] Minor refactoring on checking responses; Added product type tests with products --- library/Models/ProductTypes.php | 4 +- library/Models/Products.php | 2 +- tests/_support/ApiTester.php | 15 +- tests/api/Companies/AddCest.php | 1 + tests/api/Companies/GetCest.php | 47 ++++++ tests/api/IndividualTypes/GetCest.php | 1 + tests/api/ProductTypes/GetCest.php | 141 ++++++++++++++++++ tests/api/Products/GetCest.php | 32 ++-- tests/api/Users/GetCest.php | 2 + .../library/Models/ProductTypesCest.php | 2 +- .../library/Models/ProductsCest.php | 2 +- 11 files changed, 216 insertions(+), 33 deletions(-) diff --git a/library/Models/ProductTypes.php b/library/Models/ProductTypes.php index 8ffe1495..37acf9ea 100644 --- a/library/Models/ProductTypes.php +++ b/library/Models/ProductTypes.php @@ -20,12 +20,12 @@ class ProductTypes extends AbstractModel */ public function initialize() { - $this->belongsTo( + $this->hasMany( 'id', Products::class, 'typeId', [ - 'alias' => Relationships::PRODUCT, + 'alias' => Relationships::PRODUCTS, 'reusable' => true, ] ); diff --git a/library/Models/Products.php b/library/Models/Products.php index d9131d78..ec0424fc 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -33,7 +33,7 @@ public function initialize() ] ); - $this->hasOne( + $this->belongsTo( 'typeId', ProductTypes::class, 'id', diff --git a/tests/_support/ApiTester.php b/tests/_support/ApiTester.php index c1e041c3..5b3be8ee 100644 --- a/tests/_support/ApiTester.php +++ b/tests/_support/ApiTester.php @@ -95,20 +95,9 @@ public function seeErrorJsonResponse(string $message) ); } - public function seeSuccessJsonResponse(array $data = [], array $extra = []) + public function seeSuccessJsonResponse(string $key = 'data', array $data = []) { - $contents = [ - 'jsonapi' => [ - 'version' => '1.0', - ], - 'data' => $data, - ]; - - if (true !== empty($extra)) { - $contents = $contents + $extra; - } - - $this->seeResponseContainsJson($contents); + $this->seeResponseContainsJson([$key => $data]); } public function apiLogin() diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index d2dde284..ac57b326 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -38,6 +38,7 @@ public function addNewCompany(ApiTester $I) $I->assertNotEquals(false, $company); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $company->get('id'), diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 74aed64b..31247e65 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -33,6 +33,7 @@ public function getCompany(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $comOne->get('id'), @@ -87,6 +88,7 @@ public function getCompanies(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $comOne->get('id'), @@ -182,6 +184,7 @@ public function getCompaniesWithProducts(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $comOne->get('id'), @@ -234,6 +237,50 @@ public function getCompaniesWithProducts(ApiTester $I) ] ] ); + + $I->seeSuccessJsonResponse( + 'included', + [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productOne->get('id'), + 'attributes' => [ + 'typeId' => $productOne->get('typeId'), + 'name' => $productOne->get('name'), + 'description' => $productOne->get('description'), + 'quantity' => $productOne->get('quantity'), + 'price' => $productOne->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCTS, + $productOne->get('id') + ), + ], + ], + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productTwo->get('id'), + 'attributes' => [ + 'typeId' => $productTwo->get('typeId'), + 'name' => $productTwo->get('name'), + 'description' => $productTwo->get('description'), + 'quantity' => $productTwo->get('quantity'), + 'price' => $productTwo->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCTS, + $productTwo->get('id') + ), + ], + ], + ] + ); } public function getCompaniesWithUnknownRelationship(ApiTester $I) diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index 6710f367..b3bb088c 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -32,6 +32,7 @@ public function getIndividualTypes(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $typeOne->get('id'), diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index 453a3355..cf6a6416 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -4,6 +4,8 @@ use ApiTester; use Niden\Constants\Relationships; +use function Niden\Core\envValue; +use Niden\Models\Products; use Niden\Models\ProductTypes; use Page\Data; use function uniqid; @@ -32,6 +34,7 @@ public function getProductTypes(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $typeOne->get('id'), @@ -64,6 +67,144 @@ public function getUnknownProductTypes(ApiTester $I) $I->seeResponseIs404(); } + public function getProductTypesWithProducts(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => uniqid('type-a-'), + 'description' => uniqid(), + ] + ); + /** @var Products $productOne */ + $productOne = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + /** @var Products $productTwo */ + $productTwo = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-b-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productTypesUrl . '/' . $productType->get('id') . '/relationships/' . Relationships::PRODUCTS); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::PRODUCT_TYPES, + 'id' => $productType->get('id'), + 'attributes' => [ + 'name' => $productType->get('name'), + 'description' => $productType->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCT_TYPES, + $productType->get('id') + ) + ], + 'relationships' => [ + Relationships::PRODUCTS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL'), + Relationships::PRODUCT_TYPES, + $productType->get('id'), + Relationships::PRODUCTS + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCT_TYPES, + $productType->get('id'), + Relationships::PRODUCTS + ), + ], + 'data' => [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productOne->get('id'), + ], + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productTwo->get('id'), + ], + ] + ] + ] + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productOne->get('id'), + 'attributes' => [ + 'typeId' => $productOne->get('typeId'), + 'name' => $productOne->get('name'), + 'description' => $productOne->get('description'), + 'quantity' => $productOne->get('quantity'), + 'price' => $productOne->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCTS, + $productOne->get('id') + ), + ], + ], + [ + 'type' => Relationships::PRODUCTS, + 'id' => $productTwo->get('id'), + 'attributes' => [ + 'typeId' => $productTwo->get('typeId'), + 'name' => $productTwo->get('name'), + 'description' => $productTwo->get('description'), + 'quantity' => $productTwo->get('quantity'), + 'price' => $productTwo->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCTS, + $productTwo->get('id') + ), + ], + ], + ] + ); + } + public function getProductTypesNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 6b79aa87..96f56a1e 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -43,6 +43,7 @@ public function getProduct(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $product->get('id'), @@ -120,6 +121,7 @@ public function getProducts(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $productOne->get('id'), @@ -191,10 +193,9 @@ public function getProductsWithProductTypes(ApiTester $I) $I->sendGET(Data::$productsUrl . '/' . $product->get('id') . '/relationships/' . Relationships::PRODUCT_TYPES); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); - $url = envValue('APP_URL', 'http://localhost'); - $response = json_decode($I->grabResponse(), true); - $expected = [ - 'data' => [ + $I->seeSuccessJsonResponse( + 'data', + [ [ 'type' => Relationships::PRODUCTS, 'id' => $product->get('id'), @@ -208,7 +209,7 @@ public function getProductsWithProductTypes(ApiTester $I) 'links' => [ 'self' => sprintf( '%s/%s/%s', - $url, + envValue('APP_URL', 'localhost'), Relationships::PRODUCTS, $product->get('id') ), @@ -218,14 +219,14 @@ public function getProductsWithProductTypes(ApiTester $I) 'links' => [ 'self' => sprintf( '%s/%s/%s/relationships/%s', - $url, + envValue('APP_URL', 'localhost'), Relationships::PRODUCTS, $product->get('id'), Relationships::PRODUCT_TYPES ), 'related' => sprintf( '%s/%s/%s/%s', - $url, + envValue('APP_URL', 'localhost'), Relationships::PRODUCTS, $product->get('id'), Relationships::PRODUCT_TYPES @@ -238,8 +239,12 @@ public function getProductsWithProductTypes(ApiTester $I) ], ], ], - ], - 'included' => [ + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ [ 'type' => Relationships::PRODUCT_TYPES, 'id' => $productType->get('id'), @@ -250,17 +255,14 @@ public function getProductsWithProductTypes(ApiTester $I) 'links' => [ 'self' => sprintf( '%s/%s/%s', - $url, + envValue('APP_URL', 'localhost'), Relationships::PRODUCT_TYPES, $productType->get('id') ), ], ], - ], - ]; - - $I->assertEquals($expected['data'], $response['data']); - $I->assertEquals($expected['included'], $response['included']); + ] + ); } public function getProductsNoData(ApiTester $I) diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 0a2a182c..995196e1 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -171,6 +171,7 @@ public function loginKnownUserValidToken(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $record->get('id'), @@ -220,6 +221,7 @@ public function getManyUsers(ApiTester $I) $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( + 'data', [ [ 'id' => $userOne->get('id'), diff --git a/tests/integration/library/Models/ProductTypesCest.php b/tests/integration/library/Models/ProductTypesCest.php index 8e3b6e13..ded868bd 100644 --- a/tests/integration/library/Models/ProductTypesCest.php +++ b/tests/integration/library/Models/ProductTypesCest.php @@ -37,7 +37,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(ProductTypes::class); $expected = [ - [0, 'id', Products::class, 'typeId', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + [2, 'id', Products::class, 'typeId', ['alias' => Relationships::PRODUCTS, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index d0dac7a6..dadc642b 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -43,7 +43,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Products::class); $expected = [ - [1, 'typeId', ProductTypes::class, 'id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], + [0, 'typeId', ProductTypes::class, 'id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } From 4c3f107eb733392a4b6e0e90cdec1a810630eb54 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Sat, 28 Jul 2018 20:25:16 -0400 Subject: [PATCH 51/70] Work on the routes and tests --- library/Mvc/Model/AbstractModel.php | 25 ++++------- library/Providers/RouterProvider.php | 50 ++++++++++++++------- tests/_support/Page/Data.php | 26 ++++++++--- tests/unit/library/Providers/RouterCest.php | 26 ++++++----- 4 files changed, 76 insertions(+), 51 deletions(-) diff --git a/library/Mvc/Model/AbstractModel.php b/library/Mvc/Model/AbstractModel.php index 8d2f0149..8c12d27d 100644 --- a/library/Mvc/Model/AbstractModel.php +++ b/library/Mvc/Model/AbstractModel.php @@ -72,16 +72,15 @@ public function getModelMessages(Logger $logger = null): string /** * Sets a field in the model sanitized * - * @param string $field The name of the field - * @param mixed $value The value of the field - * @param bool $sanitize Whether to sanitize input or not + * @param string $field The name of the field + * @param mixed $value The value of the field * * @return AbstractModel * @throws ModelException */ - public function set($field, $value, $sanitize = true): AbstractModel + public function set($field, $value): AbstractModel { - $this->getSetFields('set', $field, $value, $sanitize); + $this->getSetFields('set', $field, $value); return $this; } @@ -92,12 +91,11 @@ public function set($field, $value, $sanitize = true): AbstractModel * @param string $type * @param string $field * @param mixed $value - * @param bool $sanitize * * @return mixed * @throws ModelException */ - private function getSetFields(string $type, string $field, $value = '', bool $sanitize = true) + private function getSetFields(string $type, string $field, $value = '') { $return = null; $modelFields = $this->getModelFilters(); @@ -113,9 +111,9 @@ private function getSetFields(string $type, string $field, $value = '', bool $sa } if ('get' === $type) { - $return = $this->sanitize($this->$field, $filter, $sanitize); + $return = $this->sanitize($this->$field, $filter); } else { - $this->$field = $this->sanitize($value, $filter, $sanitize); + $this->$field = $this->sanitize($value, $filter); } return $return; @@ -126,19 +124,14 @@ private function getSetFields(string $type, string $field, $value = '', bool $sa * * @param mixed $value The value to sanitize * @param string|array $filter The filter to apply - * @param bool $sanitize * * @return mixed */ - private function sanitize($value, $filter, bool $sanitize = true) + private function sanitize($value, $filter) { /** @var Filter $filterService */ $filterService = $this->getDI()->get('filter'); - if (true === $sanitize) { - return $filterService->sanitize($value, $filter); - } else { - return $value; - } + return $filterService->sanitize($value, $filter); } } diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index db6d48db..c0e06e81 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -11,6 +11,7 @@ use Niden\Api\Controllers\ProductTypes\GetController as ProductTypesGetController; use Niden\Api\Controllers\Users\GetController as UsersGetController; use Niden\Api\Controllers\LoginController; +use Niden\Constants\Relationships as Rel; use Niden\Middleware\NotFoundMiddleware; use Niden\Middleware\AuthenticationMiddleware; use Niden\Middleware\ResponseMiddleware; @@ -106,24 +107,39 @@ private function getMiddleware(): array */ private function getRoutes(): array { - return [ + $routes = [ // Class, Method, Route, Handler - [LoginController::class, '/login', 'post', '/'], - [CompaniesAddController::class, '/companies', 'post', '/'], - [CompaniesGetController::class, '/companies', 'get', '/'], - [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}'], - [CompaniesGetController::class, '/companies', 'get', '/{companyId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], - [IndividualTypesGetController::class, '/individual-types', 'get', '/'], - [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}'], - [IndividualTypesGetController::class, '/individual-types', 'get', '/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], - [ProductsGetController::class, '/products', 'get', '/'], - [ProductsGetController::class, '/products', 'get', '/{productId:[0-9]+}'], - [ProductsGetController::class, '/products', 'get', '/{productId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], - [ProductTypesGetController::class, '/product-types', 'get', '/'], - [ProductTypesGetController::class, '/product-types', 'get', '/{typeId:[0-9]+}'], - [ProductTypesGetController::class, '/product-types', 'get', '/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], - [UsersGetController::class, '/users', 'get', '/'], - [UsersGetController::class, '/users', 'get', '/{userId:[0-9]+}'], + [LoginController::class, '/login', 'post', '/'], + [CompaniesAddController::class, '/companies', 'post', '/'], + [UsersGetController::class, '/users', 'get', '/'], + [UsersGetController::class, '/users', 'get', '/{recordId:[0-9]+}'], ]; + + $routes = $this->getMultiRoutes($routes, CompaniesGetController::class, Rel::COMPANIES); + $routes = $this->getMultiRoutes($routes, IndividualTypesGetController::class, Rel::INDIVIDUAL_TYPES); + $routes = $this->getMultiRoutes($routes, ProductsGetController::class, Rel::PRODUCTS); + $routes = $this->getMultiRoutes($routes, ProductTypesGetController::class, Rel::PRODUCT_TYPES); + + + return $routes; + } + + /** + * Adds multiple routes for the same handler abiding by the JSONAPI standard + * + * @param array $routes + * @param string $class + * @param string $relationship + * + * @return array + */ + private function getMultiRoutes(array $routes, string $class, string $relationship): array + { + $routes[] = [$class, '/' . $relationship, 'get', '/']; + $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}']; + $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}']; + $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}']; + + return $routes; } } diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index b2c71574..f9205327 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -4,13 +4,25 @@ class Data { - public static $companiesUrl = '/companies'; - public static $loginUrl = '/login'; - public static $individualTypesUrl = '/individual-types'; - public static $productsUrl = '/products'; - public static $productTypesUrl = '/product-types'; - public static $usersUrl = '/users'; - public static $wrongUrl = '/sommething'; + public static $companiesUrl = '/companies'; + public static $companiesRecordUrl = '/companies/%'; + public static $companiesRecordRelationshipUrl = '/companies/%/%'; + public static $companiesRecordRelationshipRelationshipUrl = '/companies/%/relationships/%s'; + public static $loginUrl = '/login'; + public static $individualTypesUrl = '/individual-types'; + public static $individualTypesRecordUrl = '/individual-types/%'; + public static $individualTypesRecordRelationshipUrl = '/individual-types/%/%'; + public static $individualTypesRecordRelationshipRelationshipUrl = '/individual-types/%/relationships/%s'; + public static $productsUrl = '/products'; + public static $productsRecordUrl = '/products/%'; + public static $productsRecordRelationshipUrl = '/products/%/%'; + public static $productsRecordRelationshipRelationshipUrl = '/products/%/relationships/%s'; + public static $productTypesUrl = '/product-types'; + public static $productTypesRecordUrl = '/product-types/%'; + public static $productTypesRecordRelationshipUrl = '/product-types/%/%'; + public static $productTypesRecordRelationshipRelationshipUrl = '/product-types/%/relationships/%s'; + public static $usersUrl = '/users'; + public static $wrongUrl = '/sommething'; public static function loginJson() { diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 8fd530c0..0e8a8962 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -31,23 +31,27 @@ public function checkRegistration(UnitTester $I) $expected = [ ['POST', '/login'], ['POST', '/companies'], + ['GET', '/users'], + ['GET', '/users/{recordId:[0-9]+}'], ['GET', '/companies'], - ['GET', '/companies/{companyId:[0-9]+}'], - ['GET', '/companies/{companyId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/companies/{recordId:[0-9]+}'], + ['GET', '/companies/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], + ['GET', '/companies/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ['GET', '/individual-types'], - ['GET', '/individual-types/{typeId:[0-9]+}'], - ['GET', '/individual-types/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individual-types/{recordId:[0-9]+}'], + ['GET', '/individual-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individual-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ['GET', '/products'], - ['GET', '/products/{productId:[0-9]+}'], - ['GET', '/products/{productId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/products/{recordId:[0-9]+}'], + ['GET', '/products/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], + ['GET', '/products/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ['GET', '/product-types'], - ['GET', '/product-types/{typeId:[0-9]+}'], - ['GET', '/product-types/{typeId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], - ['GET', '/users'], - ['GET', '/users/{userId:[0-9]+}'], + ['GET', '/product-types/{recordId:[0-9]+}'], + ['GET', '/product-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], + ['GET', '/product-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ]; - $I->assertEquals(16, count($routes)); + $I->assertEquals(20, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); From 492a446a2259186fa0721a08ed2f71ccb13b84a7 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 30 Jul 2018 13:13:19 -0400 Subject: [PATCH 52/70] Added more test constants (urls); Refactored tests; Added more tests for direct relationships --- tests/_support/Page/Data.php | 24 ++-- tests/api/Companies/GetCest.php | 183 ++++++++++++++------------ tests/api/IndividualTypes/GetCest.php | 8 +- tests/api/ProductTypes/GetCest.php | 78 +++++++---- tests/api/Products/GetCest.php | 42 ++++-- 5 files changed, 197 insertions(+), 138 deletions(-) diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index f9205327..2f6e2e25 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -5,22 +5,22 @@ class Data { public static $companiesUrl = '/companies'; - public static $companiesRecordUrl = '/companies/%'; - public static $companiesRecordRelationshipUrl = '/companies/%/%'; - public static $companiesRecordRelationshipRelationshipUrl = '/companies/%/relationships/%s'; + public static $companiesRecordUrl = '/companies/%s'; + public static $companiesRecordRelationshipUrl = '/companies/%s/%s'; + public static $companiesRecordRelationshipRelationshipUrl = '/companies/%s/relationships/%s'; public static $loginUrl = '/login'; public static $individualTypesUrl = '/individual-types'; - public static $individualTypesRecordUrl = '/individual-types/%'; - public static $individualTypesRecordRelationshipUrl = '/individual-types/%/%'; - public static $individualTypesRecordRelationshipRelationshipUrl = '/individual-types/%/relationships/%s'; + public static $individualTypesRecordUrl = '/individual-types/%s'; + public static $individualTypesRecordRelationshipUrl = '/individual-types/%s/%s'; + public static $individualTypesRecordRelationshipRelationshipUrl = '/individual-types/%s/relationships/%s'; public static $productsUrl = '/products'; - public static $productsRecordUrl = '/products/%'; - public static $productsRecordRelationshipUrl = '/products/%/%'; - public static $productsRecordRelationshipRelationshipUrl = '/products/%/relationships/%s'; + public static $productsRecordUrl = '/products/%s'; + public static $productsRecordRelationshipUrl = '/products/%s/%s'; + public static $productsRecordRelationshipRelationshipUrl = '/products/%s/relationships/%s'; public static $productTypesUrl = '/product-types'; - public static $productTypesRecordUrl = '/product-types/%'; - public static $productTypesRecordRelationshipUrl = '/product-types/%/%'; - public static $productTypesRecordRelationshipRelationshipUrl = '/product-types/%/relationships/%s'; + public static $productTypesRecordUrl = '/product-types/%s'; + public static $productTypesRecordRelationshipUrl = '/product-types/%s/%s'; + public static $productTypesRecordRelationshipRelationshipUrl = '/product-types/%s/relationships/%s'; public static $usersUrl = '/users'; public static $wrongUrl = '/sommething'; diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 31247e65..92acc770 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -114,7 +114,99 @@ public function getCompanies(ApiTester $I) ); } + public function getCompaniesWithRelationshipProducts(ApiTester $I) + { + $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); + } + public function getCompaniesWithProducts(ApiTester $I) + { + $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipUrl); + } + + public function getCompaniesWithUnknownRelationship(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var ProductTypes $productType */ + $productType = $I->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => uniqid('prt-a-'), + 'description' => uniqid(), + ] + ); + + /** @var Products $productOne */ + $productOne = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-a-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + /** @var Products $productTwo */ + $productTwo = $I->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid('prd-b-'), + 'typeId' => $productType->get('id'), + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productOne->get('id'), + ] + ); + + $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $comOne->get('id'), + 'productId' => $productTwo->get('id'), + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/unknown'); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + + public function getCompaniesNoData(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function runCompaniesWithProductsTests(ApiTester $I, $url = '') { $I->addApiUserRecord(); $token = $I->apiLogin(); @@ -179,7 +271,13 @@ public function getCompaniesWithProducts(ApiTester $I) ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/' . Relationships::PRODUCTS); + $I->sendGET( + sprintf( + $url, + $comOne->get('id'), + Relationships::PRODUCTS + ) + ); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); @@ -282,86 +380,5 @@ public function getCompaniesWithProducts(ApiTester $I) ] ); } - - public function getCompaniesWithUnknownRelationship(ApiTester $I) - { - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('prt-a-'), - 'description' => uniqid(), - ] - ); - - /** @var Products $productOne */ - $productOne = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - - /** @var Products $productTwo */ - $productTwo = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-b-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); - - $I->haveRecordWithFields( - CompaniesXProducts::class, - [ - 'companyId' => $comOne->get('id'), - 'productId' => $productOne->get('id'), - ] - ); - - $I->haveRecordWithFields( - CompaniesXProducts::class, - [ - 'companyId' => $comOne->get('id'), - 'productId' => $productTwo->get('id'), - ] - ); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/unknown'); - $I->deleteHeader('Authorization'); - $I->seeResponseIs404(); - } - - public function getCompaniesNoData(ApiTester $I) - { - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse(); - } } + diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index b3bb088c..6dff6569 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -18,13 +18,15 @@ public function getIndividualTypes(ApiTester $I) $typeOne = $I->haveRecordWithFields( IndividualTypes::class, [ - 'name' => uniqid('type-a-'), + 'name' => uniqid('type-a-'), + 'description' => uniqid('desc-a-'), ] ); $typeTwo = $I->haveRecordWithFields( IndividualTypes::class, [ - 'name' => uniqid('type-b-'), + 'name' => uniqid('type-b-'), + 'description' => uniqid('desc-b-'), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -60,7 +62,7 @@ public function getUnknownIndividualTypes(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$individualTypesUrl . '/1'); + $I->sendGET(sprintf(Data::$individualTypesRecordUrl, 1)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index cf6a6416..0a34e467 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -4,10 +4,10 @@ use ApiTester; use Niden\Constants\Relationships; -use function Niden\Core\envValue; use Niden\Models\Products; use Niden\Models\ProductTypes; use Page\Data; +use function Niden\Core\envValue; use function uniqid; class GetCest @@ -20,13 +20,15 @@ public function getProductTypes(ApiTester $I) $typeOne = $I->haveRecordWithFields( ProductTypes::class, [ - 'name' => uniqid('type-a-'), + 'name' => uniqid('type-a-'), + 'description' => uniqid('desc-a-'), ] ); $typeTwo = $I->haveRecordWithFields( ProductTypes::class, [ - 'name' => uniqid('type-b-'), + 'name' => uniqid('type-b-'), + 'description' => uniqid('desc-b-'), ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); @@ -62,12 +64,35 @@ public function getUnknownProductTypes(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productTypesUrl . '/1'); + $I->sendGET(sprintf(Data::$productTypesRecordUrl, 1)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } + public function getProductTypesWithRelationshipProducts(ApiTester $I) + { + var_dump(Data::$productTypesRecordRelationshipUrl); + $this->runProductTypesWithProductsTests($I, Data::$productTypesRecordRelationshipUrl); + } + public function getProductTypesWithProducts(ApiTester $I) + { + $this->runProductTypesWithProductsTests($I, Data::$productTypesRecordRelationshipRelationshipUrl); + } + + public function getProductTypesNoData(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productTypesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function runProductTypesWithProductsTests(ApiTester $I, $url) { $I->addApiUserRecord(); $token = $I->apiLogin(); @@ -102,9 +127,20 @@ public function getProductTypesWithProducts(ApiTester $I) 'price' => 19.99, ] ); - + var_dump($url); + var_dump(sprintf( + $url, + $productType->get('id'), + Relationships::PRODUCTS + )); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productTypesUrl . '/' . $productType->get('id') . '/relationships/' . Relationships::PRODUCTS); + $I->sendGET( + sprintf( + $url, + $productType->get('id'), + Relationships::PRODUCTS + ) + ); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); @@ -112,19 +148,19 @@ public function getProductTypesWithProducts(ApiTester $I) 'data', [ [ - 'type' => Relationships::PRODUCT_TYPES, - 'id' => $productType->get('id'), - 'attributes' => [ + 'type' => Relationships::PRODUCT_TYPES, + 'id' => $productType->get('id'), + 'attributes' => [ 'name' => $productType->get('name'), 'description' => $productType->get('description'), ], - 'links' => [ + 'links' => [ 'self' => sprintf( '%s/%s/%s', envValue('APP_URL'), Relationships::PRODUCT_TYPES, $productType->get('id') - ) + ), ], 'relationships' => [ Relationships::PRODUCTS => [ @@ -144,7 +180,7 @@ public function getProductTypesWithProducts(ApiTester $I) Relationships::PRODUCTS ), ], - 'data' => [ + 'data' => [ [ 'type' => Relationships::PRODUCTS, 'id' => $productOne->get('id'), @@ -153,9 +189,9 @@ public function getProductTypesWithProducts(ApiTester $I) 'type' => Relationships::PRODUCTS, 'id' => $productTwo->get('id'), ], - ] - ] - ] + ], + ], + ], ], ] ); @@ -204,16 +240,4 @@ public function getProductTypesWithProducts(ApiTester $I) ] ); } - - public function getProductTypesNoData(ApiTester $I) - { - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productTypesUrl); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse(); - } } diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 96f56a1e..e6c8d65d 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -164,6 +164,28 @@ public function getProducts(ApiTester $I) } public function getProductsWithProductTypes(ApiTester $I) + { + $this->runProductsWithProductTypesTests($I, Data::$productsRecordRelationshipRelationshipUrl); + } + + public function getProductsWithRelationshipProductTypes(ApiTester $I) + { + $this->runProductsWithProductTypesTests($I, Data::$productsRecordRelationshipUrl); + } + + public function getProductsNoData(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$productsUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function runProductsWithProductTypesTests(ApiTester $I, $url) { /** @var ProductTypes $productType */ $productType = $I->haveRecordWithFields( @@ -190,7 +212,13 @@ public function getProductsWithProductTypes(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productsUrl . '/' . $product->get('id') . '/relationships/' . Relationships::PRODUCT_TYPES); + $I->sendGET( + sprintf( + $url, + $product->get('id'), + Relationships::PRODUCT_TYPES + ) + ); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -264,16 +292,4 @@ public function getProductsWithProductTypes(ApiTester $I) ] ); } - - public function getProductsNoData(ApiTester $I) - { - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productsUrl); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse(); - } } From a82c455ae6d6fc05f1580984ae75e9d1448cf358 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 30 Jul 2018 14:42:28 -0400 Subject: [PATCH 53/70] Added data cache provider; reduced queries and response time --- api/config/providers.php | 2 + api/controllers/BaseController.php | 8 ++- api/controllers/LoginController.php | 8 ++- library/Middleware/TokenUserMiddleware.php | 5 +- .../Middleware/TokenValidationMiddleware.php | 5 +- .../TokenVerificationMiddleware.php | 5 +- library/Providers/CacheDataProvider.php | 67 +++++++++++++++++++ library/Traits/QueryTrait.php | 63 +++++++++++++---- .../integration/library/Traits/QueryCest.php | 13 +++- tests/unit/library/Providers/CacheCest.php | 26 +++++++ 10 files changed, 177 insertions(+), 25 deletions(-) create mode 100644 library/Providers/CacheDataProvider.php create mode 100644 tests/unit/library/Providers/CacheCest.php diff --git a/api/config/providers.php b/api/config/providers.php index 178e163e..2feba384 100644 --- a/api/config/providers.php +++ b/api/config/providers.php @@ -4,6 +4,7 @@ * Enabled providers. Order does matter */ +use Niden\Providers\CacheDataProvider; use Niden\Providers\ConfigProvider; use Niden\Providers\DatabaseProvider; use Niden\Providers\ErrorHandlerProvider; @@ -22,4 +23,5 @@ RequestProvider::class, ResponseProvider::class, RouterProvider::class, + CacheDataProvider::class, ]; diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 212cc1c3..567f5b31 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -8,6 +8,7 @@ use Niden\Traits\FractalTrait; use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; @@ -20,8 +21,9 @@ * * @package Niden\Api\Controllers * - * @property Micro $application - * @property Response $response + * @property Micro $application + * @property Libmemcached $cache + * @property Response $response */ class BaseController extends Controller { @@ -56,7 +58,7 @@ public function callAction($id = 0, $relationships = '') { $parameters = $this->checkIdParameter($id); $parameter = $this->filter->sanitize($relationships, [Filter::FILTER_STRING, Filter::FILTER_TRIM]); - $results = $this->getRecords($this->model, $parameters, $this->orderBy); + $results = $this->getRecords($this->cache, $this->model, $parameters, $this->orderBy); $related = []; if (count($parameters) > 0 && 0 === count($results)) { diff --git a/api/controllers/LoginController.php b/api/controllers/LoginController.php index 7c8a03d2..6585ec5b 100644 --- a/api/controllers/LoginController.php +++ b/api/controllers/LoginController.php @@ -10,6 +10,7 @@ use Niden\Models\Users; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Filter; use Phalcon\Mvc\Controller; @@ -18,8 +19,9 @@ * * @package Niden\Api\Controllers * - * @property Request $request - * @property Response $response + * @property Libmemcached $cache + * @property Request $request + * @property Response $response */ class LoginController extends Controller { @@ -37,7 +39,7 @@ public function callAction() $username = $this->request->getPost('username', Filter::FILTER_STRING); $password = $this->request->getPost('password', Filter::FILTER_STRING); /** @var Users|false $user */ - $user = $this->getUserByUsernameAndPassword($username, $password); + $user = $this->getUserByUsernameAndPassword($this->cache, $username, $password); if (false !== $user) { /** diff --git a/library/Middleware/TokenUserMiddleware.php b/library/Middleware/TokenUserMiddleware.php index 0e030456..1a7c9344 100755 --- a/library/Middleware/TokenUserMiddleware.php +++ b/library/Middleware/TokenUserMiddleware.php @@ -6,6 +6,7 @@ use Niden\Http\Request; use Niden\Models\Users; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Mvc\Micro; /** @@ -22,6 +23,8 @@ class TokenUserMiddleware extends TokenBase */ public function call(Micro $api) { + /** @var Libmemcached $cache */ + $cache = $api->getService('cache'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -32,7 +35,7 @@ public function call(Micro $api) $token = $this->getToken($request->getBearerTokenFromHeader()); /** @var Users|false $user */ - $user = $this->getUserByToken($token); + $user = $this->getUserByToken($cache, $token); if (false === $user) { $this->halt($api, 200, 'Invalid Token'); diff --git a/library/Middleware/TokenValidationMiddleware.php b/library/Middleware/TokenValidationMiddleware.php index f8e7b054..5a0f3a7c 100755 --- a/library/Middleware/TokenValidationMiddleware.php +++ b/library/Middleware/TokenValidationMiddleware.php @@ -7,6 +7,7 @@ use Niden\Exception\ModelException; use Niden\Http\Request; use Niden\Models\Users; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Mvc\Micro; /** @@ -24,6 +25,8 @@ class TokenValidationMiddleware extends TokenBase */ public function call(Micro $api) { + /** @var Libmemcached $cache */ + $cache = $api->getService('cache'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -36,7 +39,7 @@ public function call(Micro $api) $token = $this->getToken($request->getBearerTokenFromHeader()); /** @var Users $user */ - $user = $this->getUserByToken($token); + $user = $this->getUserByToken($cache, $token); if (false === $token->validate($user->getValidationData())) { $this->halt($api, 200, 'Invalid Token'); diff --git a/library/Middleware/TokenVerificationMiddleware.php b/library/Middleware/TokenVerificationMiddleware.php index e92ecd2f..86cb06b1 100755 --- a/library/Middleware/TokenVerificationMiddleware.php +++ b/library/Middleware/TokenVerificationMiddleware.php @@ -8,6 +8,7 @@ use Niden\Exception\ModelException; use Niden\Http\Request; use Niden\Models\Users; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Mvc\Micro; /** @@ -25,6 +26,8 @@ class TokenVerificationMiddleware extends TokenBase */ public function call(Micro $api) { + /** @var Libmemcached $cache */ + $cache = $api->getService('cache'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -38,7 +41,7 @@ public function call(Micro $api) $signer = new Sha512(); /** @var Users $user */ - $user = $this->getUserByToken($token); + $user = $this->getUserByToken($cache, $token); if (false === $token->verify($signer, $user->get('tokenPassword'))) { $this->halt($api, 200, 'Invalid Token'); } diff --git a/library/Providers/CacheDataProvider.php b/library/Providers/CacheDataProvider.php new file mode 100644 index 00000000..ba351a06 --- /dev/null +++ b/library/Providers/CacheDataProvider.php @@ -0,0 +1,67 @@ +setShared( + 'cache', + $this->createCache('data') + ); + } + + /** + * Returns a cache object + * + * @param string $prefix + * + * @return Libmemcached + */ + protected function createCache(string $prefix): Libmemcached + { + $frontAdapter = Data::class; + $frontOptions = [ + 'lifetime' => envValue('CACHE_LIFETIME', 86400), + ]; + $backOptions = $this->createOptions($prefix); + + return new Libmemcached(new $frontAdapter($frontOptions), $backOptions); + } + + /** + * Returns memcached options + * + * @param string $prefix + * + * @return array + */ + protected function createOptions(string $prefix): array + { + return [ + 'servers' => [ + 0 => [ + 'host' => envValue('DATA_API_MEMCACHED_HOST', '127.0.0.1'), + 'port' => envValue('DATA_API_MEMCACHED_PORT', 11211), + 'weight' => envValue('DATA_API_MEMCACHED_WEIGHT', 100), + ], + ], + 'client' => [ + \Memcached::OPT_HASH => \Memcached::HASH_MD5, + \Memcached::OPT_PREFIX_KEY => 'api-', + ], + 'lifetime' => 3600, + 'prefix' => $prefix . '-', + ]; + } +} diff --git a/library/Traits/QueryTrait.php b/library/Traits/QueryTrait.php index a39a474f..362ac28d 100644 --- a/library/Traits/QueryTrait.php +++ b/library/Traits/QueryTrait.php @@ -4,12 +4,15 @@ namespace Niden\Traits; +use function json_encode; use Lcobucci\JWT\Token; use Niden\Constants\Flags; use Niden\Constants\JWTClaims; use Niden\Models\Users; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Mvc\Model\Query\Builder; use Phalcon\Mvc\Model\ResultsetInterface; +use function sha1; /** * Trait QueryTrait @@ -21,11 +24,12 @@ trait QueryTrait /** * Gets a user from the database based on the JWT token * - * @param Token $token + * @param Libmemcached $cache + * @param Token $token * * @return Users|false */ - protected function getUserByToken(Token $token) + protected function getUserByToken(Libmemcached $cache, Token $token) { $parameters = [ 'issuer' => $token->getClaim(JWTClaims::CLAIM_ISSUER), @@ -33,7 +37,7 @@ protected function getUserByToken(Token $token) 'status' => Flags::ACTIVE, ]; - $result = $this->getRecords(Users::class, $parameters); + $result = $this->getRecords($cache, Users::class, $parameters); return $result[0] ?? false; } @@ -41,12 +45,13 @@ protected function getUserByToken(Token $token) /** * Gets a user from the database based on the username and password * - * @param string $username - * @param string $password + * @param Libmemcached $cache + * @param string $username + * @param string $password * * @return Users|false */ - protected function getUserByUsernameAndPassword($username, $password) + protected function getUserByUsernameAndPassword(Libmemcached $cache, $username, $password) { $parameters = [ 'username' => $username, @@ -54,7 +59,7 @@ protected function getUserByUsernameAndPassword($username, $password) 'status' => Flags::ACTIVE, ]; - $result = $this->getRecords(Users::class, $parameters); + $result = $this->getRecords($cache, Users::class, $parameters); return $result[0] ?? false; } @@ -62,14 +67,19 @@ protected function getUserByUsernameAndPassword($username, $password) /** * Runs a query using the builder * - * @param string $class - * @param array $where - * @param string $orderBy + * @param Libmemcached $cache + * @param string $class + * @param array $where + * @param string $orderBy * * @return ResultsetInterface */ - protected function getRecords(string $class, array $where = [], string $orderBy = '') - { + protected function getRecords( + Libmemcached $cache, + string $class, + array $where = [], + string $orderBy = '' + ): ResultsetInterface { $builder = new Builder(); $builder->addFrom($class); @@ -84,6 +94,33 @@ protected function getRecords(string $class, array $where = [], string $orderBy $builder->orderBy($orderBy); } - return $builder->getQuery()->execute(); + return $this->getResults($cache, $builder, $where); + } + + /** + * Runs the builder query if there is no cached data + * + * @param Libmemcached $cache + * @param Builder $builder + * @param array $where + * + * @return ResultsetInterface + */ + private function getResults(Libmemcached $cache, Builder $builder, array $where = []): ResultsetInterface + { + /** + * Calculate the cache key + */ + $phql = $builder->getPhql(); + $params = json_encode($where); + $cacheKey = sha1(sprintf('%s-%s.cache', $phql, $params)); + if (true === $cache->exists($cacheKey)) { + $data = $cache->get($cacheKey); + } else { + $data = $builder->getQuery()->execute(); + $cache->save($cacheKey, $data); + } + + return $data; } } diff --git a/tests/integration/library/Traits/QueryCest.php b/tests/integration/library/Traits/QueryCest.php index 36237f8f..b8dfe6f0 100644 --- a/tests/integration/library/Traits/QueryCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -9,6 +9,7 @@ use Niden\Models\Users; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; +use Phalcon\Cache\Backend\Libmemcached; /** * Class QueryCest @@ -37,7 +38,9 @@ public function checkGetUserByUsernameAndPassword(IntegrationTester $I) ] ); - $dbUser = $this->getUserByUsernameAndPassword('testusername', 'testpass'); + /** @var Libmemcached $cache */ + $cache = $I->grabFromDi('cache'); + $dbUser = $this->getUserByUsernameAndPassword($cache, 'testusername', 'testpass'); $I->assertNotEquals(false, $dbUser); } @@ -61,7 +64,9 @@ public function checkGetUserByWrongUsernameAndPasswordReturnsFalse(IntegrationTe ] ); - $I->assertFalse($this->getUserByUsernameAndPassword('testusername', 'nothing')); + /** @var Libmemcached $cache */ + $cache = $I->grabFromDi('cache'); + $I->assertFalse($this->getUserByUsernameAndPassword($cache, 'testusername', 'nothing')); } /** @@ -93,6 +98,8 @@ public function checkGetUserByWrongTokenReturnsFalse(IntegrationTester $I) ->getToken() ; - $I->assertFalse($this->getUserByToken($token)); + /** @var Libmemcached $cache */ + $cache = $I->grabFromDi('cache'); + $I->assertFalse($this->getUserByToken($cache, $token)); } } diff --git a/tests/unit/library/Providers/CacheCest.php b/tests/unit/library/Providers/CacheCest.php new file mode 100644 index 00000000..39e434d6 --- /dev/null +++ b/tests/unit/library/Providers/CacheCest.php @@ -0,0 +1,26 @@ +register($diContainer); + + $I->assertTrue($diContainer->has('cache')); + /** @var Libmemcached $cache */ + $cache = $diContainer->getShared('cache'); + $I->assertTrue($cache instanceof Libmemcached); + } +} From ee465bd69dbe27b88a218213e3964698283b29b1 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 30 Jul 2018 14:53:41 -0400 Subject: [PATCH 54/70] Corrections for scrutinizer run --- library/Traits/QueryTrait.php | 1 + scrutinizer.yml | 4 +++- storage/ci/.env.example | 12 ++++++------ 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/library/Traits/QueryTrait.php b/library/Traits/QueryTrait.php index 362ac28d..8ff0990d 100644 --- a/library/Traits/QueryTrait.php +++ b/library/Traits/QueryTrait.php @@ -115,6 +115,7 @@ private function getResults(Libmemcached $cache, Builder $builder, array $where $params = json_encode($where); $cacheKey = sha1(sprintf('%s-%s.cache', $phql, $params)); if (true === $cache->exists($cacheKey)) { + /** @var ResultsetInterface $data */ $data = $cache->get($cacheKey); } else { $data = $builder->getQuery()->execute(); diff --git a/scrutinizer.yml b/scrutinizer.yml index f855e5a5..1b0058f2 100644 --- a/scrutinizer.yml +++ b/scrutinizer.yml @@ -8,7 +8,6 @@ build: postgresql: false redis: false node: false - selenium: false php: version: 7.1.12 ini: @@ -26,6 +25,9 @@ build: DATA_API_MYSQL_PASS: "password" DATA_API_MYSQL_USER: "root" DATA_API_MYSQL_NAME: "gonano" + DATA_API_MEMCACHED_HOST: "127.0.0.1" + DATA_API_MEMCACHED_PORT: 11211 + DATA_API_MEMCACHED_WEIGHT: 100 APP_IP: "api.phalcon.ld" cache: diff --git a/storage/ci/.env.example b/storage/ci/.env.example index cf989c78..7ee07fa8 100644 --- a/storage/ci/.env.example +++ b/storage/ci/.env.example @@ -11,13 +11,13 @@ TOKEN_AUDIENCE=https://phalconphp.com CACHE_PREFIX=api_cache_ CACHE_LIFETIME=86400 -DATA_API_MEMCACHED_HOST=127.0.0.1 -DATA_API_MEMCACHED_PORT=11211 -DATA_API_MEMCACHED_WEIGHT=100 +#DATA_API_MEMCACHED_HOST=127.0.0.1 +#DATA_API_MEMCACHED_PORT=11211 +#DATA_API_MEMCACHED_WEIGHT=100 -DATA_API_MYSQL_NAME=gonano -DATA_API_MYSQL_USER=root -DATA_API_MYSQL_PASS=password +#DATA_API_MYSQL_NAME=gonano +#DATA_API_MYSQL_USER=root +#DATA_API_MYSQL_PASS=password APP_IP=api.phalcon.ld From 32d027a0e02204fac890ce2c73e9f677d3221a9a Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Mon, 30 Jul 2018 16:43:43 -0400 Subject: [PATCH 55/70] Added conditional to not use cache in dev mode; Reworked calls to getRecords --- api/controllers/BaseController.php | 4 +- api/controllers/LoginController.php | 4 +- cli/config/providers.php | 2 + cli/tasks/ClearcacheTask.php | 64 ++++++++++++++++++- library/Middleware/TokenUserMiddleware.php | 5 +- .../Middleware/TokenValidationMiddleware.php | 5 +- .../TokenVerificationMiddleware.php | 5 +- library/Traits/QueryTrait.php | 26 +++++--- .../integration/library/Traits/QueryCest.php | 13 +++- ...ClearCacheCest.php => ClearCacheCest.php_} | 0 tests/unit/config/AutoloaderCest.php | 6 -- 11 files changed, 109 insertions(+), 25 deletions(-) rename tests/unit/cli/{ClearCacheCest.php => ClearCacheCest.php_} (100%) diff --git a/api/controllers/BaseController.php b/api/controllers/BaseController.php index 567f5b31..d2fa084d 100644 --- a/api/controllers/BaseController.php +++ b/api/controllers/BaseController.php @@ -9,6 +9,7 @@ use Niden\Traits\QueryTrait; use Niden\Traits\ResponseTrait; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Filter; use Phalcon\Mvc\Controller; use Phalcon\Mvc\Micro; @@ -23,6 +24,7 @@ * * @property Micro $application * @property Libmemcached $cache + * @property Config $config * @property Response $response */ class BaseController extends Controller @@ -58,7 +60,7 @@ public function callAction($id = 0, $relationships = '') { $parameters = $this->checkIdParameter($id); $parameter = $this->filter->sanitize($relationships, [Filter::FILTER_STRING, Filter::FILTER_TRIM]); - $results = $this->getRecords($this->cache, $this->model, $parameters, $this->orderBy); + $results = $this->getRecords($this->config, $this->cache, $this->model, $parameters, $this->orderBy); $related = []; if (count($parameters) > 0 && 0 === count($results)) { diff --git a/api/controllers/LoginController.php b/api/controllers/LoginController.php index 6585ec5b..128bb1ab 100644 --- a/api/controllers/LoginController.php +++ b/api/controllers/LoginController.php @@ -11,6 +11,7 @@ use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Filter; use Phalcon\Mvc\Controller; @@ -20,6 +21,7 @@ * @package Niden\Api\Controllers * * @property Libmemcached $cache + * @property Config $config * @property Request $request * @property Response $response */ @@ -39,7 +41,7 @@ public function callAction() $username = $this->request->getPost('username', Filter::FILTER_STRING); $password = $this->request->getPost('password', Filter::FILTER_STRING); /** @var Users|false $user */ - $user = $this->getUserByUsernameAndPassword($this->cache, $username, $password); + $user = $this->getUserByUsernameAndPassword($this->config, $this->cache, $username, $password); if (false !== $user) { /** diff --git a/cli/config/providers.php b/cli/config/providers.php index e3e7780a..bb9d637d 100644 --- a/cli/config/providers.php +++ b/cli/config/providers.php @@ -4,6 +4,7 @@ * Enabled providers. Order does matter */ +use Niden\Providers\CacheDataProvider; use Niden\Providers\CliDispatcherProvider; use Niden\Providers\ConfigProvider; use Niden\Providers\DatabaseProvider; @@ -18,4 +19,5 @@ ErrorHandlerProvider::class, DatabaseProvider::class, CliDispatcherProvider::class, + CacheDataProvider::class, ]; diff --git a/cli/tasks/ClearcacheTask.php b/cli/tasks/ClearcacheTask.php index 1c2745d0..c283a777 100755 --- a/cli/tasks/ClearcacheTask.php +++ b/cli/tasks/ClearcacheTask.php @@ -5,19 +5,38 @@ use function in_array; use function Niden\Core\appPath; +use Phalcon\Cache\Backend\Libmemcached; use Phalcon\Cli\Task as PhTask; +use const PHP_EOL; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; +/** + * Class ClearcacheTask + * + * @package Niden\Cli\Tasks + * + * @property Libmemcached $cache + */ class ClearcacheTask extends PhTask { /** - * Adds the developer logins in the system + * Clears the data cache from the application */ public function mainAction() + { + $this->clearFileCache(); + $this->clearMemCached(); + } + + /** + * Clears file based cache + */ + private function clearFileCache() { echo 'Clearing Cache folders' . PHP_EOL; + $fileList = []; $whitelist = ['.', '..', '.gitignore']; $path = appPath('storage/cache'); $dirIterator = new RecursiveDirectoryIterator($path); @@ -26,13 +45,52 @@ public function mainAction() RecursiveIteratorIterator::CHILD_FIRST ); + /** + * Get how many files we have there and where they are + */ foreach ($iterator as $file) { if (true !== $file->isDir() && true !== in_array($file->getFilename(), $whitelist)) { - unlink($file->getPathname()); - echo '.'; + $fileList[] = $file->getPathname(); } } + echo sprintf('Found %s files', count($fileList)) . PHP_EOL; + foreach ($fileList as $file) { + echo '.'; + unlink($file); + } + echo PHP_EOL . 'Cleared Cache folders' . PHP_EOL; } + + /** + * Clears memcached data cache + */ + private function clearMemCached() + { + echo 'Clearing data cache' . PHP_EOL; + $options = $this->cache->getOptions(); + $servers = $options['servers'] ?? []; + $memcached = new \Memcached(); + foreach ($servers as $server) { + $memcached->addServer($server['host'], $server['port'], $server['weight']); + } + + $keys = $memcached->getAllKeys(); + echo sprintf('Found %s keys', count($keys)) . PHP_EOL; + foreach ($keys as $key) { + if ('api-data' === substr($key, 0, 8)) { + $server = $memcached->getServerByKey($key); + $result = $memcached->deleteByKey($server['host'], $key); + $resultCode = $memcached->getResultCode(); + if (true === $result && $resultCode !== \Memcached::RES_NOTFOUND) { + echo '.'; + } else { + echo 'F'; + } + } + } + + echo PHP_EOL . 'Cleared data cache' . PHP_EOL; + } } diff --git a/library/Middleware/TokenUserMiddleware.php b/library/Middleware/TokenUserMiddleware.php index 1a7c9344..dfc314de 100755 --- a/library/Middleware/TokenUserMiddleware.php +++ b/library/Middleware/TokenUserMiddleware.php @@ -7,6 +7,7 @@ use Niden\Http\Request; use Niden\Models\Users; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Mvc\Micro; /** @@ -25,6 +26,8 @@ public function call(Micro $api) { /** @var Libmemcached $cache */ $cache = $api->getService('cache'); + /** @var Config $config */ + $config = $api->getService('config'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -35,7 +38,7 @@ public function call(Micro $api) $token = $this->getToken($request->getBearerTokenFromHeader()); /** @var Users|false $user */ - $user = $this->getUserByToken($cache, $token); + $user = $this->getUserByToken($config, $cache, $token); if (false === $user) { $this->halt($api, 200, 'Invalid Token'); diff --git a/library/Middleware/TokenValidationMiddleware.php b/library/Middleware/TokenValidationMiddleware.php index 5a0f3a7c..5b7f9e80 100755 --- a/library/Middleware/TokenValidationMiddleware.php +++ b/library/Middleware/TokenValidationMiddleware.php @@ -8,6 +8,7 @@ use Niden\Http\Request; use Niden\Models\Users; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Mvc\Micro; /** @@ -27,6 +28,8 @@ public function call(Micro $api) { /** @var Libmemcached $cache */ $cache = $api->getService('cache'); + /** @var Config $config */ + $config = $api->getService('config'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -39,7 +42,7 @@ public function call(Micro $api) $token = $this->getToken($request->getBearerTokenFromHeader()); /** @var Users $user */ - $user = $this->getUserByToken($cache, $token); + $user = $this->getUserByToken($config, $cache, $token); if (false === $token->validate($user->getValidationData())) { $this->halt($api, 200, 'Invalid Token'); diff --git a/library/Middleware/TokenVerificationMiddleware.php b/library/Middleware/TokenVerificationMiddleware.php index 86cb06b1..5c46a390 100755 --- a/library/Middleware/TokenVerificationMiddleware.php +++ b/library/Middleware/TokenVerificationMiddleware.php @@ -9,6 +9,7 @@ use Niden\Http\Request; use Niden\Models\Users; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Mvc\Micro; /** @@ -28,6 +29,8 @@ public function call(Micro $api) { /** @var Libmemcached $cache */ $cache = $api->getService('cache'); + /** @var Config $config */ + $config = $api->getService('config'); /** @var Request $request */ $request = $api->getService('request'); if (true === $this->isValidCheck($request)) { @@ -41,7 +44,7 @@ public function call(Micro $api) $signer = new Sha512(); /** @var Users $user */ - $user = $this->getUserByToken($cache, $token); + $user = $this->getUserByToken($config, $cache, $token); if (false === $token->verify($signer, $user->get('tokenPassword'))) { $this->halt($api, 200, 'Invalid Token'); } diff --git a/library/Traits/QueryTrait.php b/library/Traits/QueryTrait.php index 8ff0990d..a9f3b3a7 100644 --- a/library/Traits/QueryTrait.php +++ b/library/Traits/QueryTrait.php @@ -10,6 +10,7 @@ use Niden\Constants\JWTClaims; use Niden\Models\Users; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; use Phalcon\Mvc\Model\Query\Builder; use Phalcon\Mvc\Model\ResultsetInterface; use function sha1; @@ -24,12 +25,13 @@ trait QueryTrait /** * Gets a user from the database based on the JWT token * + * @param Config $config * @param Libmemcached $cache * @param Token $token * * @return Users|false */ - protected function getUserByToken(Libmemcached $cache, Token $token) + protected function getUserByToken(Config $config, Libmemcached $cache, Token $token) { $parameters = [ 'issuer' => $token->getClaim(JWTClaims::CLAIM_ISSUER), @@ -37,7 +39,7 @@ protected function getUserByToken(Libmemcached $cache, Token $token) 'status' => Flags::ACTIVE, ]; - $result = $this->getRecords($cache, Users::class, $parameters); + $result = $this->getRecords($config, $cache, Users::class, $parameters); return $result[0] ?? false; } @@ -45,13 +47,14 @@ protected function getUserByToken(Libmemcached $cache, Token $token) /** * Gets a user from the database based on the username and password * + * @param Config $config * @param Libmemcached $cache * @param string $username * @param string $password * * @return Users|false */ - protected function getUserByUsernameAndPassword(Libmemcached $cache, $username, $password) + protected function getUserByUsernameAndPassword(Config $config, Libmemcached $cache, $username, $password) { $parameters = [ 'username' => $username, @@ -59,7 +62,7 @@ protected function getUserByUsernameAndPassword(Libmemcached $cache, $username, 'status' => Flags::ACTIVE, ]; - $result = $this->getRecords($cache, Users::class, $parameters); + $result = $this->getRecords($config, $cache, Users::class, $parameters); return $result[0] ?? false; } @@ -67,6 +70,7 @@ protected function getUserByUsernameAndPassword(Libmemcached $cache, $username, /** * Runs a query using the builder * + * @param Config $config * @param Libmemcached $cache * @param string $class * @param array $where @@ -75,6 +79,7 @@ protected function getUserByUsernameAndPassword(Libmemcached $cache, $username, * @return ResultsetInterface */ protected function getRecords( + Config $config, Libmemcached $cache, string $class, array $where = [], @@ -94,27 +99,32 @@ protected function getRecords( $builder->orderBy($orderBy); } - return $this->getResults($cache, $builder, $where); + return $this->getResults($config, $cache, $builder, $where); } /** * Runs the builder query if there is no cached data * + * @param Config $config * @param Libmemcached $cache * @param Builder $builder * @param array $where * * @return ResultsetInterface */ - private function getResults(Libmemcached $cache, Builder $builder, array $where = []): ResultsetInterface - { + private function getResults( + Config $config, + Libmemcached $cache, + Builder $builder, + array $where = [] + ): ResultsetInterface { /** * Calculate the cache key */ $phql = $builder->getPhql(); $params = json_encode($where); $cacheKey = sha1(sprintf('%s-%s.cache', $phql, $params)); - if (true === $cache->exists($cacheKey)) { + if (true !== $config->path('app.devMode') && true === $cache->exists($cacheKey)) { /** @var ResultsetInterface $data */ $data = $cache->get($cacheKey); } else { diff --git a/tests/integration/library/Traits/QueryCest.php b/tests/integration/library/Traits/QueryCest.php index b8dfe6f0..fab0ecb1 100644 --- a/tests/integration/library/Traits/QueryCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -10,6 +10,7 @@ use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; use Phalcon\Cache\Backend\Libmemcached; +use Phalcon\Config; /** * Class QueryCest @@ -40,7 +41,9 @@ public function checkGetUserByUsernameAndPassword(IntegrationTester $I) /** @var Libmemcached $cache */ $cache = $I->grabFromDi('cache'); - $dbUser = $this->getUserByUsernameAndPassword($cache, 'testusername', 'testpass'); + /** @var Config $config */ + $config = $I->grabFromDi('config'); + $dbUser = $this->getUserByUsernameAndPassword($config, $cache, 'testusername', 'testpass'); $I->assertNotEquals(false, $dbUser); } @@ -66,7 +69,9 @@ public function checkGetUserByWrongUsernameAndPasswordReturnsFalse(IntegrationTe /** @var Libmemcached $cache */ $cache = $I->grabFromDi('cache'); - $I->assertFalse($this->getUserByUsernameAndPassword($cache, 'testusername', 'nothing')); + /** @var Config $config */ + $config = $I->grabFromDi('config'); + $I->assertFalse($this->getUserByUsernameAndPassword($config, $cache, 'testusername', 'nothing')); } /** @@ -100,6 +105,8 @@ public function checkGetUserByWrongTokenReturnsFalse(IntegrationTester $I) /** @var Libmemcached $cache */ $cache = $I->grabFromDi('cache'); - $I->assertFalse($this->getUserByToken($cache, $token)); + /** @var Config $config */ + $config = $I->grabFromDi('config'); + $I->assertFalse($this->getUserByToken($config, $cache, $token)); } } diff --git a/tests/unit/cli/ClearCacheCest.php b/tests/unit/cli/ClearCacheCest.php_ similarity index 100% rename from tests/unit/cli/ClearCacheCest.php rename to tests/unit/cli/ClearCacheCest.php_ diff --git a/tests/unit/config/AutoloaderCest.php b/tests/unit/config/AutoloaderCest.php index 5c5f20e7..860abc1b 100755 --- a/tests/unit/config/AutoloaderCest.php +++ b/tests/unit/config/AutoloaderCest.php @@ -22,9 +22,6 @@ public function checkDotenvVariables(UnitTester $I) $I->assertNotEquals(false, getenv('APP_TIMEZONE')); $I->assertNotEquals(false, getenv('CACHE_PREFIX')); $I->assertNotEquals(false, getenv('CACHE_LIFETIME')); - $I->assertNotEquals(false, getenv('DATA_API_MEMCACHED_HOST')); - $I->assertNotEquals(false, getenv('DATA_API_MEMCACHED_PORT')); - $I->assertNotEquals(false, getenv('DATA_API_MEMCACHED_WEIGHT')); $I->assertNotEquals(false, getenv('DATA_API_MYSQL_NAME')); $I->assertNotEquals(false, getenv('LOGGER_DEFAULT_FILENAME')); $I->assertNotEquals(false, getenv('VERSION')); @@ -37,9 +34,6 @@ public function checkDotenvVariables(UnitTester $I) $I->assertEquals('UTC', getenv('APP_TIMEZONE')); $I->assertEquals('api_cache_', getenv('CACHE_PREFIX')); $I->assertEquals(86400, getenv('CACHE_LIFETIME')); - $I->assertEquals(11211, getenv('DATA_API_MEMCACHED_PORT')); - $I->assertEquals(100, getenv('DATA_API_MEMCACHED_WEIGHT')); - $I->assertEquals('gonano', getenv('DATA_API_MYSQL_NAME')); $I->assertEquals('api', getenv('LOGGER_DEFAULT_FILENAME')); $I->assertEquals('20180401', getenv('VERSION')); } From eec12a5eccfc2497a6999ebce11db5e4788de93e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 1 Aug 2018 16:41:46 -0400 Subject: [PATCH 56/70] Added more tests for the cached data when getting records --- storage/ci/.env.example | 2 +- storage/ci/.env.prod | 12 +- tests/_support/Helper/Integration.php | 10 ++ tests/api/Companies/GetCachedCest.php | 138 ++++++++++++++++++ tests/api/Companies/GetCest.php | 5 +- .../integration/library/Traits/QueryCest.php | 60 ++++++++ ...ClearCacheCest.php_ => ClearCacheCest.php} | 3 + 7 files changed, 222 insertions(+), 8 deletions(-) create mode 100644 tests/api/Companies/GetCachedCest.php rename tests/unit/cli/{ClearCacheCest.php_ => ClearCacheCest.php} (90%) diff --git a/storage/ci/.env.example b/storage/ci/.env.example index 7ee07fa8..6fd5bfe5 100644 --- a/storage/ci/.env.example +++ b/storage/ci/.env.example @@ -15,7 +15,7 @@ CACHE_LIFETIME=86400 #DATA_API_MEMCACHED_PORT=11211 #DATA_API_MEMCACHED_WEIGHT=100 -#DATA_API_MYSQL_NAME=gonano +DATA_API_MYSQL_NAME=gonano #DATA_API_MYSQL_USER=root #DATA_API_MYSQL_PASS=password diff --git a/storage/ci/.env.prod b/storage/ci/.env.prod index edcaad85..0b1228e1 100644 --- a/storage/ci/.env.prod +++ b/storage/ci/.env.prod @@ -11,13 +11,15 @@ TOKEN_AUDIENCE=https://phalconphp.com CACHE_PREFIX=api_cache_ CACHE_LIFETIME=86400 -DATA_API_MEMCACHED_HOST=127.0.0.1 -DATA_API_MEMCACHED_PORT=11211 -DATA_API_MEMCACHED_WEIGHT=100 +#DATA_API_MEMCACHED_HOST=127.0.0.1 +#DATA_API_MEMCACHED_PORT=11211 +#DATA_API_MEMCACHED_WEIGHT=100 DATA_API_MYSQL_NAME=gonano -DATA_API_MYSQL_USER=phalcon -DATA_API_MYSQL_PASS=secret +#DATA_API_MYSQL_USER=root +#DATA_API_MYSQL_PASS=password + +APP_IP=api.phalcon.ld LOGGER_DEFAULT_FILENAME=api diff --git a/tests/_support/Helper/Integration.php b/tests/_support/Helper/Integration.php index 7dd45049..0eaf32e8 100644 --- a/tests/_support/Helper/Integration.php +++ b/tests/_support/Helper/Integration.php @@ -54,6 +54,16 @@ public function _after(TestInterface $test) $this->diContainer->get('db')->close(); } + /** + * @param string $name + * + * @return mixed + */ + public function grabDi() + { + return $this->diContainer; + } + /** * @param string $name * diff --git a/tests/api/Companies/GetCachedCest.php b/tests/api/Companies/GetCachedCest.php new file mode 100644 index 00000000..438c1320 --- /dev/null +++ b/tests/api/Companies/GetCachedCest.php @@ -0,0 +1,138 @@ +assertTrue($result); + + } + + public function _after(ApiTester $I) + { + /** + * Manipulate the .env file to simulate production + */ + $result = copy(appPath('./storage/ci/.env.example'), appPath('./.env')); + $I->assertTrue($result); + } + + public function getCompaniesWithCache(ApiTester $I) + { + /** @var Config $config */ + $config = $I->grabFromDi('config'); + $I->assertFalse($config->path('app.devMode')); + + /** + * Login + */ + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** + * Company 1 + */ + $comName = uniqid('com-cached-'); + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => $comName, + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + /** + * Get the company - should see "com-cached" -> save to cache + */ + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'id' => $comOne->get('id'), + 'type' => Relationships::COMPANIES, + 'attributes' => [ + 'name' => $comName, + 'address' => $comOne->get('address'), + 'city' => $comOne->get('city'), + 'phone' => $comOne->get('phone'), + ], + ], + ] + ); + + /** + * Get the company again - should see "com-cached" -> should get cached + */ + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'id' => $comOne->get('id'), + 'type' => Relationships::COMPANIES, + 'attributes' => [ + 'name' => $comName, + 'address' => $comOne->get('address'), + 'city' => $comOne->get('city'), + 'phone' => $comOne->get('phone'), + ], + ], + ] + ); + + /** + * Change the name in the database + */ + $result = $comOne->set('name', 'no-cache-name')->save(); + $I->assertNotEquals(false, $result); + +// /** +// * Call the get again and check if we get cached data or not +// */ +// $I->haveHttpHeader('Authorization', 'Bearer ' . $token); +// $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); +// $I->deleteHeader('Authorization'); +// $I->seeResponseIsSuccessful(); +// $I->seeSuccessJsonResponse( +// 'data', +// [ +// [ +// 'id' => $comOne->get('id'), +// 'type' => Relationships::COMPANIES, +// 'attributes' => [ +// 'name' => $comName, +// 'address' => $comOne->get('address'), +// 'city' => $comOne->get('city'), +// 'phone' => $comOne->get('phone'), +// ], +// ], +// ] +// ); + } +} + diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 92acc770..6d2952c9 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -10,6 +10,7 @@ use Niden\Models\Products; use Niden\Models\ProductTypes; use Page\Data; +use function sprintf; use function uniqid; class GetCest @@ -29,7 +30,7 @@ public function getCompany(ApiTester $I) ] ); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id')); + $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -55,7 +56,7 @@ public function getUnknownCompany(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/9999'); + $I->sendGET(sprintf(Data::$companiesRecordUrl, 9999)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } diff --git a/tests/integration/library/Traits/QueryCest.php b/tests/integration/library/Traits/QueryCest.php index fab0ecb1..6d19fc83 100644 --- a/tests/integration/library/Traits/QueryCest.php +++ b/tests/integration/library/Traits/QueryCest.php @@ -5,7 +5,9 @@ use IntegrationTester; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Signer\Hmac\Sha512; +use function Niden\Core\appPath; use Niden\Exception\ModelException; +use Niden\Models\Companies; use Niden\Models\Users; use Niden\Traits\QueryTrait; use Niden\Traits\TokenTrait; @@ -109,4 +111,62 @@ public function checkGetUserByWrongTokenReturnsFalse(IntegrationTester $I) $config = $I->grabFromDi('config'); $I->assertFalse($this->getUserByToken($config, $cache, $token)); } + + public function getCompaniesCachedData(IntegrationTester $I) + { + $configData = require appPath('./library/Core/config.php'); + $I->assertTrue($configData['app']['devMode']); + + $configData['app']['devMode'] = false; + /** @var Config $config */ + $config = new Config($configData); + $container = $I->grabDi(); + $container->set('config', $config); + $I->assertFalse($config->path('app.devMode')); + + /** @var Libmemcached $cache */ + $cache = $I->grabFromDi('cache'); + /** @var Config $config */ + $config = $I->grabFromDi('config'); + $I->assertFalse($config->path('app.devMode')); + + /** + * Company 1 + */ + $comName = uniqid('com-cached-'); + $comOne = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => $comName, + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + $results = $this->getRecords($config, $cache, Companies::class); + $I->assertEquals(1, count($results)); + $I->assertEquals($comName, $results[0]->get('name')); + $I->assertEquals($comOne->get('address'), $results[0]->get('address')); + $I->assertEquals($comOne->get('city'), $results[0]->get('city')); + $I->assertEquals($comOne->get('phone'), $results[0]->get('phone')); + + /** + * Get the record again but ensure the name has been changed + */ + $result = $comOne->set('name', 'com-cached-change')->save(); + $I->assertNotEquals(false, $result); + + /** + * This should return the cached result + */ + $results = $this->getRecords($config, $cache, Companies::class); + $I->assertEquals(1, count($results)); + $I->assertEquals($comName, $results[0]->get('name')); + $I->assertEquals($comOne->get('address'), $results[0]->get('address')); + $I->assertEquals($comOne->get('city'), $results[0]->get('city')); + $I->assertEquals($comOne->get('phone'), $results[0]->get('phone')); + + + } } diff --git a/tests/unit/cli/ClearCacheCest.php_ b/tests/unit/cli/ClearCacheCest.php similarity index 90% rename from tests/unit/cli/ClearCacheCest.php_ rename to tests/unit/cli/ClearCacheCest.php index 311208e7..292ad738 100755 --- a/tests/unit/cli/ClearCacheCest.php_ +++ b/tests/unit/cli/ClearCacheCest.php @@ -4,6 +4,7 @@ use FilesystemIterator; use Niden\Cli\Tasks\ClearcacheTask; +use Niden\Providers\CacheDataProvider; use Phalcon\Di\FactoryDefault\Cli; use UnitTester; use function fclose; @@ -22,6 +23,8 @@ public function checkClearCache(UnitTester $I) $path = appPath('/storage/cache/data'); $container = new Cli(); + $cache = new CacheDataProvider(); + $cache->register($container); $task = new ClearcacheTask(); $task->setDI($container); From d2a5c3ea015508ce27e17ca559a28ef586c41827 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Wed, 1 Aug 2018 17:06:34 -0400 Subject: [PATCH 57/70] Removed obsolete test --- tests/api/Companies/GetCachedCest.php | 138 -------------------------- 1 file changed, 138 deletions(-) delete mode 100644 tests/api/Companies/GetCachedCest.php diff --git a/tests/api/Companies/GetCachedCest.php b/tests/api/Companies/GetCachedCest.php deleted file mode 100644 index 438c1320..00000000 --- a/tests/api/Companies/GetCachedCest.php +++ /dev/null @@ -1,138 +0,0 @@ -assertTrue($result); - - } - - public function _after(ApiTester $I) - { - /** - * Manipulate the .env file to simulate production - */ - $result = copy(appPath('./storage/ci/.env.example'), appPath('./.env')); - $I->assertTrue($result); - } - - public function getCompaniesWithCache(ApiTester $I) - { - /** @var Config $config */ - $config = $I->grabFromDi('config'); - $I->assertFalse($config->path('app.devMode')); - - /** - * Login - */ - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - /** - * Company 1 - */ - $comName = uniqid('com-cached-'); - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => $comName, - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); - - /** - * Get the company - should see "com-cached" -> save to cache - */ - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse( - 'data', - [ - [ - 'id' => $comOne->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comName, - 'address' => $comOne->get('address'), - 'city' => $comOne->get('city'), - 'phone' => $comOne->get('phone'), - ], - ], - ] - ); - - /** - * Get the company again - should see "com-cached" -> should get cached - */ - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); - $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse( - 'data', - [ - [ - 'id' => $comOne->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comName, - 'address' => $comOne->get('address'), - 'city' => $comOne->get('city'), - 'phone' => $comOne->get('phone'), - ], - ], - ] - ); - - /** - * Change the name in the database - */ - $result = $comOne->set('name', 'no-cache-name')->save(); - $I->assertNotEquals(false, $result); - -// /** -// * Call the get again and check if we get cached data or not -// */ -// $I->haveHttpHeader('Authorization', 'Bearer ' . $token); -// $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); -// $I->deleteHeader('Authorization'); -// $I->seeResponseIsSuccessful(); -// $I->seeSuccessJsonResponse( -// 'data', -// [ -// [ -// 'id' => $comOne->get('id'), -// 'type' => Relationships::COMPANIES, -// 'attributes' => [ -// 'name' => $comName, -// 'address' => $comOne->get('address'), -// 'city' => $comOne->get('city'), -// 'phone' => $comOne->get('phone'), -// ], -// ], -// ] -// ); - } -} - From a6ee0965110abecdffd0de117de5f62cee2f6451 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 09:54:26 -0400 Subject: [PATCH 58/70] Refactored test responses --- tests/_support/Page/Data.php | 153 ++++++++++++++++++++++++++ tests/api/Companies/AddCest.php | 19 ++-- tests/api/Companies/GetCest.php | 100 ++++++----------- tests/api/IndividualTypes/GetCest.php | 31 +++--- tests/api/ProductTypes/GetCest.php | 92 ++++++---------- tests/api/Products/GetCest.php | 106 ++++++------------ tests/api/Users/GetCest.php | 36 +----- 7 files changed, 278 insertions(+), 259 deletions(-) diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index 2f6e2e25..5bf8d5e4 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -2,6 +2,10 @@ namespace Page; +use Niden\Constants\Relationships; +use function Niden\Core\envValue; +use Niden\Mvc\Model\AbstractModel; + class Data { public static $companiesUrl = '/companies'; @@ -24,6 +28,9 @@ class Data public static $usersUrl = '/users'; public static $wrongUrl = '/sommething'; + /** + * @return array + */ public static function loginJson() { return [ @@ -32,6 +39,14 @@ public static function loginJson() ]; } + /** + * @param $name + * @param string $address + * @param string $city + * @param string $phone + * + * @return array + */ public static function companyAddJson($name, $address = '', $city = '', $phone = '') { return [ @@ -41,4 +56,142 @@ public static function companyAddJson($name, $address = '', $city = '', $phone = 'phone' => $phone, ]; } + + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function companyResponse(AbstractModel $record) + { + return [ + 'id' => $record->get('id'), + 'type' => Relationships::COMPANIES, + 'attributes' => [ + 'name' => $record->get('name'), + 'address' => $record->get('address'), + 'city' => $record->get('city'), + 'phone' => $record->get('phone'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::COMPANIES, + $record->get('id') + ), + ], + ]; + } + + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function individualTypeResponse(AbstractModel $record) + { + return [ + 'id' => $record->get('id'), + 'type' => Relationships::INDIVIDUAL_TYPES, + 'attributes' => [ + 'name' => $record->get('name'), + 'description' => $record->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUAL_TYPES, + $record->get('id') + ), + ], + ]; + } + + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function productResponse(AbstractModel $record) + { + return [ + 'type' => Relationships::PRODUCTS, + 'id' => $record->get('id'), + 'attributes' => [ + 'typeId' => $record->get('typeId'), + 'name' => $record->get('name'), + 'description' => $record->get('description'), + 'quantity' => $record->get('quantity'), + 'price' => $record->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCTS, + $record->get('id') + ), + ], + ]; + } + + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function productTypeResponse(AbstractModel $record) + { + return [ + 'id' => $record->get('id'), + 'type' => Relationships::PRODUCT_TYPES, + 'attributes' => [ + 'name' => $record->get('name'), + 'description' => $record->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::PRODUCT_TYPES, + $record->get('id') + ), + ], + ]; + } + + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function userResponse(AbstractModel $record) + { + return [ + 'id' => $record->get('id'), + 'type' => Relationships::USERS, + 'attributes' => [ + 'status' => $record->get('status'), + 'username' => $record->get('username'), + 'issuer' => $record->get('issuer'), + 'tokenPassword' => $record->get('tokenPassword'), + 'tokenId' => $record->get('tokenId'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::USERS, + $record->get('id') + ), + ], + ]; + } } diff --git a/tests/api/Companies/AddCest.php b/tests/api/Companies/AddCest.php index ac57b326..fde635a7 100644 --- a/tests/api/Companies/AddCest.php +++ b/tests/api/Companies/AddCest.php @@ -10,6 +10,11 @@ class AddCest { + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function addNewCompany(ApiTester $I) { $I->addApiUserRecord(); @@ -40,22 +45,16 @@ public function addNewCompany(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $company->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $company->get('name'), - 'address' => $company->get('address'), - 'city' => $company->get('city'), - 'phone' => $company->get('phone'), - ], - ], + Data::companyResponse($company), ] ); $I->assertNotEquals(false, $company->delete()); } + /** + * @param ApiTester $I + */ public function addNewCompanyWithExistingName(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 6d2952c9..02a2f9f0 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -15,6 +15,11 @@ class GetCest { + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getCompany(ApiTester $I) { $I->addApiUserRecord(); @@ -36,20 +41,14 @@ public function getCompany(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $comOne->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comOne->get('name'), - 'address' => $comOne->get('address'), - 'city' => $comOne->get('city'), - 'phone' => $comOne->get('phone'), - ], - ], + Data::companyResponse($comOne), ] ); } + /** + * @param ApiTester $I + */ public function getUnknownCompany(ApiTester $I) { $I->addApiUserRecord(); @@ -61,6 +60,11 @@ public function getUnknownCompany(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getCompanies(ApiTester $I) { $I->addApiUserRecord(); @@ -91,40 +95,33 @@ public function getCompanies(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $comOne->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comOne->get('name'), - 'address' => $comOne->get('address'), - 'city' => $comOne->get('city'), - 'phone' => $comOne->get('phone'), - ], - ], - [ - 'id' => $comTwo->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comTwo->get('name'), - 'address' => $comTwo->get('address'), - 'city' => $comTwo->get('city'), - 'phone' => $comTwo->get('phone'), - ], - ], + Data::companyResponse($comOne), + Data::companyResponse($comTwo), ] ); } + /** + * @param ApiTester $I + */ public function getCompaniesWithRelationshipProducts(ApiTester $I) { $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); } + /** + * @param ApiTester $I + */ public function getCompaniesWithProducts(ApiTester $I) { $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipUrl); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getCompaniesWithUnknownRelationship(ApiTester $I) { $I->addApiUserRecord(); @@ -195,6 +192,9 @@ public function getCompaniesWithUnknownRelationship(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + */ public function getCompaniesNoData(ApiTester $I) { $I->addApiUserRecord(); @@ -340,44 +340,8 @@ private function runCompaniesWithProductsTests(ApiTester $I, $url = '') $I->seeSuccessJsonResponse( 'included', [ - [ - 'type' => Relationships::PRODUCTS, - 'id' => $productOne->get('id'), - 'attributes' => [ - 'typeId' => $productOne->get('typeId'), - 'name' => $productOne->get('name'), - 'description' => $productOne->get('description'), - 'quantity' => $productOne->get('quantity'), - 'price' => $productOne->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL'), - Relationships::PRODUCTS, - $productOne->get('id') - ), - ], - ], - [ - 'type' => Relationships::PRODUCTS, - 'id' => $productTwo->get('id'), - 'attributes' => [ - 'typeId' => $productTwo->get('typeId'), - 'name' => $productTwo->get('name'), - 'description' => $productTwo->get('description'), - 'quantity' => $productTwo->get('quantity'), - 'price' => $productTwo->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL'), - Relationships::PRODUCTS, - $productTwo->get('id') - ), - ], - ], + Data::productResponse($productOne), + Data::productResponse($productTwo), ] ); } diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index 6dff6569..50223afb 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -3,13 +3,17 @@ namespace Niden\Tests\api\IndividualTypes; use ApiTester; -use Niden\Constants\Relationships; use Niden\Models\IndividualTypes; use Page\Data; use function uniqid; class GetCest { + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getIndividualTypes(ApiTester $I) { $I->addApiUserRecord(); @@ -33,29 +37,19 @@ public function getIndividualTypes(ApiTester $I) $I->sendGET(Data::$individualTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $typeOne->get('id'), - 'type' => Relationships::INDIVIDUAL_TYPES, - 'attributes' => [ - 'name' => $typeOne->get('name'), - 'description' => $typeOne->get('description'), - ], - ], - [ - 'id' => $typeTwo->get('id'), - 'type' => Relationships::INDIVIDUAL_TYPES, - 'attributes' => [ - 'name' => $typeTwo->get('name'), - 'description' => $typeTwo->get('description'), - ], - ], + Data::individualTypeResponse($typeOne), + Data::individualTypeResponse($typeTwo), ] ); } + /** + * @param ApiTester $I + */ public function getUnknownIndividualTypes(ApiTester $I) { $I->addApiUserRecord(); @@ -67,6 +61,9 @@ public function getUnknownIndividualTypes(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + */ public function getIndividualTypesNoData(ApiTester $I) { $I->addApiUserRecord(); diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index 0a34e467..612a67eb 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -12,6 +12,11 @@ class GetCest { + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProductTypes(ApiTester $I) { $I->addApiUserRecord(); @@ -38,26 +43,15 @@ public function getProductTypes(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $typeOne->get('id'), - 'type' => Relationships::PRODUCT_TYPES, - 'attributes' => [ - 'name' => $typeOne->get('name'), - 'description' => $typeOne->get('description'), - ], - ], - [ - 'id' => $typeTwo->get('id'), - 'type' => Relationships::PRODUCT_TYPES, - 'attributes' => [ - 'name' => $typeTwo->get('name'), - 'description' => $typeTwo->get('description'), - ], - ], + Data::productTypeResponse($typeOne), + Data::productTypeResponse($typeTwo), ] ); } + /** + * @param ApiTester $I + */ public function getUnknownProductTypes(ApiTester $I) { $I->addApiUserRecord(); @@ -69,17 +63,29 @@ public function getUnknownProductTypes(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProductTypesWithRelationshipProducts(ApiTester $I) { - var_dump(Data::$productTypesRecordRelationshipUrl); $this->runProductTypesWithProductsTests($I, Data::$productTypesRecordRelationshipUrl); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProductTypesWithProducts(ApiTester $I) { $this->runProductTypesWithProductsTests($I, Data::$productTypesRecordRelationshipRelationshipUrl); } + /** + * @param ApiTester $I + */ public function getProductTypesNoData(ApiTester $I) { $I->addApiUserRecord(); @@ -92,6 +98,12 @@ public function getProductTypesNoData(ApiTester $I) $I->seeSuccessJsonResponse(); } + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ private function runProductTypesWithProductsTests(ApiTester $I, $url) { $I->addApiUserRecord(); @@ -127,12 +139,6 @@ private function runProductTypesWithProductsTests(ApiTester $I, $url) 'price' => 19.99, ] ); - var_dump($url); - var_dump(sprintf( - $url, - $productType->get('id'), - Relationships::PRODUCTS - )); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET( sprintf( @@ -199,44 +205,8 @@ private function runProductTypesWithProductsTests(ApiTester $I, $url) $I->seeSuccessJsonResponse( 'included', [ - [ - 'type' => Relationships::PRODUCTS, - 'id' => $productOne->get('id'), - 'attributes' => [ - 'typeId' => $productOne->get('typeId'), - 'name' => $productOne->get('name'), - 'description' => $productOne->get('description'), - 'quantity' => $productOne->get('quantity'), - 'price' => $productOne->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL'), - Relationships::PRODUCTS, - $productOne->get('id') - ), - ], - ], - [ - 'type' => Relationships::PRODUCTS, - 'id' => $productTwo->get('id'), - 'attributes' => [ - 'typeId' => $productTwo->get('typeId'), - 'name' => $productTwo->get('name'), - 'description' => $productTwo->get('description'), - 'quantity' => $productTwo->get('quantity'), - 'price' => $productTwo->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL'), - Relationships::PRODUCTS, - $productTwo->get('id') - ), - ], - ], + Data::productResponse($productOne), + Data::productResponse($productTwo), ] ); } diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index e6c8d65d..9f9a86b1 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -12,6 +12,11 @@ class GetCest { + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProduct(ApiTester $I) { $I->addApiUserRecord(); @@ -45,28 +50,14 @@ public function getProduct(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $product->get('id'), - 'type' => Relationships::PRODUCTS, - 'attributes' => [ - 'name' => $product->get('name'), - 'typeId' => $productType->get('id'), - 'description' => $product->get('description'), - 'quantity' => $product->get('quantity'), - 'price' => $product->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/products/%s', - envValue('APP_URL', 'localhost'), - $product->get('id') - ), - ], - ], + Data::productResponse($product), ] ); } + /** + * @param ApiTester $I + */ public function getUnknownProduct(ApiTester $I) { $I->addApiUserRecord(); @@ -78,6 +69,11 @@ public function getUnknownProduct(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProducts(ApiTester $I) { $I->addApiUserRecord(); @@ -123,56 +119,35 @@ public function getProducts(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $productOne->get('id'), - 'type' => Relationships::PRODUCTS, - 'attributes' => [ - 'name' => $productOne->get('name'), - 'typeId' => $productType->get('id'), - 'description' => $productOne->get('description'), - 'quantity' => $productOne->get('quantity'), - 'price' => $productOne->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/products/%s', - envValue('APP_URL', 'localhost'), - $productOne->get('id') - ), - ], - ], - [ - 'id' => $productTwo->get('id'), - 'type' => Relationships::PRODUCTS, - 'attributes' => [ - 'name' => $productTwo->get('name'), - 'typeId' => $productType->get('id'), - 'description' => $productTwo->get('description'), - 'quantity' => $productTwo->get('quantity'), - 'price' => $productTwo->get('price'), - ], - 'links' => [ - 'self' => sprintf( - '%s/products/%s', - envValue('APP_URL', 'localhost'), - $productTwo->get('id') - ), - ], - ], + Data::productResponse($productOne), + Data::productResponse($productTwo), ] ); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProductsWithProductTypes(ApiTester $I) { $this->runProductsWithProductTypesTests($I, Data::$productsRecordRelationshipRelationshipUrl); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ public function getProductsWithRelationshipProductTypes(ApiTester $I) { $this->runProductsWithProductTypesTests($I, Data::$productsRecordRelationshipUrl); } + /** + * @param ApiTester $I + */ public function getProductsNoData(ApiTester $I) { $I->addApiUserRecord(); @@ -185,6 +160,12 @@ public function getProductsNoData(ApiTester $I) $I->seeSuccessJsonResponse(); } + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ private function runProductsWithProductTypesTests(ApiTester $I, $url) { /** @var ProductTypes $productType */ @@ -273,22 +254,7 @@ private function runProductsWithProductTypesTests(ApiTester $I, $url) $I->seeSuccessJsonResponse( 'included', [ - [ - 'type' => Relationships::PRODUCT_TYPES, - 'id' => $productType->get('id'), - 'attributes' => [ - 'name' => $productType->get('name'), - 'description' => $productType->get('description'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - envValue('APP_URL', 'localhost'), - Relationships::PRODUCT_TYPES, - $productType->get('id') - ), - ], - ], + Data::productTypeResponse($productType), ] ); } diff --git a/tests/api/Users/GetCest.php b/tests/api/Users/GetCest.php index 995196e1..946f7ea3 100644 --- a/tests/api/Users/GetCest.php +++ b/tests/api/Users/GetCest.php @@ -173,17 +173,7 @@ public function loginKnownUserValidToken(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $record->get('id'), - 'type' => Relationships::USERS, - 'attributes' => [ - 'status' => $record->get('status'), - 'username' => $record->get('username'), - 'issuer' => $record->get('issuer'), - 'tokenPassword' => $record->get('tokenPassword'), - 'tokenId' => $record->get('tokenId'), - ], - ], + Data::userResponse($record), ] ); } @@ -223,28 +213,8 @@ public function getManyUsers(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - [ - 'id' => $userOne->get('id'), - 'type' => Relationships::USERS, - 'attributes' => [ - 'status' => $userOne->get('status'), - 'username' => $userOne->get('username'), - 'issuer' => $userOne->get('issuer'), - 'tokenPassword' => $userOne->get('tokenPassword'), - 'tokenId' => $userOne->get('tokenId'), - ], - ], - [ - 'id' => $userTwo->get('id'), - 'type' => Relationships::USERS, - 'attributes' => [ - 'status' => $userTwo->get('status'), - 'username' => $userTwo->get('username'), - 'issuer' => $userTwo->get('issuer'), - 'tokenPassword' => $userTwo->get('tokenPassword'), - 'tokenId' => $userTwo->get('tokenId'), - ], - ], + Data::userResponse($userOne), + Data::userResponse($userTwo), ] ); } From cdd559ae76b805ea8bd1878660538587cf028e48 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 10:08:21 -0400 Subject: [PATCH 59/70] Changed relationship to its plural form (product types/individual types) --- library/Constants/Relationships.php | 2 -- library/Models/IndividualTypes.php | 2 +- library/Models/Individuals.php | 2 +- library/Models/Products.php | 2 +- library/Transformers/ProductsTransformer.php | 2 +- .../library/Models/IndividualTypesCest.php | 2 +- .../library/Models/IndividualsCest.php | 2 +- .../library/Models/ProductsCest.php | 2 +- .../Transformers/ProductsTransformerCest.php | 18 ++---------------- .../library/Constants/RelationshipsCest.php | 2 -- 10 files changed, 9 insertions(+), 27 deletions(-) diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php index a3e88df0..448d98a0 100644 --- a/library/Constants/Relationships.php +++ b/library/Constants/Relationships.php @@ -9,11 +9,9 @@ class Relationships const COMPANY = 'company'; const COMPANIES = 'companies'; const INDIVIDUAL = 'individual'; - const INDIVIDUAL_TYPE = 'individual-type'; const INDIVIDUAL_TYPES = 'individual-types'; const INDIVIDUALS = 'individuals'; const PRODUCT = 'product'; - const PRODUCT_TYPE = 'product-type'; const PRODUCT_TYPES = 'product-types'; const PRODUCTS = 'products'; const USERS = 'users'; diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php index 8d1fd98e..a0f95279 100644 --- a/library/Models/IndividualTypes.php +++ b/library/Models/IndividualTypes.php @@ -25,7 +25,7 @@ public function initialize() Individuals::class, 'typeId', [ - 'alias' => Relationships::INDIVIDUAL, + 'alias' => Relationships::INDIVIDUALS, 'reusable' => true, ] ); diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php index e13f7538..23aa91ee 100644 --- a/library/Models/Individuals.php +++ b/library/Models/Individuals.php @@ -35,7 +35,7 @@ public function initialize() IndividualTypes::class, 'id', [ - 'alias' => Relationships::INDIVIDUAL_TYPE, + 'alias' => Relationships::INDIVIDUAL_TYPES, 'reusable' => true, ] ); diff --git a/library/Models/Products.php b/library/Models/Products.php index ec0424fc..8e970134 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -38,7 +38,7 @@ public function initialize() ProductTypes::class, 'id', [ - 'alias' => Relationships::PRODUCT_TYPE, + 'alias' => Relationships::PRODUCT_TYPES, 'reusable' => true, ] ); diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php index 7b392250..151a9a18 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php @@ -46,7 +46,7 @@ public function includeCompanies(Products $product) public function includeProductTypes(Products $product) { /** @var ProductTypes $productType */ - $productType = $product->getRelated(Relationships::PRODUCT_TYPE); + $productType = $product->getRelated(Relationships::PRODUCT_TYPES); return $this->item($productType, new BaseTransformer(), Relationships::PRODUCT_TYPES); } diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index 47bb24ce..93ce9b28 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -37,7 +37,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(IndividualTypes::class); $expected = [ - [0, 'id', Individuals::class, 'typeId', ['alias' => Relationships::INDIVIDUAL, 'reusable' => true]], + [0, 'id', Individuals::class, 'typeId', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php index a9f7582c..25e5d7c2 100644 --- a/tests/integration/library/Models/IndividualsCest.php +++ b/tests/integration/library/Models/IndividualsCest.php @@ -49,7 +49,7 @@ public function validateRelationships(IntegrationTester $I) $actual = $I->getModelRelationships(Individuals::class); $expected = [ [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], - [1, 'typeId', IndividualTypes::class, 'id', ['alias' => Relationships::INDIVIDUAL_TYPE, 'reusable' => true]], + [1, 'typeId', IndividualTypes::class, 'id', ['alias' => Relationships::INDIVIDUAL_TYPES, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/ProductsCest.php b/tests/integration/library/Models/ProductsCest.php index dadc642b..acafcdb6 100644 --- a/tests/integration/library/Models/ProductsCest.php +++ b/tests/integration/library/Models/ProductsCest.php @@ -43,7 +43,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Products::class); $expected = [ - [0, 'typeId', ProductTypes::class, 'id', ['alias' => Relationships::PRODUCT_TYPE, 'reusable' => true]], + [0, 'typeId', ProductTypes::class, 'id', ['alias' => Relationships::PRODUCT_TYPES, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php index f3f3e582..ef7bb08d 100644 --- a/tests/integration/library/Transformers/ProductsTransformerCest.php +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -11,6 +11,7 @@ use Niden\Models\ProductTypes; use Niden\Transformers\ProductsTransformer; use function Niden\Core\envValue; +use Page\Data; class ProductsTransformerCest { @@ -95,22 +96,7 @@ public function checkTransformer(IntegrationTester $I) ], ], 'included' => [ - [ - 'type' => Relationships::PRODUCT_TYPES, - 'id' => $productType->get('id'), - 'attributes' => [ - 'name' => $productType->get('name'), - 'description' => $productType->get('description'), - ], - 'links' => [ - 'self' => sprintf( - '%s/%s/%s', - $url, - Relationships::PRODUCT_TYPES, - $productType->get('id') - ), - ], - ], + Data::productTypeResponse($productType), ], ]; diff --git a/tests/unit/library/Constants/RelationshipsCest.php b/tests/unit/library/Constants/RelationshipsCest.php index 2b8ead2a..28a4fa67 100644 --- a/tests/unit/library/Constants/RelationshipsCest.php +++ b/tests/unit/library/Constants/RelationshipsCest.php @@ -12,11 +12,9 @@ public function checkConstants(CliTester $I) $I->assertEquals('company', Relationships::COMPANY); $I->assertEquals('companies', Relationships::COMPANIES); $I->assertEquals('individual', Relationships::INDIVIDUAL); - $I->assertEquals('individual-type', Relationships::INDIVIDUAL_TYPE); $I->assertEquals('individual-types', Relationships::INDIVIDUAL_TYPES); $I->assertEquals('individuals', Relationships::INDIVIDUALS); $I->assertEquals('product', Relationships::PRODUCT); - $I->assertEquals('product-type', Relationships::PRODUCT_TYPE); $I->assertEquals('product-types', Relationships::PRODUCT_TYPES); $I->assertEquals('products', Relationships::PRODUCTS); $I->assertEquals('users', Relationships::USERS); From 5f33c38130bfd4aa10503e328a8477c3d9f68817 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 11:32:39 -0400 Subject: [PATCH 60/70] Corrected relationships --- library/Models/CompaniesXProducts.php | 4 ++-- library/Models/Individuals.php | 2 +- library/Models/Products.php | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/library/Models/CompaniesXProducts.php b/library/Models/CompaniesXProducts.php index 0417871b..3a0e2e12 100644 --- a/library/Models/CompaniesXProducts.php +++ b/library/Models/CompaniesXProducts.php @@ -25,7 +25,7 @@ public function initialize() Companies::class, 'id', [ - 'alias' => Relationships::COMPANY, + 'alias' => Relationships::COMPANIES, 'reusable' => true, ] ); @@ -35,7 +35,7 @@ public function initialize() Products::class, 'id', [ - 'alias' => Relationships::PRODUCT, + 'alias' => Relationships::PRODUCTS, 'reusable' => true, ] ); diff --git a/library/Models/Individuals.php b/library/Models/Individuals.php index 23aa91ee..165b0aef 100644 --- a/library/Models/Individuals.php +++ b/library/Models/Individuals.php @@ -25,7 +25,7 @@ public function initialize() Companies::class, 'id', [ - 'alias' => Relationships::COMPANY, + 'alias' => Relationships::COMPANIES, 'reusable' => true, ] ); diff --git a/library/Models/Products.php b/library/Models/Products.php index 8e970134..b5e8fce8 100644 --- a/library/Models/Products.php +++ b/library/Models/Products.php @@ -22,10 +22,10 @@ public function initialize() { $this->hasManyToMany( 'id', - Products::class, + CompaniesXProducts::class, 'productId', 'companyId', - CompaniesXProducts::class, + Companies::class, 'id', [ 'alias' => Relationships::COMPANIES, From cc3e3fd906c9ed93370f3ff60fcf0e1638b85589 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 11:32:54 -0400 Subject: [PATCH 61/70] Corrections to transformers and tests --- library/Constants/Relationships.php | 3 - library/Transformers/BaseTransformer.php | 18 +++ library/Transformers/CompaniesTransformer.php | 26 +++- .../IndividualTypesTransformer.php | 34 ++++ .../Transformers/IndividualsTransformer.php | 55 +++++++ .../Transformers/ProductTypesTransformer.php | 12 +- library/Transformers/ProductsTransformer.php | 22 +-- .../library/Models/CompaniesXProductsCest.php | 4 +- .../library/Models/IndividualsCest.php | 2 +- .../IndividualsTransformerCest.php | 146 ++++++++++++++++++ .../Transformers/ProductsTransformerCest.php | 49 +++++- .../library/Constants/RelationshipsCest.php | 3 - 12 files changed, 343 insertions(+), 31 deletions(-) create mode 100644 library/Transformers/IndividualTypesTransformer.php create mode 100644 library/Transformers/IndividualsTransformer.php create mode 100644 tests/integration/library/Transformers/IndividualsTransformerCest.php diff --git a/library/Constants/Relationships.php b/library/Constants/Relationships.php index 448d98a0..cec83808 100644 --- a/library/Constants/Relationships.php +++ b/library/Constants/Relationships.php @@ -6,12 +6,9 @@ class Relationships { - const COMPANY = 'company'; const COMPANIES = 'companies'; - const INDIVIDUAL = 'individual'; const INDIVIDUAL_TYPES = 'individual-types'; const INDIVIDUALS = 'individuals'; - const PRODUCT = 'product'; const PRODUCT_TYPES = 'product-types'; const PRODUCTS = 'products'; const USERS = 'users'; diff --git a/library/Transformers/BaseTransformer.php b/library/Transformers/BaseTransformer.php index 4e9200f7..ecdbcfa4 100644 --- a/library/Transformers/BaseTransformer.php +++ b/library/Transformers/BaseTransformer.php @@ -5,6 +5,8 @@ namespace Niden\Transformers; use function array_keys; +use League\Fractal\Resource\Collection; +use League\Fractal\Resource\Item; use League\Fractal\TransformerAbstract; use Niden\Exception\ModelException; use Niden\Mvc\Model\AbstractModel; @@ -30,4 +32,20 @@ public function transform(AbstractModel $model) return $data; } + + /** + * @param string $method + * @param AbstractModel $model + * @param string $transformer + * @param string $relationship + * + * @return Collection|Item + */ + protected function getRelatedData(string $method, AbstractModel $model, string $transformer, string $relationship) + { + /** @var AbstractModel $data */ + $data = $model->getRelated($relationship); + + return $this->$method($data, new $transformer(), $relationship); + } } diff --git a/library/Transformers/CompaniesTransformer.php b/library/Transformers/CompaniesTransformer.php index a1fea3c0..a2b9d658 100644 --- a/library/Transformers/CompaniesTransformer.php +++ b/library/Transformers/CompaniesTransformer.php @@ -7,7 +7,6 @@ use League\Fractal\Resource\Collection; use Niden\Constants\Relationships; use Niden\Models\Companies; -use Niden\Models\Products; /** * Class CompaniesTransformer @@ -24,11 +23,28 @@ class CompaniesTransformer extends BaseTransformer * * @return Collection */ - public function includeProducts(Companies $company) + public function includeIndividuals(Companies $company) { - /** @var Products $products */ - $products = $company->getRelated(Relationships::PRODUCTS); + return $this->getRelatedData( + 'collection', + $company, + IndividualsTransformer::class, + Relationships::INDIVIDUALS + ); + } - return $this->collection($products, new ProductsTransformer(), Relationships::PRODUCTS); + /** + * @param Companies $company + * + * @return Collection + */ + public function includeProducts(Companies $company) + { + return $this->getRelatedData( + 'collection', + $company, + ProductsTransformer::class, + Relationships::PRODUCTS + ); } } diff --git a/library/Transformers/IndividualTypesTransformer.php b/library/Transformers/IndividualTypesTransformer.php new file mode 100644 index 00000000..69b2a7d6 --- /dev/null +++ b/library/Transformers/IndividualTypesTransformer.php @@ -0,0 +1,34 @@ +getRelatedData( + 'collection', + $type, + IndividualsTransformer::class, + Relationships::INDIVIDUALS + ); + } +} diff --git a/library/Transformers/IndividualsTransformer.php b/library/Transformers/IndividualsTransformer.php new file mode 100644 index 00000000..e080f4bc --- /dev/null +++ b/library/Transformers/IndividualsTransformer.php @@ -0,0 +1,55 @@ +getRelatedData( + 'item', + $individual, + CompaniesTransformer::class, + Relationships::COMPANIES + ); + } + + /** + * Includes the product types + * + * @param Individuals $individual + * + * @return Item + */ + public function includeIndividualTypes(Individuals $individual) + { + return $this->getRelatedData( + 'item', + $individual, + BaseTransformer::class, + Relationships::INDIVIDUAL_TYPES + ); + } +} diff --git a/library/Transformers/ProductTypesTransformer.php b/library/Transformers/ProductTypesTransformer.php index 54380f57..6b2db982 100644 --- a/library/Transformers/ProductTypesTransformer.php +++ b/library/Transformers/ProductTypesTransformer.php @@ -6,8 +6,6 @@ use League\Fractal\Resource\Collection; use Niden\Constants\Relationships; -use Niden\Models\Companies; -use Niden\Models\Products; use Niden\Models\ProductTypes; /** @@ -26,9 +24,11 @@ class ProductTypesTransformer extends BaseTransformer */ public function includeProducts(ProductTypes $type) { - /** @var Products $products */ - $products = $type->getRelated(Relationships::PRODUCTS); - - return $this->collection($products, new ProductsTransformer(), Relationships::PRODUCTS); + return $this->getRelatedData( + 'collection', + $type, + ProductsTransformer::class, + Relationships::PRODUCTS + ); } } diff --git a/library/Transformers/ProductsTransformer.php b/library/Transformers/ProductsTransformer.php index 151a9a18..cf832fd3 100644 --- a/library/Transformers/ProductsTransformer.php +++ b/library/Transformers/ProductsTransformer.php @@ -7,9 +7,7 @@ use League\Fractal\Resource\Collection; use League\Fractal\Resource\Item; use Niden\Constants\Relationships; -use Niden\Models\Companies; use Niden\Models\Products; -use Niden\Models\ProductTypes; /** * Class ProductsTransformer @@ -30,10 +28,12 @@ class ProductsTransformer extends BaseTransformer */ public function includeCompanies(Products $product) { - /** @var Companies $companies */ - $companies = $product->getRelated(Relationships::COMPANIES); - - return $this->collection($companies, new CompaniesTransformer(), Relationships::PRODUCT_TYPES); + return $this->getRelatedData( + 'collection', + $product, + CompaniesTransformer::class, + Relationships::COMPANIES + ); } /** @@ -45,9 +45,11 @@ public function includeCompanies(Products $product) */ public function includeProductTypes(Products $product) { - /** @var ProductTypes $productType */ - $productType = $product->getRelated(Relationships::PRODUCT_TYPES); - - return $this->item($productType, new BaseTransformer(), Relationships::PRODUCT_TYPES); + return $this->getRelatedData( + 'item', + $product, + BaseTransformer::class, + Relationships::PRODUCT_TYPES + ); } } diff --git a/tests/integration/library/Models/CompaniesXProductsCest.php b/tests/integration/library/Models/CompaniesXProductsCest.php index 0bf96cb8..989d513d 100644 --- a/tests/integration/library/Models/CompaniesXProductsCest.php +++ b/tests/integration/library/Models/CompaniesXProductsCest.php @@ -36,8 +36,8 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(CompaniesXProducts::class); $expected = [ - [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], - [0, 'productId', Products::class, 'id', ['alias' => Relationships::PRODUCT, 'reusable' => true]], + [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANIES, 'reusable' => true]], + [0, 'productId', Products::class, 'id', ['alias' => Relationships::PRODUCTS, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } diff --git a/tests/integration/library/Models/IndividualsCest.php b/tests/integration/library/Models/IndividualsCest.php index 25e5d7c2..6e767a0d 100644 --- a/tests/integration/library/Models/IndividualsCest.php +++ b/tests/integration/library/Models/IndividualsCest.php @@ -48,7 +48,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(Individuals::class); $expected = [ - [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANY, 'reusable' => true]], + [0, 'companyId', Companies::class, 'id', ['alias' => Relationships::COMPANIES, 'reusable' => true]], [1, 'typeId', IndividualTypes::class, 'id', ['alias' => Relationships::INDIVIDUAL_TYPES, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); diff --git a/tests/integration/library/Transformers/IndividualsTransformerCest.php b/tests/integration/library/Transformers/IndividualsTransformerCest.php new file mode 100644 index 00000000..ddb902be --- /dev/null +++ b/tests/integration/library/Transformers/IndividualsTransformerCest.php @@ -0,0 +1,146 @@ +haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + /** @var IndividualTypes $individualType */ + $individualType = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Individuals $individual */ + $individual = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => $company->get('id'), + 'typeId' => $individualType->get('id'), + 'prefix' => uniqid(), + 'first' => uniqid('first-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + + $url = envValue('APP_URL', 'http://localhost'); + $manager = new Manager(); + $manager->setSerializer(new JsonApiSerializer($url)); + $manager->parseIncludes([Relationships::COMPANIES, Relationships::INDIVIDUAL_TYPES]); + $resource = new Collection([$individual], new IndividualsTransformer(), Relationships::INDIVIDUALS); + $results = $manager->createData($resource)->toArray(); + $expected = [ + 'data' => [ + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individual->get('id'), + 'attributes' => [ + 'companyId' => $individual->get('companyId'), + 'typeId' => $individual->get('typeId'), + 'prefix' => $individual->get('prefix'), + 'first' => $individual->get('first'), + 'middle' => $individual->get('middle'), + 'last' => $individual->get('last'), + 'suffix' => $individual->get('suffix'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + $url, + Relationships::INDIVIDUALS, + $individual->get('id') + ), + ], + 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + $url, + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::COMPANIES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + $url, + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + 'type' => Relationships::COMPANIES, + 'id' => $company->get('id'), + ], + ], + Relationships::INDIVIDUAL_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + $url, + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::INDIVIDUAL_TYPES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + $url, + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::INDIVIDUAL_TYPES + ), + ], + 'data' => [ + 'type' => Relationships::INDIVIDUAL_TYPES, + 'id' => $individualType->get('id'), + ], + ], + ], + ], + ], + 'included' => [ + Data::companyResponse($company), + Data::individualTypeResponse($individualType), + ], + ]; + + $I->assertEquals($expected, $results); + } +} diff --git a/tests/integration/library/Transformers/ProductsTransformerCest.php b/tests/integration/library/Transformers/ProductsTransformerCest.php index ef7bb08d..518ac886 100644 --- a/tests/integration/library/Transformers/ProductsTransformerCest.php +++ b/tests/integration/library/Transformers/ProductsTransformerCest.php @@ -7,6 +7,8 @@ use League\Fractal\Resource\Collection; use League\Fractal\Serializer\JsonApiSerializer; use Niden\Constants\Relationships; +use Niden\Models\Companies; +use Niden\Models\CompaniesXProducts; use Niden\Models\Products; use Niden\Models\ProductTypes; use Niden\Transformers\ProductsTransformer; @@ -22,6 +24,17 @@ class ProductsTransformerCest */ public function checkTransformer(IntegrationTester $I) { + /** @var Companies $company */ + $company = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + /** @var ProductTypes $productType */ $productType = $I->haveRecordWithFields( ProductTypes::class, @@ -43,10 +56,19 @@ public function checkTransformer(IntegrationTester $I) ] ); + /** @var CompaniesXProducts $glue */ + $glue = $I->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $company->get('id'), + 'productId' => $product->get('id'), + ] + ); + $url = envValue('APP_URL', 'http://localhost'); $manager = new Manager(); $manager->setSerializer(new JsonApiSerializer($url)); - $manager->parseIncludes(Relationships::PRODUCT_TYPES); + $manager->parseIncludes([Relationships::COMPANIES, Relationships::PRODUCT_TYPES]); $resource = new Collection([$product], new ProductsTransformer(), Relationships::PRODUCTS); $results = $manager->createData($resource)->toArray(); $expected = [ @@ -70,6 +92,30 @@ public function checkTransformer(IntegrationTester $I) ), ], 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + $url, + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + $url, + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + [ + 'type' => Relationships::COMPANIES, + 'id' => $company->get('id'), + ], + ], + ], Relationships::PRODUCT_TYPES => [ 'links' => [ 'self' => sprintf( @@ -96,6 +142,7 @@ public function checkTransformer(IntegrationTester $I) ], ], 'included' => [ + Data::companyResponse($company), Data::productTypeResponse($productType), ], ]; diff --git a/tests/unit/library/Constants/RelationshipsCest.php b/tests/unit/library/Constants/RelationshipsCest.php index 28a4fa67..559e8425 100644 --- a/tests/unit/library/Constants/RelationshipsCest.php +++ b/tests/unit/library/Constants/RelationshipsCest.php @@ -9,12 +9,9 @@ class RelationshipsCest { public function checkConstants(CliTester $I) { - $I->assertEquals('company', Relationships::COMPANY); $I->assertEquals('companies', Relationships::COMPANIES); - $I->assertEquals('individual', Relationships::INDIVIDUAL); $I->assertEquals('individual-types', Relationships::INDIVIDUAL_TYPES); $I->assertEquals('individuals', Relationships::INDIVIDUALS); - $I->assertEquals('product', Relationships::PRODUCT); $I->assertEquals('product-types', Relationships::PRODUCT_TYPES); $I->assertEquals('products', Relationships::PRODUCTS); $I->assertEquals('users', Relationships::USERS); From c03f9201e9a90c1bae87bfb612f0e54468f8773e Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 11:34:43 -0400 Subject: [PATCH 62/70] Added routes for individuals --- library/Providers/RouterProvider.php | 1 + tests/unit/library/Providers/RouterCest.php | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index c0e06e81..05986546 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -116,6 +116,7 @@ private function getRoutes(): array ]; $routes = $this->getMultiRoutes($routes, CompaniesGetController::class, Rel::COMPANIES); + $routes = $this->getMultiRoutes($routes, IndividualsGetController::class, Rel::INDIVIDUALS); $routes = $this->getMultiRoutes($routes, IndividualTypesGetController::class, Rel::INDIVIDUAL_TYPES); $routes = $this->getMultiRoutes($routes, ProductsGetController::class, Rel::PRODUCTS); $routes = $this->getMultiRoutes($routes, ProductTypesGetController::class, Rel::PRODUCT_TYPES); diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 0e8a8962..83337434 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -37,6 +37,10 @@ public function checkRegistration(UnitTester $I) ['GET', '/companies/{recordId:[0-9]+}'], ['GET', '/companies/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], ['GET', '/companies/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individuals'], + ['GET', '/individuals/{recordId:[0-9]+}'], + ['GET', '/individuals/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individuals/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ['GET', '/individual-types'], ['GET', '/individual-types/{recordId:[0-9]+}'], ['GET', '/individual-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], @@ -51,7 +55,7 @@ public function checkRegistration(UnitTester $I) ['GET', '/product-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], ]; - $I->assertEquals(20, count($routes)); + $I->assertEquals(24, count($routes)); foreach ($routes as $index => $route) { $I->assertEquals($expected[$index][0], $route->getHttpMethods()); $I->assertEquals($expected[$index][1], $route->getPattern()); From e2cbf89114d75a275137f8c4b838dc62e6365ac0 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 13:40:06 -0400 Subject: [PATCH 63/70] Added individuals get controller; Routes for individuals; Initial tests for individuals; Added helper methods for adding records --- api/controllers/Individuals/GetController.php | 36 ++ library/Providers/RouterProvider.php | 1 + tests/_support/Helper/Integration.php | 92 ++++- tests/_support/Page/Data.php | 35 ++ tests/api/Companies/GetCest.php | 90 +---- tests/api/IndividualTypes/GetCest.php | 16 +- tests/api/Individuals/GetCest.php | 348 ++++++++++++++++++ tests/api/ProductTypes/GetCest.php | 48 +-- .../IndividualsTransformerCest.php | 1 - 9 files changed, 535 insertions(+), 132 deletions(-) create mode 100644 api/controllers/Individuals/GetController.php create mode 100644 tests/api/Individuals/GetCest.php diff --git a/api/controllers/Individuals/GetController.php b/api/controllers/Individuals/GetController.php new file mode 100644 index 00000000..d06d4d84 --- /dev/null +++ b/api/controllers/Individuals/GetController.php @@ -0,0 +1,36 @@ +haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid($namePrefix), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + } + + /** + * @param int $companyId + * @param int $productId + * + * @return mixed + */ + public function addCompanyXProduct(int $companyId, int $productId) + { + return $this->haveRecordWithFields( + CompaniesXProducts::class, + [ + 'companyId' => $companyId, + 'productId' => $productId, + ] + ); + } + + /** + * @param string $namePrefix + * + * @return mixed + */ + public function addIndividualTypeRecord(string $namePrefix = '') + { + return $this->haveRecordWithFields( + IndividualTypes::class, + [ + 'name' => uniqid($namePrefix), + 'description' => uniqid(), + ] + ); + } + + /** + * @param string $namePrefix + * @param int $typeId * * @return mixed */ + public function addProductRecord(string $namePrefix = '', int $typeId = 0) + { + return $this->haveRecordWithFields( + Products::class, + [ + 'name' => uniqid($namePrefix), + 'typeId' => $typeId, + 'description' => uniqid(), + 'quantity' => 25, + 'price' => 19.99, + ] + ); + } + + /** + * @param string $namePrefix + * + * @return mixed + */ + public function addProductTypeRecord(string $namePrefix = '') + { + return $this->haveRecordWithFields( + ProductTypes::class, + [ + 'name' => uniqid($namePrefix), + 'description' => uniqid(), + ] + ); + } + + /** + * @return mixed + */ public function grabDi() { return $this->diContainer; diff --git a/tests/_support/Page/Data.php b/tests/_support/Page/Data.php index 5bf8d5e4..efd93099 100644 --- a/tests/_support/Page/Data.php +++ b/tests/_support/Page/Data.php @@ -13,6 +13,10 @@ class Data public static $companiesRecordRelationshipUrl = '/companies/%s/%s'; public static $companiesRecordRelationshipRelationshipUrl = '/companies/%s/relationships/%s'; public static $loginUrl = '/login'; + public static $individualsUrl = '/individuals'; + public static $individualsRecordUrl = '/individuals/%s'; + public static $individualsRecordRelationshipUrl = '/individuals/%s/%s'; + public static $individualsRecordRelationshipRelationshipUrl = '/individuals/%s/relationships/%s'; public static $individualTypesUrl = '/individual-types'; public static $individualTypesRecordUrl = '/individual-types/%s'; public static $individualTypesRecordRelationshipUrl = '/individual-types/%s/%s'; @@ -85,6 +89,37 @@ public static function companyResponse(AbstractModel $record) ]; } + /** + * @param AbstractModel $record + * + * @return array + * @throws \Niden\Exception\ModelException + */ + public static function individualResponse(AbstractModel $record) + { + return [ + 'id' => $record->get('id'), + 'type' => Relationships::INDIVIDUALS, + 'attributes' => [ + 'companyId' => $record->get('companyId'), + 'typeId' => $record->get('typeId'), + 'prefix' => $record->get('prefix'), + 'first' => $record->get('first'), + 'middle' => $record->get('middle'), + 'last' => $record->get('last'), + 'suffix' => $record->get('suffix'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $record->get('id') + ), + ], + ]; + } + /** * @param AbstractModel $record * diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index 02a2f9f0..dca1340c 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -68,26 +68,9 @@ public function getUnknownCompany(ApiTester $I) public function getCompanies(ApiTester $I) { $I->addApiUserRecord(); - $token = $I->apiLogin(); - - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); - $comTwo = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-b-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); + $token = $I->apiLogin(); + $comOne = $I->addCompanyRecord('com-a-'); + $comTwo = $I->addCompanyRecord('com-b-'); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$companiesUrl); $I->deleteHeader('Authorization'); @@ -207,69 +190,28 @@ public function getCompaniesNoData(ApiTester $I) $I->seeSuccessJsonResponse(); } + /** + * @param ApiTester $I + * @param string $url + * + * @throws \Niden\Exception\ModelException + */ private function runCompaniesWithProductsTests(ApiTester $I, $url = '') { $I->addApiUserRecord(); $token = $I->apiLogin(); /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('prt-a-'), - 'description' => uniqid(), - ] - ); - + $productType = $I->addProductTypeRecord('prt-a-'); /** @var Products $productOne */ - $productOne = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - + $productOne = $I->addProductRecord('prd-a-', $productType->get('id')); /** @var Products $productTwo */ - $productTwo = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-b-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); + $productTwo = $I->addProductRecord('prd-b-', $productType->get('id')); + /** @var Companies $comOne */ + $comOne = $I->addCompanyRecord('com-a-'); - $I->haveRecordWithFields( - CompaniesXProducts::class, - [ - 'companyId' => $comOne->get('id'), - 'productId' => $productOne->get('id'), - ] - ); - - $I->haveRecordWithFields( - CompaniesXProducts::class, - [ - 'companyId' => $comOne->get('id'), - 'productId' => $productTwo->get('id'), - ] - ); + $I->addCompanyXProduct($comOne->get('id'), $productOne->get('id')); + $I->addCompanyXProduct($comOne->get('id'), $productTwo->get('id')); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET( diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index 50223afb..eda5fecb 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -19,20 +19,8 @@ public function getIndividualTypes(ApiTester $I) $I->addApiUserRecord(); $token = $I->apiLogin(); - $typeOne = $I->haveRecordWithFields( - IndividualTypes::class, - [ - 'name' => uniqid('type-a-'), - 'description' => uniqid('desc-a-'), - ] - ); - $typeTwo = $I->haveRecordWithFields( - IndividualTypes::class, - [ - 'name' => uniqid('type-b-'), - 'description' => uniqid('desc-b-'), - ] - ); + $typeOne = $I->addIndividualTypeRecord('type-a-'); + $typeTwo = $I->addIndividualTypeRecord('type-b-'); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$individualTypesUrl); $I->deleteHeader('Authorization'); diff --git a/tests/api/Individuals/GetCest.php b/tests/api/Individuals/GetCest.php new file mode 100644 index 00000000..c99f56c0 --- /dev/null +++ b/tests/api/Individuals/GetCest.php @@ -0,0 +1,348 @@ +addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var Companies $company */ + $company = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + /** @var IndividualTypes $individualType */ + $individualType = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Individuals $individual */ + $individual = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => $company->get('id'), + 'typeId' => $individualType->get('id'), + 'prefix' => uniqid(), + 'first' => uniqid('first-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$individualsRecordUrl, $individual->get('id'))); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + Data::individualResponse($individual), + ] + ); + } + + /** + * @param ApiTester $I + */ + public function getUnknownIndividual(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$individualsRecordUrl, 9999)); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividuals(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $individualOne = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => 1, + 'typeId' => 1, + 'prefix' => uniqid(), + 'first' => uniqid('first-a-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + $individualTwo = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => 1, + 'typeId' => 1, + 'prefix' => uniqid(), + 'first' => uniqid('first-b-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$individualsUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + Data::companyResponse($individualOne), + Data::companyResponse($individualTwo), + ] + ); + } + + /** + * @param ApiTester $I + */ + public function getIndividualsWithRelationshipCompanies(ApiTester $I) + { + $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipRelationshipUrl); + } + + /** + * @param ApiTester $I + */ + public function getIndividualsWithCompanies(ApiTester $I) + { + $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualsWithUnknownRelationship(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var Companies $company */ + $company = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + /** @var IndividualTypes $individualType */ + $individualType = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Individuals $individual */ + $individual = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => $company->get('id'), + 'typeId' => $individualType->get('id'), + 'prefix' => uniqid(), + 'first' => uniqid('first-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$individualsRecordRelationshipUrl, $individual->get('id'), 'unknown')); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + + /** + * @param ApiTester $I + */ + public function getIndividualsNoData(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$individualsUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } + + private function runIndividualsWithCompaniesTests(ApiTester $I, $url = '') + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var Companies $company */ + $company = $I->haveRecordWithFields( + Companies::class, + [ + 'name' => uniqid('com-a-'), + 'address' => uniqid(), + 'city' => uniqid(), + 'phone' => uniqid(), + ] + ); + + /** @var IndividualTypes $individualType */ + $individualType = $I->haveRecordWithFields( + IndividualTypes::class, + [ + 'name' => 'my type', + 'description' => 'description of my type', + ] + ); + + /** @var Individuals $individual */ + $individual = $I->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => $company->get('id'), + 'typeId' => $individualType->get('id'), + 'prefix' => uniqid(), + 'first' => uniqid('first-a-'), + 'middle' => uniqid(), + 'last' => uniqid('last-'), + 'suffix' => uniqid(), + ] + ); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $individual->get('id'), + Relationships::COMPANIES + ) + ); + $I->deleteHeader('Authorization'); + + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'id' => $individual->get('id'), + 'type' => Relationships::INDIVIDUALS, + 'attributes' => [ + 'companyId' => $individual->get('companyId'), + 'typeId' => $individual->get('typeId'), + 'prefix' => $individual->get('prefix'), + 'first' => $individual->get('first'), + 'middle' => $individual->get('middle'), + 'last' => $individual->get('last'), + 'suffix' => $individual->get('suffix'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $individual->get('id') + ), + ], + 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $company->get('id'), + Relationships::COMPANIES + + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $company->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + 'type' => Relationships::COMPANIES, + 'id' => $company->get('id'), + ] + ], + Relationships::INDIVIDUAL_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $individualType->get('id'), + Relationships::INDIVIDUAL_TYPES + + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUALS, + $individualType->get('id'), + Relationships::INDIVIDUAL_TYPES + ), + ], + 'data' => [ + 'type' => Relationships::INDIVIDUAL_TYPES, + 'id' => $individualType->get('id'), + ] + ] + ] + ] + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::companyResponse($company), + Data::individualTypeResponse($individualType), + ] + ); + } +} + diff --git a/tests/api/ProductTypes/GetCest.php b/tests/api/ProductTypes/GetCest.php index 612a67eb..97b67c1e 100644 --- a/tests/api/ProductTypes/GetCest.php +++ b/tests/api/ProductTypes/GetCest.php @@ -22,20 +22,8 @@ public function getProductTypes(ApiTester $I) $I->addApiUserRecord(); $token = $I->apiLogin(); - $typeOne = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('type-a-'), - 'description' => uniqid('desc-a-'), - ] - ); - $typeTwo = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('type-b-'), - 'description' => uniqid('desc-b-'), - ] - ); + $typeOne = $I->addProductTypeRecord('type-a-'); + $typeTwo = $I->addProductTypeRecord('type-b-'); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$productTypesUrl); $I->deleteHeader('Authorization'); @@ -109,36 +97,12 @@ private function runProductTypesWithProductsTests(ApiTester $I, $url) $I->addApiUserRecord(); $token = $I->apiLogin(); - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('type-a-'), - 'description' => uniqid(), - ] - ); + /** @var ProductTypes $productType */ + $productType = $I->addProductTypeRecord('type-a-'); /** @var Products $productOne */ - $productOne = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - + $productOne = $I->addProductRecord('prd-a-', $productType->get('id')); /** @var Products $productTwo */ - $productTwo = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-b-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); + $productTwo = $I->addProductRecord('prd-b-', $productType->get('id')); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET( sprintf( diff --git a/tests/integration/library/Transformers/IndividualsTransformerCest.php b/tests/integration/library/Transformers/IndividualsTransformerCest.php index ddb902be..e6bd9e9a 100644 --- a/tests/integration/library/Transformers/IndividualsTransformerCest.php +++ b/tests/integration/library/Transformers/IndividualsTransformerCest.php @@ -10,7 +10,6 @@ use Niden\Models\Companies; use Niden\Models\Individuals; use Niden\Models\IndividualTypes; -use Niden\Models\Products; use Niden\Transformers\IndividualsTransformer; use Page\Data; use function Niden\Core\envValue; From 38ed06b62c5f3b3c120890561e3cc71c9e149991 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 13:48:39 -0400 Subject: [PATCH 64/70] Corrected docblock; Use of new helper methods in Products get tests --- .../Transformers/IndividualsTransformer.php | 3 +- tests/api/Products/GetCest.php | 77 +++---------------- 2 files changed, 10 insertions(+), 70 deletions(-) diff --git a/library/Transformers/IndividualsTransformer.php b/library/Transformers/IndividualsTransformer.php index e080f4bc..9105d8c3 100644 --- a/library/Transformers/IndividualsTransformer.php +++ b/library/Transformers/IndividualsTransformer.php @@ -4,7 +4,6 @@ namespace Niden\Transformers; -use League\Fractal\Resource\Collection; use League\Fractal\Resource\Item; use Niden\Constants\Relationships; use Niden\Models\Individuals; @@ -24,7 +23,7 @@ class IndividualsTransformer extends BaseTransformer * * @param Individuals $individual * - * @return Collection + * @return Item */ public function includeCompanies(Individuals $individual) { diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 9f9a86b1..640528e6 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -23,28 +23,11 @@ public function getProduct(ApiTester $I) $token = $I->apiLogin(); /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('prt-a-'), - 'description' => uniqid(), - ] - ); - + $productType = $I->addProductTypeRecord('prt-a-'); /** @var Products $product */ - $product = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - + $product = $I->addProductRecord('prd-a-', $productType->get('id')); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productsUrl . '/' . $product->get('id')); + $I->sendGET(sprintf(Data::$productsRecordUrl, $product->get('id'))); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( @@ -64,7 +47,7 @@ public function getUnknownProduct(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$productsUrl . '/1'); + $I->sendGET(sprintf(Data::$productsRecordUrl, 1)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } @@ -80,37 +63,11 @@ public function getProducts(ApiTester $I) $token = $I->apiLogin(); /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('prt-a-'), - 'description' => uniqid(), - ] - ); - + $productType = $I->addProductTypeRecord('prt-a-'); /** @var Products $productOne */ - $productOne = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); - + $productOne = $I->addProductRecord('prd-a-', $productType->get('id')); /** @var Products $productTwo */ - $productTwo = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-b-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); + $productTwo = $I->addProductRecord('prd-b-', $productType->get('id')); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$productsUrl); @@ -169,25 +126,9 @@ public function getProductsNoData(ApiTester $I) private function runProductsWithProductTypesTests(ApiTester $I, $url) { /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => 'my type', - 'description' => 'description of my type', - ] - ); - + $productType = $I->addProductTypeRecord('prt-a-'); /** @var Products $product */ - $product = $I->haveRecordWithFields( - Products::class, - [ - 'name' => 'my product', - 'typeId' => $productType->get('id'), - 'description' => 'my product description', - 'quantity' => 99, - 'price' => 19.99, - ] - ); + $product = $I->addProductRecord('prd-a-', $productType->get('id')); $I->addApiUserRecord(); $token = $I->apiLogin(); From f3f2886d33fda8091ebb1ca4a2c2a90434f27ed7 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 15:26:05 -0400 Subject: [PATCH 65/70] Fix for routes to accept comma --- library/Providers/RouterProvider.php | 4 ++-- tests/unit/library/Providers/RouterCest.php | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/library/Providers/RouterProvider.php b/library/Providers/RouterProvider.php index fd212617..79241064 100644 --- a/library/Providers/RouterProvider.php +++ b/library/Providers/RouterProvider.php @@ -139,8 +139,8 @@ private function getMultiRoutes(array $routes, string $class, string $relationsh { $routes[] = [$class, '/' . $relationship, 'get', '/']; $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}']; - $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}']; - $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}']; + $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}']; + $routes[] = [$class, '/' . $relationship, 'get', '/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}']; return $routes; } diff --git a/tests/unit/library/Providers/RouterCest.php b/tests/unit/library/Providers/RouterCest.php index 83337434..2473993d 100644 --- a/tests/unit/library/Providers/RouterCest.php +++ b/tests/unit/library/Providers/RouterCest.php @@ -35,24 +35,24 @@ public function checkRegistration(UnitTester $I) ['GET', '/users/{recordId:[0-9]+}'], ['GET', '/companies'], ['GET', '/companies/{recordId:[0-9]+}'], - ['GET', '/companies/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], - ['GET', '/companies/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/companies/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}'], + ['GET', '/companies/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}'], ['GET', '/individuals'], ['GET', '/individuals/{recordId:[0-9]+}'], - ['GET', '/individuals/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], - ['GET', '/individuals/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individuals/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}'], + ['GET', '/individuals/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}'], ['GET', '/individual-types'], ['GET', '/individual-types/{recordId:[0-9]+}'], - ['GET', '/individual-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], - ['GET', '/individual-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/individual-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}'], + ['GET', '/individual-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}'], ['GET', '/products'], ['GET', '/products/{recordId:[0-9]+}'], - ['GET', '/products/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], - ['GET', '/products/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/products/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}'], + ['GET', '/products/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}'], ['GET', '/product-types'], ['GET', '/product-types/{recordId:[0-9]+}'], - ['GET', '/product-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-.]+}'], - ['GET', '/product-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-.]+}'], + ['GET', '/product-types/{recordId:[0-9]+}/{relationships:[a-zA-Z-,.]+}'], + ['GET', '/product-types/{recordId:[0-9]+}/relationships/{relationships:[a-zA-Z-,.]+}'], ]; $I->assertEquals(24, count($routes)); From 0f59959033cd2066ed656d0f7246f20610f4c7ef Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 15:26:33 -0400 Subject: [PATCH 66/70] Corrected relationship parsing for Fractal --- library/Traits/FractalTrait.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/Traits/FractalTrait.php b/library/Traits/FractalTrait.php index 128f731f..e0c30cba 100644 --- a/library/Traits/FractalTrait.php +++ b/library/Traits/FractalTrait.php @@ -35,8 +35,8 @@ protected function format($results, string $transformer, string $resource, array /** * Process relationships */ - foreach ($relationships as $relationship) { - $manager->parseIncludes($relationship); + if (count($relationships) > 0) { + $manager->parseIncludes($relationships); } $resource = new Collection($results, new $transformer(), $resource); From e00620a294f309dd627a32abbafba381f44bda38 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 15:26:50 -0400 Subject: [PATCH 67/70] Test corrections --- tests/api/Products/GetCest.php | 261 ++++++++++++++++++++++++++++++++- 1 file changed, 257 insertions(+), 4 deletions(-) diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index 640528e6..f49a20ea 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -4,6 +4,8 @@ use ApiTester; use Niden\Constants\Relationships; +use Niden\Models\Companies; +use Niden\Models\CompaniesXProducts; use Niden\Models\Products; use Niden\Models\ProductTypes; use Page\Data; @@ -82,6 +84,46 @@ public function getProducts(ApiTester $I) ); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getProductsWithAllRelationships(ApiTester $I) + { + $this->runProductsWithAllRelationshipsTests($I, Data::$productsRecordRelationshipRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getProductsWithRelationshipAllRelationships(ApiTester $I) + { + $this->runProductsWithAllRelationshipsTests($I, Data::$productsRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getProductsWithCompanies(ApiTester $I) + { + $this->runProductsWithCompaniesTests($I, Data::$productsRecordRelationshipRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getProductsWithRelationshipCompanies(ApiTester $I) + { + $this->runProductsWithCompaniesTests($I, Data::$productsRecordRelationshipUrl); + } + /** * @param ApiTester $I * @@ -117,6 +159,220 @@ public function getProductsNoData(ApiTester $I) $I->seeSuccessJsonResponse(); } + private function addRecords(ApiTester $I): array + { + /** @var Companies $comOne */ + $comOne = $I->addCompanyRecord('com-a'); + /** @var Companies $comTwo */ + $comTwo = $I->addCompanyRecord('com-b'); + /** @var ProductTypes $productType */ + $productType = $I->addProductTypeRecord('prt-a-'); + /** @var Products $product */ + $product = $I->addProductRecord('prd-a-', $productType->get('id')); + $I->addCompanyXProduct($comOne->get('id'), $product->get('id')); + $I->addCompanyXProduct($comTwo->get('id'), $product->get('id')); + + return [$product, $productType, $comOne, $comTwo]; + } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runProductsWithAllRelationshipsTests(ApiTester $I, $url) + { + list($product, $productType, $comOne, $comTwo) = $this->addRecords($I); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $product->get('id'), + Relationships::COMPANIES . ',' . Relationships::PRODUCT_TYPES + ) + ); + + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $product->get('id'), + 'attributes' => [ + 'typeId' => $productType->get('id'), + 'name' => $product->get('name'), + 'description' => $product->get('description'), + 'quantity' => $product->get('quantity'), + 'price' => $product->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id') + ), + ], + 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + [ + 'type' => Relationships::COMPANIES, + 'id' => $comOne->get('id'), + ], + [ + 'type' => Relationships::COMPANIES, + 'id' => $comTwo->get('id'), + ], + ], + ], + Relationships::PRODUCT_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::PRODUCT_TYPES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::PRODUCT_TYPES + ), + ], + 'data' => [ + 'type' => Relationships::PRODUCT_TYPES, + 'id' => $productType->get('id'), + ], + ], + ], + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::companyResponse($comOne), + Data::companyResponse($comTwo), + Data::productTypeResponse($productType), + ] + ); + } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runProductsWithCompaniesTests(ApiTester $I, $url) + { + list($product, $productType, $comOne, $comTwo) = $this->addRecords($I); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $product->get('id'), + Relationships::COMPANIES + ) + ); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $product->get('id'), + 'attributes' => [ + 'typeId' => $productType->get('id'), + 'name' => $product->get('name'), + 'description' => $product->get('description'), + 'quantity' => $product->get('quantity'), + 'price' => $product->get('price'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id') + ), + ], + 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::PRODUCTS, + $product->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + [ + 'type' => Relationships::COMPANIES, + 'id' => $comOne->get('id'), + ], + [ + 'type' => Relationships::COMPANIES, + 'id' => $comTwo->get('id'), + ], + ], + ], + ], + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::companyResponse($comOne), + Data::companyResponse($comTwo), + ] + ); + } + /** * @param ApiTester $I * @param $url @@ -125,10 +381,7 @@ public function getProductsNoData(ApiTester $I) */ private function runProductsWithProductTypesTests(ApiTester $I, $url) { - /** @var ProductTypes $productType */ - $productType = $I->addProductTypeRecord('prt-a-'); - /** @var Products $product */ - $product = $I->addProductRecord('prd-a-', $productType->get('id')); + list($product, $productType) = $this->addRecords($I); $I->addApiUserRecord(); $token = $I->apiLogin(); From 7090340a5c4ee30ab23bc63f5abf08d970f457ed Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 15:41:32 -0400 Subject: [PATCH 68/70] Added Individual tests with all relationships --- tests/_support/Helper/Integration.php | 34 ++- tests/api/IndividualTypes/GetCest.php | 2 - tests/api/Individuals/GetCest.php | 406 ++++++++++++++++---------- tests/api/Products/GetCest.php | 2 - 4 files changed, 281 insertions(+), 163 deletions(-) diff --git a/tests/_support/Helper/Integration.php b/tests/_support/Helper/Integration.php index 48859c1e..466bde71 100644 --- a/tests/_support/Helper/Integration.php +++ b/tests/_support/Helper/Integration.php @@ -9,6 +9,7 @@ use Niden\Bootstrap\Api; use Niden\Models\Companies; use Niden\Models\CompaniesXProducts; +use Niden\Models\Individuals; use Niden\Models\IndividualTypes; use Niden\Models\Products; use Niden\Models\ProductTypes; @@ -62,7 +63,7 @@ public function _after(TestInterface $test) /** * @param string $namePrefix * - * @return mixed + * @return Companies */ public function addCompanyRecord(string $namePrefix = '') { @@ -81,7 +82,7 @@ public function addCompanyRecord(string $namePrefix = '') * @param int $companyId * @param int $productId * - * @return mixed + * @return CompaniesXProducts */ public function addCompanyXProduct(int $companyId, int $productId) { @@ -97,7 +98,7 @@ public function addCompanyXProduct(int $companyId, int $productId) /** * @param string $namePrefix * - * @return mixed + * @return IndividualTypes */ public function addIndividualTypeRecord(string $namePrefix = '') { @@ -112,9 +113,32 @@ public function addIndividualTypeRecord(string $namePrefix = '') /** * @param string $namePrefix + * @param int $comId * @param int $typeId * - * @return mixed + * @return Individuals + */ + public function addIndividualRecord(string $namePrefix = '', int $comId = 0, int $typeId = 0) + { + return $this->haveRecordWithFields( + Individuals::class, + [ + 'companyId' => $comId, + 'typeId' => $typeId, + 'prefix' => uniqid(), + 'first' => uniqid($namePrefix), + 'middle' => uniqid(), + 'last' => uniqid(), + 'suffix' => uniqid(), + ] + ); + } + + /** + * @param string $namePrefix + * @param int $typeId + * + * @return Products */ public function addProductRecord(string $namePrefix = '', int $typeId = 0) { @@ -133,7 +157,7 @@ public function addProductRecord(string $namePrefix = '', int $typeId = 0) /** * @param string $namePrefix * - * @return mixed + * @return ProductTypes */ public function addProductTypeRecord(string $namePrefix = '') { diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index eda5fecb..055b7184 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -3,9 +3,7 @@ namespace Niden\Tests\api\IndividualTypes; use ApiTester; -use Niden\Models\IndividualTypes; use Page\Data; -use function uniqid; class GetCest { diff --git a/tests/api/Individuals/GetCest.php b/tests/api/Individuals/GetCest.php index c99f56c0..463d1fdd 100644 --- a/tests/api/Individuals/GetCest.php +++ b/tests/api/Individuals/GetCest.php @@ -4,13 +4,11 @@ use ApiTester; use Niden\Constants\Relationships; -use function Niden\Core\envValue; use Niden\Models\Companies; use Niden\Models\Individuals; use Niden\Models\IndividualTypes; use Page\Data; -use function sprintf; -use function uniqid; +use function Niden\Core\envValue; class GetCest { @@ -25,38 +23,11 @@ public function getIndividual(ApiTester $I) $token = $I->apiLogin(); /** @var Companies $company */ - $company = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); - + $company = $I->addCompanyRecord('com-a-'); /** @var IndividualTypes $individualType */ - $individualType = $I->haveRecordWithFields( - IndividualTypes::class, - [ - 'name' => 'my type', - 'description' => 'description of my type', - ] - ); - + $individualType = $I->addIndividualTypeRecord('prt-a-'); /** @var Individuals $individual */ - $individual = $I->haveRecordWithFields( - Individuals::class, - [ - 'companyId' => $company->get('id'), - 'typeId' => $individualType->get('id'), - 'prefix' => uniqid(), - 'first' => uniqid('first-'), - 'middle' => uniqid(), - 'last' => uniqid('last-'), - 'suffix' => uniqid(), - ] - ); + $individual = $I->addIndividualRecord('prd-a-', $company->get('id'), $individualType->get('id')); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(sprintf(Data::$individualsRecordUrl, $individual->get('id'))); $I->deleteHeader('Authorization'); @@ -78,7 +49,7 @@ public function getUnknownIndividual(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$individualsRecordUrl, 9999)); + $I->sendGET(sprintf(Data::$individualsRecordUrl, 1)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } @@ -93,30 +64,15 @@ public function getIndividuals(ApiTester $I) $I->addApiUserRecord(); $token = $I->apiLogin(); - $individualOne = $I->haveRecordWithFields( - Individuals::class, - [ - 'companyId' => 1, - 'typeId' => 1, - 'prefix' => uniqid(), - 'first' => uniqid('first-a-'), - 'middle' => uniqid(), - 'last' => uniqid('last-'), - 'suffix' => uniqid(), - ] - ); - $individualTwo = $I->haveRecordWithFields( - Individuals::class, - [ - 'companyId' => 1, - 'typeId' => 1, - 'prefix' => uniqid(), - 'first' => uniqid('first-b-'), - 'middle' => uniqid(), - 'last' => uniqid('last-'), - 'suffix' => uniqid(), - ] - ); + /** @var Companies $company */ + $company = $I->addCompanyRecord('com-a-'); + /** @var IndividualTypes $individualType */ + $individualType = $I->addIndividualTypeRecord('prt-a-'); + /** @var Individuals $individualOne */ + $individualOne = $I->addIndividualRecord('ind-a-', $company->get('id'), $individualType->get('id')); + /** @var Individuals $individualTwo */ + $individualTwo = $I->addIndividualRecord('ind-b-', $company->get('id'), $individualType->get('id')); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$individualsUrl); $I->deleteHeader('Authorization'); @@ -124,26 +80,30 @@ public function getIndividuals(ApiTester $I) $I->seeSuccessJsonResponse( 'data', [ - Data::companyResponse($individualOne), - Data::companyResponse($individualTwo), + Data::individualResponse($individualOne), + Data::individualResponse($individualTwo), ] ); } /** * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException */ - public function getIndividualsWithRelationshipCompanies(ApiTester $I) + public function getIndividualsWithAllRelationships(ApiTester $I) { - $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipRelationshipUrl); + $this->runIndividualsWithAllRelationshipsTests($I, Data::$individualsRecordRelationshipRelationshipUrl); } /** * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException */ - public function getIndividualsWithCompanies(ApiTester $I) + public function getIndividualsWithRelationshipAllRelationships(ApiTester $I) { - $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipUrl); + $this->runIndividualsWithAllRelationshipsTests($I, Data::$individualsRecordRelationshipUrl); } /** @@ -151,49 +111,39 @@ public function getIndividualsWithCompanies(ApiTester $I) * * @throws \Niden\Exception\ModelException */ - public function getIndividualsWithUnknownRelationship(ApiTester $I) + public function getIndividualsWithCompanies(ApiTester $I) { - $I->addApiUserRecord(); - $token = $I->apiLogin(); - - /** @var Companies $company */ - $company = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); + $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipRelationshipUrl); + } - /** @var IndividualTypes $individualType */ - $individualType = $I->haveRecordWithFields( - IndividualTypes::class, - [ - 'name' => 'my type', - 'description' => 'description of my type', - ] - ); + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualsWithRelationshipCompanies(ApiTester $I) + { + $this->runIndividualsWithCompaniesTests($I, Data::$individualsRecordRelationshipUrl); + } - /** @var Individuals $individual */ - $individual = $I->haveRecordWithFields( - Individuals::class, - [ - 'companyId' => $company->get('id'), - 'typeId' => $individualType->get('id'), - 'prefix' => uniqid(), - 'first' => uniqid('first-'), - 'middle' => uniqid(), - 'last' => uniqid('last-'), - 'suffix' => uniqid(), - ] - ); + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualsWithIndividualTypes(ApiTester $I) + { + $this->runIndividualsWithIndividualTypesTests($I, Data::$individualsRecordRelationshipRelationshipUrl); + } - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$individualsRecordRelationshipUrl, $individual->get('id'), 'unknown')); - $I->deleteHeader('Authorization'); - $I->seeResponseIs404(); + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualsWithRelationshipIndividualTypes(ApiTester $I) + { + $this->runIndividualsWithIndividualTypesTests($I, Data::$individualsRecordRelationshipUrl); } /** @@ -211,63 +161,155 @@ public function getIndividualsNoData(ApiTester $I) $I->seeSuccessJsonResponse(); } - private function runIndividualsWithCompaniesTests(ApiTester $I, $url = '') + private function addRecords(ApiTester $I): array + { + /** @var Companies $company */ + $company = $I->addCompanyRecord('com-a'); + /** @var IndividualTypes $individualType */ + $individualType = $I->addIndividualTypeRecord('prt-a-'); + /** @var Individuals $individual */ + $individual = $I->addIndividualRecord('ind-a-', $company->get('id'), $individualType->get('id')); + + + return [$individual, $individualType, $company]; + } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runIndividualsWithAllRelationshipsTests(ApiTester $I, $url) { + list($individual, $individualType, $company) = $this->addRecords($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); - /** @var Companies $company */ - $company = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $individual->get('id'), + Relationships::COMPANIES . ',' . Relationships::INDIVIDUAL_TYPES + ) ); - /** @var IndividualTypes $individualType */ - $individualType = $I->haveRecordWithFields( - IndividualTypes::class, + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', [ - 'name' => 'my type', - 'description' => 'description of my type', + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individual->get('id'), + 'attributes' => [ + 'companyId' => $individual->get('companyId'), + 'typeId' => $individual->get('typeId'), + 'prefix' => $individual->get('prefix'), + 'first' => $individual->get('first'), + 'middle' => $individual->get('middle'), + 'last' => $individual->get('last'), + 'suffix' => $individual->get('suffix'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id') + ), + ], + 'relationships' => [ + Relationships::COMPANIES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::COMPANIES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::COMPANIES + ), + ], + 'data' => [ + 'type' => Relationships::COMPANIES, + 'id' => $company->get('id'), + ], + ], + Relationships::INDIVIDUAL_TYPES => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::INDIVIDUAL_TYPES + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id'), + Relationships::INDIVIDUAL_TYPES + ), + ], + 'data' => [ + 'type' => Relationships::INDIVIDUAL_TYPES, + 'id' => $individualType->get('id'), + ], + ], + ], + ], ] ); - /** @var Individuals $individual */ - $individual = $I->haveRecordWithFields( - Individuals::class, + $I->seeSuccessJsonResponse( + 'included', [ - 'companyId' => $company->get('id'), - 'typeId' => $individualType->get('id'), - 'prefix' => uniqid(), - 'first' => uniqid('first-a-'), - 'middle' => uniqid(), - 'last' => uniqid('last-'), - 'suffix' => uniqid(), + Data::companyResponse($company), + Data::individualTypeResponse($individualType), ] ); + } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runIndividualsWithCompaniesTests(ApiTester $I, $url) + { + list($individual, $individualType, $company) = $this->addRecords($I); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET( sprintf( $url, $individual->get('id'), - Relationships::COMPANIES + Relationships::COMPANIES ) ); $I->deleteHeader('Authorization'); - $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( 'data', [ [ - 'id' => $individual->get('id'), - 'type' => Relationships::INDIVIDUALS, - 'attributes' => [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individual->get('id'), + 'attributes' => [ 'companyId' => $individual->get('companyId'), 'typeId' => $individual->get('typeId'), 'prefix' => $individual->get('prefix'), @@ -276,10 +318,10 @@ private function runIndividualsWithCompaniesTests(ApiTester $I, $url = '') 'last' => $individual->get('last'), 'suffix' => $individual->get('suffix'), ], - 'links' => [ + 'links' => [ 'self' => sprintf( '%s/%s/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::INDIVIDUALS, $individual->get('id') ), @@ -289,60 +331,116 @@ private function runIndividualsWithCompaniesTests(ApiTester $I, $url = '') 'links' => [ 'self' => sprintf( '%s/%s/%s/relationships/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::INDIVIDUALS, - $company->get('id'), + $individual->get('id'), Relationships::COMPANIES - ), 'related' => sprintf( '%s/%s/%s/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::INDIVIDUALS, - $company->get('id'), + $individual->get('id'), Relationships::COMPANIES ), ], - 'data' => [ + 'data' => [ 'type' => Relationships::COMPANIES, 'id' => $company->get('id'), - ] + ], ], + ], + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::companyResponse($company), + ] + ); + } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runIndividualsWithIndividualTypesTests(ApiTester $I, $url) + { + list($individual, $individualType) = $this->addRecords($I); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $individual->get('id'), + Relationships::INDIVIDUAL_TYPES + ) + ); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individual->get('id'), + 'attributes' => [ + 'companyId' => $individual->get('companyId'), + 'typeId' => $individual->get('typeId'), + 'prefix' => $individual->get('prefix'), + 'first' => $individual->get('first'), + 'middle' => $individual->get('middle'), + 'last' => $individual->get('last'), + 'suffix' => $individual->get('suffix'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::INDIVIDUALS, + $individual->get('id') + ), + ], + 'relationships' => [ Relationships::INDIVIDUAL_TYPES => [ 'links' => [ 'self' => sprintf( '%s/%s/%s/relationships/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::INDIVIDUALS, - $individualType->get('id'), + $individual->get('id'), Relationships::INDIVIDUAL_TYPES - ), 'related' => sprintf( '%s/%s/%s/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::INDIVIDUALS, - $individualType->get('id'), + $individual->get('id'), Relationships::INDIVIDUAL_TYPES ), ], - 'data' => [ + 'data' => [ 'type' => Relationships::INDIVIDUAL_TYPES, 'id' => $individualType->get('id'), - ] - ] - ] - ] + ], + ], + ], + ], ] ); $I->seeSuccessJsonResponse( 'included', [ - Data::companyResponse($company), Data::individualTypeResponse($individualType), ] ); } } - diff --git a/tests/api/Products/GetCest.php b/tests/api/Products/GetCest.php index f49a20ea..e12df483 100644 --- a/tests/api/Products/GetCest.php +++ b/tests/api/Products/GetCest.php @@ -5,12 +5,10 @@ use ApiTester; use Niden\Constants\Relationships; use Niden\Models\Companies; -use Niden\Models\CompaniesXProducts; use Niden\Models\Products; use Niden\Models\ProductTypes; use Page\Data; use function Niden\Core\envValue; -use function uniqid; class GetCest { From fb9b89ac55c492f2c46f8958d47091df5ee45388 Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Thu, 2 Aug 2018 17:17:04 -0400 Subject: [PATCH 69/70] Corrected ind-type tests; Added more tests for unknown relationships --- .../IndividualTypes/GetController.php | 11 +- library/Models/IndividualTypes.php | 2 +- tests/api/Companies/GetCest.php | 429 +++++++++++++----- tests/api/IndividualTypes/GetCest.php | 115 ++++- .../library/Models/IndividualTypesCest.php | 2 +- 5 files changed, 432 insertions(+), 127 deletions(-) diff --git a/api/controllers/IndividualTypes/GetController.php b/api/controllers/IndividualTypes/GetController.php index 4c45e591..fbff02dc 100644 --- a/api/controllers/IndividualTypes/GetController.php +++ b/api/controllers/IndividualTypes/GetController.php @@ -7,7 +7,7 @@ use Niden\Api\Controllers\BaseController; use Niden\Constants\Relationships; use Niden\Models\IndividualTypes; -use Niden\Transformers\BaseTransformer; +use Niden\Transformers\IndividualTypesTransformer; /** * Class GetController @@ -18,9 +18,16 @@ class GetController extends BaseController { /** @var string */ protected $model = IndividualTypes::class; + + /** @var array */ + protected $relationships = [ + Relationships::INDIVIDUALS, + ]; + /** @var string */ protected $resource = Relationships::INDIVIDUAL_TYPES; + /** @var string */ - protected $transformer = BaseTransformer::class; + protected $transformer = IndividualTypesTransformer::class; } diff --git a/library/Models/IndividualTypes.php b/library/Models/IndividualTypes.php index a0f95279..9298b67a 100644 --- a/library/Models/IndividualTypes.php +++ b/library/Models/IndividualTypes.php @@ -20,7 +20,7 @@ class IndividualTypes extends AbstractModel */ public function initialize() { - $this->belongsTo( + $this->hasMany( 'id', Individuals::class, 'typeId', diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index dca1340c..eac97335 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -4,14 +4,9 @@ use ApiTester; use Niden\Constants\Relationships; -use function Niden\Core\envValue; use Niden\Models\Companies; -use Niden\Models\CompaniesXProducts; -use Niden\Models\Products; -use Niden\Models\ProductTypes; use Page\Data; -use function sprintf; -use function uniqid; +use function Niden\Core\envValue; class GetCest { @@ -24,28 +19,37 @@ public function getCompany(ApiTester $I) { $I->addApiUserRecord(); $token = $I->apiLogin(); - - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] - ); + + $company = $I->addCompanyRecord('com-a-'); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$companiesRecordUrl, $comOne->get('id'))); + $I->sendGET(sprintf(Data::$companiesRecordUrl, $company->get('id'))); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( 'data', [ - Data::companyResponse($comOne), + Data::companyResponse($company), ] ); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getCompanyUnknownRelationship(ApiTester $I) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $company = $I->addCompanyRecord('com-a-'); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(sprintf(Data::$companiesRecordRelationshipUrl, $company->get('id'), 'unknown')); + $I->deleteHeader('Authorization'); + $I->seeResponseIs404(); + } + /** * @param ApiTester $I */ @@ -55,7 +59,7 @@ public function getUnknownCompany(ApiTester $I) $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(sprintf(Data::$companiesRecordUrl, 9999)); + $I->sendGET(sprintf(Data::$companiesRecordUrl, 1)); $I->deleteHeader('Authorization'); $I->seeResponseIs404(); } @@ -68,9 +72,13 @@ public function getUnknownCompany(ApiTester $I) public function getCompanies(ApiTester $I) { $I->addApiUserRecord(); - $token = $I->apiLogin(); - $comOne = $I->addCompanyRecord('com-a-'); - $comTwo = $I->addCompanyRecord('com-b-'); + $token = $I->apiLogin(); + + /** @var Companies $comOne */ + $comOne = $I->addCompanyRecord('com-a-'); + /** @var Companies $comTwo */ + $comTwo = $I->addCompanyRecord('com-b-'); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET(Data::$companiesUrl); $I->deleteHeader('Authorization'); @@ -86,18 +94,52 @@ public function getCompanies(ApiTester $I) /** * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException */ - public function getCompaniesWithRelationshipProducts(ApiTester $I) + public function getCompaniesWithAllRelationships(ApiTester $I) { - $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); + $this->runCompaniesWithAllRelationshipsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getCompaniesWithRelationshipAllRelationships(ApiTester $I) + { + $this->runCompaniesWithAllRelationshipsTests($I, Data::$companiesRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getCompaniesWithIndividuals(ApiTester $I) + { + $this->runCompaniesWithIndividualsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); } /** * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getCompaniesWithRelationshipIndividuals(ApiTester $I) + { + $this->runCompaniesWithIndividualsTests($I, Data::$companiesRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException */ public function getCompaniesWithProducts(ApiTester $I) { - $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipUrl); + $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipRelationshipUrl); } /** @@ -105,143 +147,288 @@ public function getCompaniesWithProducts(ApiTester $I) * * @throws \Niden\Exception\ModelException */ - public function getCompaniesWithUnknownRelationship(ApiTester $I) + public function getCompaniesWithRelationshipCompanyTypes(ApiTester $I) + { + $this->runCompaniesWithProductsTests($I, Data::$companiesRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + */ + public function getCompaniesNoData(ApiTester $I) { $I->addApiUserRecord(); $token = $I->apiLogin(); - /** @var ProductTypes $productType */ - $productType = $I->haveRecordWithFields( - ProductTypes::class, - [ - 'name' => uniqid('prt-a-'), - 'description' => uniqid(), - ] - ); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET(Data::$companiesUrl); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse(); + } - /** @var Products $productOne */ - $productOne = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-a-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); + private function addRecords(ApiTester $I): array + { + /** @var Companies $comOne */ + $company = $I->addCompanyRecord('com-a'); + $indType = $I->addIndividualTypeRecord('type-a-'); + $indOne = $I->addIndividualRecord('ind-a-', $company->get('id'), $indType->get('id')); + $indTwo = $I->addIndividualRecord('ind-a-', $company->get('id'), $indType->get('id')); + $prdType = $I->addProductTypeRecord('type-a-'); + $prdOne = $I->addProductRecord('prd-a-', $prdType->get('id')); + $prdTwo = $I->addProductRecord('prd-b-', $prdType->get('id')); + $I->addCompanyXProduct($company->get('id'), $prdOne->get('id')); + $I->addCompanyXProduct($company->get('id'), $prdTwo->get('id')); - /** @var Products $productTwo */ - $productTwo = $I->haveRecordWithFields( - Products::class, - [ - 'name' => uniqid('prd-b-'), - 'typeId' => $productType->get('id'), - 'description' => uniqid(), - 'quantity' => 25, - 'price' => 19.99, - ] - ); + return [$company, $prdOne, $prdTwo, $indOne, $indTwo]; + } - $comOne = $I->haveRecordWithFields( - Companies::class, - [ - 'name' => uniqid('com-a-'), - 'address' => uniqid(), - 'city' => uniqid(), - 'phone' => uniqid(), - ] + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runCompaniesWithAllRelationshipsTests(ApiTester $I, $url) + { + list($com, $prdOne, $prdTwo, $indOne, $indTwo) = $this->addRecords($I); + + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $com->get('id'), + Relationships::INDIVIDUALS . ',' . Relationships::PRODUCTS + ) ); - $I->haveRecordWithFields( - CompaniesXProducts::class, + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', [ - 'companyId' => $comOne->get('id'), - 'productId' => $productOne->get('id'), + [ + 'type' => Relationships::COMPANIES, + 'id' => $com->get('id'), + 'attributes' => [ + 'name' => $com->get('name'), + 'address' => $com->get('address'), + 'city' => $com->get('city'), + 'phone' => $com->get('phone'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id') + ), + ], + 'relationships' => [ + Relationships::INDIVIDUALS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::INDIVIDUALS + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::INDIVIDUALS + ), + ], + 'data' => [ + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $indOne->get('id'), + ], + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $indTwo->get('id'), + ], + ], + ], + Relationships::PRODUCTS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::PRODUCTS + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::PRODUCTS + ), + ], + 'data' => [ + [ + 'type' => Relationships::PRODUCTS, + 'id' => $prdOne->get('id'), + ], + [ + 'type' => Relationships::PRODUCTS, + 'id' => $prdTwo->get('id'), + ], + ], + ], + ], + ], ] ); - $I->haveRecordWithFields( - CompaniesXProducts::class, + $I->seeSuccessJsonResponse( + 'included', [ - 'companyId' => $comOne->get('id'), - 'productId' => $productTwo->get('id'), + Data::individualResponse($indOne), + Data::individualResponse($indTwo), + Data::productResponse($prdOne), + Data::productResponse($prdTwo), ] ); - - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl . '/' . $comOne->get('id') . '/relationships/unknown'); - $I->deleteHeader('Authorization'); - $I->seeResponseIs404(); } /** * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException */ - public function getCompaniesNoData(ApiTester $I) + private function runCompaniesWithIndividualsTests(ApiTester $I, $url) { + list($com, , , $indOne, $indTwo) = $this->addRecords($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); $I->haveHttpHeader('Authorization', 'Bearer ' . $token); - $I->sendGET(Data::$companiesUrl); + $I->sendGET( + sprintf( + $url, + $com->get('id'), + Relationships::INDIVIDUALS + ) + ); + $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::COMPANIES, + 'id' => $com->get('id'), + 'attributes' => [ + 'name' => $com->get('name'), + 'address' => $com->get('address'), + 'city' => $com->get('city'), + 'phone' => $com->get('phone'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id') + ), + ], + 'relationships' => [ + Relationships::INDIVIDUALS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::INDIVIDUALS + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL', 'localhost'), + Relationships::COMPANIES, + $com->get('id'), + Relationships::INDIVIDUALS + ), + ], + 'data' => [ + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $indOne->get('id'), + ], + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $indTwo->get('id'), + ], + ], + ], + ], + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::individualResponse($indOne), + Data::individualResponse($indTwo), + ] + ); } /** * @param ApiTester $I - * @param string $url + * @param $url * * @throws \Niden\Exception\ModelException */ - private function runCompaniesWithProductsTests(ApiTester $I, $url = '') + private function runCompaniesWithProductsTests(ApiTester $I, $url) { + list($com, $prdOne, $prdTwo) = $this->addRecords($I); + $I->addApiUserRecord(); $token = $I->apiLogin(); - /** @var ProductTypes $productType */ - $productType = $I->addProductTypeRecord('prt-a-'); - /** @var Products $productOne */ - $productOne = $I->addProductRecord('prd-a-', $productType->get('id')); - /** @var Products $productTwo */ - $productTwo = $I->addProductRecord('prd-b-', $productType->get('id')); - /** @var Companies $comOne */ - $comOne = $I->addCompanyRecord('com-a-'); - - $I->addCompanyXProduct($comOne->get('id'), $productOne->get('id')); - $I->addCompanyXProduct($comOne->get('id'), $productTwo->get('id')); - $I->haveHttpHeader('Authorization', 'Bearer ' . $token); $I->sendGET( sprintf( $url, - $comOne->get('id'), - Relationships::PRODUCTS + $com->get('id'), + Relationships::PRODUCTS ) ); - $I->deleteHeader('Authorization'); + $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse( 'data', [ [ - 'id' => $comOne->get('id'), - 'type' => Relationships::COMPANIES, - 'attributes' => [ - 'name' => $comOne->get('name'), - 'address' => $comOne->get('address'), - 'city' => $comOne->get('city'), - 'phone' => $comOne->get('phone'), + 'type' => Relationships::COMPANIES, + 'id' => $com->get('id'), + 'attributes' => [ + 'name' => $com->get('name'), + 'address' => $com->get('address'), + 'city' => $com->get('city'), + 'phone' => $com->get('phone'), ], - 'links' => [ + 'links' => [ 'self' => sprintf( '%s/%s/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::COMPANIES, - $comOne->get('id') + $com->get('id') ), ], 'relationships' => [ @@ -249,43 +436,41 @@ private function runCompaniesWithProductsTests(ApiTester $I, $url = '') 'links' => [ 'self' => sprintf( '%s/%s/%s/relationships/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::COMPANIES, - $comOne->get('id'), + $com->get('id'), Relationships::PRODUCTS - ), 'related' => sprintf( '%s/%s/%s/%s', - envValue('APP_URL'), + envValue('APP_URL', 'localhost'), Relationships::COMPANIES, - $comOne->get('id'), + $com->get('id'), Relationships::PRODUCTS ), ], - 'data' => [ + 'data' => [ [ 'type' => Relationships::PRODUCTS, - 'id' => $productOne->get('id'), + 'id' => $prdOne->get('id'), ], [ 'type' => Relationships::PRODUCTS, - 'id' => $productTwo->get('id'), + 'id' => $prdTwo->get('id'), ], - ] - ] - ] - ] + ], + ], + ], + ], ] ); $I->seeSuccessJsonResponse( 'included', [ - Data::productResponse($productOne), - Data::productResponse($productTwo), + Data::productResponse($prdOne), + Data::productResponse($prdTwo), ] ); } } - diff --git a/tests/api/IndividualTypes/GetCest.php b/tests/api/IndividualTypes/GetCest.php index 055b7184..6c867d6e 100644 --- a/tests/api/IndividualTypes/GetCest.php +++ b/tests/api/IndividualTypes/GetCest.php @@ -3,7 +3,11 @@ namespace Niden\Tests\api\IndividualTypes; use ApiTester; +use Niden\Constants\Relationships; +use Niden\Models\Individuals; +use Niden\Models\IndividualTypes; use Page\Data; +use function Niden\Core\envValue; class GetCest { @@ -23,7 +27,6 @@ public function getIndividualTypes(ApiTester $I) $I->sendGET(Data::$individualTypesUrl); $I->deleteHeader('Authorization'); $I->seeResponseIsSuccessful(); - $I->seeSuccessJsonResponse( 'data', [ @@ -47,6 +50,26 @@ public function getUnknownIndividualTypes(ApiTester $I) $I->seeResponseIs404(); } + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualTypesWithRelationshipIndividuals(ApiTester $I) + { + $this->runIndividualTypesWithIndividualsTests($I, Data::$individualTypesRecordRelationshipUrl); + } + + /** + * @param ApiTester $I + * + * @throws \Niden\Exception\ModelException + */ + public function getIndividualTypesWithIndividuals(ApiTester $I) + { + $this->runIndividualTypesWithIndividualsTests($I, Data::$individualTypesRecordRelationshipRelationshipUrl); + } + /** * @param ApiTester $I */ @@ -61,4 +84,94 @@ public function getIndividualTypesNoData(ApiTester $I) $I->seeResponseIsSuccessful(); $I->seeSuccessJsonResponse(); } + + /** + * @param ApiTester $I + * @param $url + * + * @throws \Niden\Exception\ModelException + */ + private function runIndividualTypesWithIndividualsTests(ApiTester $I, $url) + { + $I->addApiUserRecord(); + $token = $I->apiLogin(); + + /** @var $company */ + $company = $I->addCompanyRecord('com-a'); + /** @var IndividualTypes $individualType */ + $individualType = $I->addIndividualTypeRecord('type-a-'); + /** @var Individuals $individualOne */ + $individualOne = $I->addIndividualRecord('prd-a-', $company->get('id'), $individualType->get('id')); + /** @var Individuals $individualTwo */ + $individualTwo = $I->addIndividualRecord('prd-b-', $company->get('id'), $individualType->get('id')); + $I->haveHttpHeader('Authorization', 'Bearer ' . $token); + $I->sendGET( + sprintf( + $url, + $individualType->get('id'), + Relationships::INDIVIDUALS + ) + ); + $I->deleteHeader('Authorization'); + $I->seeResponseIsSuccessful(); + $I->seeSuccessJsonResponse( + 'data', + [ + [ + 'type' => Relationships::INDIVIDUAL_TYPES, + 'id' => $individualType->get('id'), + 'attributes' => [ + 'name' => $individualType->get('name'), + 'description' => $individualType->get('description'), + ], + 'links' => [ + 'self' => sprintf( + '%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUAL_TYPES, + $individualType->get('id') + ), + ], + 'relationships' => [ + Relationships::INDIVIDUALS => [ + 'links' => [ + 'self' => sprintf( + '%s/%s/%s/relationships/%s', + envValue('APP_URL'), + Relationships::INDIVIDUAL_TYPES, + $individualType->get('id'), + Relationships::INDIVIDUALS + ), + 'related' => sprintf( + '%s/%s/%s/%s', + envValue('APP_URL'), + Relationships::INDIVIDUAL_TYPES, + $individualType->get('id'), + Relationships::INDIVIDUALS + ), + ], + 'data' => [ + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individualOne->get('id'), + ], + [ + 'type' => Relationships::INDIVIDUALS, + 'id' => $individualTwo->get('id'), + ], + ], + ], + ], + ], + ] + ); + + $I->seeSuccessJsonResponse( + 'included', + [ + Data::individualResponse($individualOne), + Data::individualResponse($individualTwo), + ] + ); + } } diff --git a/tests/integration/library/Models/IndividualTypesCest.php b/tests/integration/library/Models/IndividualTypesCest.php index 93ce9b28..9f8e86c2 100644 --- a/tests/integration/library/Models/IndividualTypesCest.php +++ b/tests/integration/library/Models/IndividualTypesCest.php @@ -37,7 +37,7 @@ public function validateRelationships(IntegrationTester $I) { $actual = $I->getModelRelationships(IndividualTypes::class); $expected = [ - [0, 'id', Individuals::class, 'typeId', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], + [2, 'id', Individuals::class, 'typeId', ['alias' => Relationships::INDIVIDUALS, 'reusable' => true]], ]; $I->assertEquals($expected, $actual); } From 947e0d14930fa324407ebc7661102cd6362db19f Mon Sep 17 00:00:00 2001 From: Nikolaos Dimopoulos Date: Fri, 3 Aug 2018 09:39:58 -0400 Subject: [PATCH 70/70] Work on the README --- README.md | 162 +++++++++++++------------------- tests/api/Companies/GetCest.php | 2 - 2 files changed, 64 insertions(+), 100 deletions(-) diff --git a/README.md b/README.md index ce298249..a74c7fe2 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ # phalcon-api Sample API using Phalcon -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/niden/phalcon-api/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/niden/phalcon-api/?branch=master) -[![Code Coverage](https://scrutinizer-ci.com/g/niden/phalcon-api/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/niden/phalcon-api/?branch=master) -[![Build Status](https://scrutinizer-ci.com/g/niden/phalcon-api/badges/build.png?b=master)](https://scrutinizer-ci.com/g/niden/phalcon-api/build-status/master) +[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phalcon/phalcon-api/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phalcon/phalcon-api/?branch=master) +[![Code Coverage](https://scrutinizer-ci.com/g/phalcon/phalcon-api/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/phalcon/phalcon-api/?branch=master) +[![Build Status](https://scrutinizer-ci.com/g/phalcon/phalcon-api/badges/build.png?b=master)](https://scrutinizer-ci.com/g/phalcon/phalcon-api/build-status/master) -Implementation of an API application using the Phalcon Framework (https://phalconphp.com) +Implementation of an API application using the Phalcon Framework [https://phalconphp.com](https://phalconphp.com) ### Installation - Clone the project - In the project folder run `nanobox run php-server` - Hit the IP address with postman -This requires [nanobox](https://nanobox.io) to be present in your system. Visit their site for installation instructions. +**NOTE** This requires [nanobox](https://nanobox.io) to be present in your system. Visit their site for installation instructions. ### Features ##### JWT Tokens @@ -29,18 +29,63 @@ As part of the security of the API, [JWT](https://jwt.io) are used. JSON Web Tok - TokenVerification - When a token is supplied, check if it is correctly signed - TokenValidation - When a token is supplied, check if it is valid (`issuedAt`, `notBefore`, `expires`) +##### JSONAPI +This implementation follows the [JSON API](https://jsonapi.org) standard. All responses are formatted according to the standard, which offers a uniformed way of presenting data, simple or compound documents, includes (related data), sparse fieldsets, sorting, patination and filtering. + ### Usage #### Requests The routes available are: -| Method | Route | Payload | -|--------|-------------------|-------------------------------------------------------------------------------------------------------------| -| `POST` | `login` | `{"username": string, "password": string}` | -| `POST` | `companies` | `{"name": string, "address": , "city": , "phone": ` | -| `GET` | `individualtypes` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | -| `GET` | `producttypes` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | -| `GET` | `users` | `/` If no `id` passed, all records returned. If yes, then the record matching that `id` is returned | +| Method | Route | Parameters | Action | +|--------|--------------------|------------------------------------|----------------------------------------------------------| +| `POST` | `login` | `username`, `password` | Login - get Token | +| `POST` | `companies` | `name`, `address`, `city`, `phone` | Add a company record in the database | +| `GET` | `companies` | | Get companies. Empty resultset if no data present | +| `GET` | `companies` | Numeric Id | Get company by id. 404 if record does not exist | +| `GET` | `individuals` | | Get individuals. Empty resultset if no data present | +| `GET` | `individuals` | Numeric Id | Get individual by id. 404 if record does not exist | +| `GET` | `individual-types` | | Get individual types. Empty resultset if no data present | +| `GET` | `individual-types` | Numeric Id | Get individual type by id. 404 if record does not exist | +| `GET` | `products` | | Get products. Empty resultset if no data present | +| `GET` | `products` | Numeric Id | Get product by id. 404 if record does not exist | +| `GET` | `product-types` | | Get product types. Empty resultset if no data present | +| `GET` | `product-types` | Numeric Id | Get product type by id. 404 if record does not exist | +| `GET` | `users` | | Get users. Empty resultset if no data present | +| `GET` | `users` | Numeric Id | Get user by id. 404 if record does not exist | + +#### Relationships + +`/companies//individuals` +`/companies//products` +`/companies//individuals,products` + +`/companies//relationships/individuals` +`/companies//relationships/products` +`/companies//relationships/individuals,products` + +`individuals//companies` +`individuals//individual-types` +`individuals//companies,individual-types` + +`individuals//relationships/companies` +`individuals//relationships/individual-types` +`individuals//relationships/companies,individual-types` + +`individual-types//individuals` +`individual-types//relationships/individuals` + +`products//companies` +`products//product-types` +`products//companies,product-types` + +`products//relationships/companies` +`products//relationships/product-types` +`products//relationships/companies,product-types` + +`product-types//products` +`product-types//relationships/products` + #### Responses @@ -120,93 +165,14 @@ The record always has `id` and `type` present at the top level. `id` is the uniq } ``` -`POST /login` -``` -"username" => "niden" -"password" => "110011" -``` - -```json -{ - "jsonapi": { - "version": "1.0" - }, - "data": { - "token": "aa.bb.cc" - }, - "meta": { - "timestamp": "2018-06-08T15:07:35+00:00", - "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" - } -} -``` - -`GET /users/get/1051` -```json -{ - "jsonapi": { - "version": "1.0" - }, - "data": [ - { - "id": 1051, - "type": "users", - "attributes": { - "status": 1, - "username": "niden", - "issuer": "https:\/\/niden.net", - "tokenPassword": "11110000", - "tokenId": "11001100" - } - } - ], - "meta": { - "timestamp": "2018-06-08T15:07:35+00:00", - "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" - } -} -``` - -`GET /users/get` -```json -{ - "jsonapi": { - "version": "1.0" - }, - "data": [ - { - "id": 1051, - "type": "users", - "attributes": { - "status": 1, - "username": "niden", - "issuer": "https:\/\/niden.net", - "tokenPassword": "11110000", - "tokenId": "11001100" - } - }, - { - "id": 1244, - "type": "users", - "attributes": { - "status": 1, - "username": "phalcon", - "issuer": "https:\/\/phalconphp.com", - "tokenPassword": "00001111", - "tokenId": "99009900" - } - } - ], - "meta": { - "timestamp": "2018-06-08T15:07:35+00:00", - "hash": "6219ae83afaebc08da4250c4fd23ea1b4843d" - } -} -``` - +For more information regarding responses, please check [JSON API](https://jsonapi.org) + ### TODO -- Work on companies `GET` -- Work on relationships and data returned +- ~~Work on companies GET~~ +- ~~Work on relationships and data returned~~ - Write examples of code to send to the client +- Create docs endpoint - Work on pagination +- Work on filters +- Work on sorting - Perhaps add a new claim to the token tied to the device? `setClaim('deviceId', 'Web-Server')`. This will allow the client application to invalidate access to a device that has already been logged in. diff --git a/tests/api/Companies/GetCest.php b/tests/api/Companies/GetCest.php index eac97335..b8af7694 100644 --- a/tests/api/Companies/GetCest.php +++ b/tests/api/Companies/GetCest.php @@ -35,8 +35,6 @@ public function getCompany(ApiTester $I) /** * @param ApiTester $I - * - * @throws \Niden\Exception\ModelException */ public function getCompanyUnknownRelationship(ApiTester $I) {