From 16f09e99e710f7b75ea2e050c8e511570545ee91 Mon Sep 17 00:00:00 2001 From: egarcia Date: Tue, 31 Oct 2017 03:51:44 +0100 Subject: [PATCH] EduardoGR adding strategy context in order to complete the pattern --- Behavioral/Strategy/Context.php | 23 ++++++++++++ Behavioral/Strategy/ObjectCollection.php | 43 ---------------------- Behavioral/Strategy/Tests/StrategyTest.php | 12 +++--- 3 files changed, 28 insertions(+), 50 deletions(-) create mode 100644 Behavioral/Strategy/Context.php delete mode 100644 Behavioral/Strategy/ObjectCollection.php diff --git a/Behavioral/Strategy/Context.php b/Behavioral/Strategy/Context.php new file mode 100644 index 0000000..6279f0e --- /dev/null +++ b/Behavioral/Strategy/Context.php @@ -0,0 +1,23 @@ +comparator = $comparator; + } + + public function executeStrategy(array $elements) : array + { + uasort($elements, [$this->comparator, 'compare']); + + return $elements; + } +} \ No newline at end of file diff --git a/Behavioral/Strategy/ObjectCollection.php b/Behavioral/Strategy/ObjectCollection.php deleted file mode 100644 index ca8165b..0000000 --- a/Behavioral/Strategy/ObjectCollection.php +++ /dev/null @@ -1,43 +0,0 @@ -elements = $elements; - } - - public function sort(): array - { - if (!$this->comparator) { - throw new \LogicException('Comparator is not set'); - } - - uasort($this->elements, [$this->comparator, 'compare']); - - return $this->elements; - } - - /** - * @param ComparatorInterface $comparator - */ - public function setComparator(ComparatorInterface $comparator) - { - $this->comparator = $comparator; - } -} diff --git a/Behavioral/Strategy/Tests/StrategyTest.php b/Behavioral/Strategy/Tests/StrategyTest.php index cf1f7f3..0d25c7c 100644 --- a/Behavioral/Strategy/Tests/StrategyTest.php +++ b/Behavioral/Strategy/Tests/StrategyTest.php @@ -2,9 +2,9 @@ namespace DesignPatterns\Behavioral\Strategy\Tests; +use DesignPatterns\Behavioral\Strategy\Context; use DesignPatterns\Behavioral\Strategy\DateComparator; use DesignPatterns\Behavioral\Strategy\IdComparator; -use DesignPatterns\Behavioral\Strategy\ObjectCollection; use PHPUnit\Framework\TestCase; class StrategyTest extends TestCase @@ -45,9 +45,8 @@ class StrategyTest extends TestCase */ public function testIdComparator($collection, $expected) { - $obj = new ObjectCollection($collection); - $obj->setComparator(new IdComparator()); - $elements = $obj->sort(); + $obj = new Context(new IdComparator()); + $elements = $obj->executeStrategy($collection); $firstElement = array_shift($elements); $this->assertEquals($expected, $firstElement); @@ -61,9 +60,8 @@ class StrategyTest extends TestCase */ public function testDateComparator($collection, $expected) { - $obj = new ObjectCollection($collection); - $obj->setComparator(new DateComparator()); - $elements = $obj->sort(); + $obj = new Context(new DateComparator()); + $elements = $obj->executeStrategy($collection); $firstElement = array_shift($elements); $this->assertEquals($expected, $firstElement);