Skip to content

Commit

Permalink
fix: prevent adding array to int calculating total value (#492)
Browse files Browse the repository at this point in the history
* fix: prevent adding array to int calculating total value

* test: add

* style: improve var name

* amount means quantity i think

* implement feedback
  • Loading branch information
joerivanveen authored Jul 23, 2024
1 parent 00bdf7e commit ebc2ff8
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Rule/Consignment/MinimumItemValueRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ public function validate($validationSubject): void
$totalValue = 0;

foreach ($validationSubject->items as $item) {
$totalValue += $item->getItemValue();
$itemValue = $item->getItemValue();

if (! isset($itemValue['amount'])) {
continue;
}

$totalValue += (int) $itemValue['amount'];
}

if ($totalValue < 100) {
Expand Down
92 changes: 92 additions & 0 deletions test/Rule/MinimumItemValueRuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

namespace MyParcelNL\Sdk\Test\Rule;

use MyParcelNL\Sdk\src\Model\Consignment\PostNLConsignment;
use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem;
use MyParcelNL\Sdk\src\Rule\Consignment\MinimumItemValueRule;
use MyParcelNL\Sdk\Test\Bootstrap\TestCase;

class MinimumItemValueRuleTest extends TestCase
{
/**
* @return array
*/
public function provideMinimumItemValueData(): array
{
return [
[
[
'items' => [
[
'value' => 50,
],
[
'value' => 50,
],
],
],
'expected'=>true,
],
[
[
'items' => [
[
'value' => 5000,
],
[
'value' => 9995,
],
],
],
'expected'=>true,
],
[
[
'items' => [
[
'value' => 50,
],
],
],
'expected'=>false,
],
[
[
'items' => [],
],
'expected'=>true,
],
];
}

/**
* @param array $data
* @param bool $expected
*
* @dataProvider provideMinimumItemValueData
*/
public function testMinimumItemValueRule(array $data, bool $expected): void
{
$rule = new MinimumItemValueRule();
$consignment = new PostNLConsignment();

foreach ($data['items'] as $item) {
$consignment->addItem(
(new MyParcelCustomsItem())
->setItemValue($item['value'])
->setAmount(1)
->setWeight(1)
->setClassification(123456)
->setCountry('NL')
->setDescription('test')
);
}

$rule->validate($consignment);

self::assertEquals($expected, 0 === count($rule->getErrors()));
}
}

0 comments on commit ebc2ff8

Please sign in to comment.