Skip to content

Commit

Permalink
Filter for arithmetic operations laminas#28
Browse files Browse the repository at this point in the history
Signed-off-by: Flávio Gomes da Silva Lisboa <[email protected]>
  • Loading branch information
fgsl committed Oct 25, 2021
1 parent 0fc5dcd commit 05d8acd
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/FourOperations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php
namespace Laminas\Filter;


use Laminas\Filter\AbstractFilter;
use Laminas\Filter\Exception\InvalidArgumentException;

class FourOperations extends AbstractFilter {
const ADD = 'add';
const SUB = 'sub';
const MUL = 'mul';
const DIV = 'div';
const MOD = 'mod';

/**
* $options expects an array with two keys:
* operation: add, sub, mul or div
* value: value of second operand
* @param array $options
*/
public function __construct(array $options)
{
$operations = [self::ADD,self::SUB,self::MUL,self::DIV,self::MOD];
if (!isset($options['operation']) || (!in_array($options['operation'],$operations))){
throw new InvalidArgumentException(sprintf(
'%s expects argument operation string with one of theses values: add, sub, mul or div; received "%s"',
__METHOD__, $options['operation']));
}
if (!isset($options['value'])){
throw new InvalidArgumentException(sprintf(
'%s expects argument value; received none',
__METHOD__));
}
$this->options = $options;
}

public function filter($value)
{
$operand = $this->options['value'];
switch ($this->options['operation']){
case self::ADD:
return ($value + $operand);
case self::SUB:
return ($value - $operand);
case self::MUL:
return ($value * $operand);
case self::DIV:
return ($value / $operand);
case self::MOD:
return ($value % $operand);
}
return $value;
}
}
22 changes: 22 additions & 0 deletions test/FourOperationsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php
namespace LaminasTest\Filter;

use Laminas\Filter\FourOperations;
use PHPUnit\Framework\TestCase;

class FourOperationsTest extends TestCase
{
public function testOperations()
{
$filter = new FourOperations(['operation'=>'add','value'=>4]);
$this->assertEquals(9, $filter->filter(5));
$filter = new FourOperations(['operation'=>'sub','value'=>3]);
$this->assertEquals(7, $filter->filter(10));
$filter = new FourOperations(['operation'=>'mul','value'=>5]);
$this->assertEquals(30, $filter->filter(6));
$filter = new FourOperations(['operation'=>'div','value'=>12]);
$this->assertEquals(12, $filter->filter(144));
$filter = new FourOperations(['operation'=>'mod','value'=>2]);
$this->assertEquals(1, $filter->filter(3));
}
}

0 comments on commit 05d8acd

Please sign in to comment.