Skip to content

Commit 16f09e9

Browse files
author
egarcia
committed
EduardoGR adding strategy context in order to complete the pattern
1 parent 3ea7462 commit 16f09e9

File tree

3 files changed

+28
-50
lines changed

3 files changed

+28
-50
lines changed

Behavioral/Strategy/Context.php

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace DesignPatterns\Behavioral\Strategy;
4+
5+
class Context
6+
{
7+
/**
8+
* @var ComparatorInterface
9+
*/
10+
private $comparator;
11+
12+
public function __construct(ComparatorInterface $comparator)
13+
{
14+
$this->comparator = $comparator;
15+
}
16+
17+
public function executeStrategy(array $elements) : array
18+
{
19+
uasort($elements, [$this->comparator, 'compare']);
20+
21+
return $elements;
22+
}
23+
}

Behavioral/Strategy/ObjectCollection.php

-43
This file was deleted.

Behavioral/Strategy/Tests/StrategyTest.php

+5-7
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
namespace DesignPatterns\Behavioral\Strategy\Tests;
44

5+
use DesignPatterns\Behavioral\Strategy\Context;
56
use DesignPatterns\Behavioral\Strategy\DateComparator;
67
use DesignPatterns\Behavioral\Strategy\IdComparator;
7-
use DesignPatterns\Behavioral\Strategy\ObjectCollection;
88
use PHPUnit\Framework\TestCase;
99

1010
class StrategyTest extends TestCase
@@ -45,9 +45,8 @@ public function provideDates()
4545
*/
4646
public function testIdComparator($collection, $expected)
4747
{
48-
$obj = new ObjectCollection($collection);
49-
$obj->setComparator(new IdComparator());
50-
$elements = $obj->sort();
48+
$obj = new Context(new IdComparator());
49+
$elements = $obj->executeStrategy($collection);
5150

5251
$firstElement = array_shift($elements);
5352
$this->assertEquals($expected, $firstElement);
@@ -61,9 +60,8 @@ public function testIdComparator($collection, $expected)
6160
*/
6261
public function testDateComparator($collection, $expected)
6362
{
64-
$obj = new ObjectCollection($collection);
65-
$obj->setComparator(new DateComparator());
66-
$elements = $obj->sort();
63+
$obj = new Context(new DateComparator());
64+
$elements = $obj->executeStrategy($collection);
6765

6866
$firstElement = array_shift($elements);
6967
$this->assertEquals($expected, $firstElement);

0 commit comments

Comments
 (0)