Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 4 | class ObjectTest extends PHPUnit_Framework_TestCase { |
||
| 5 | |||
| 6 | public function __construct(){ |
||
| 7 | |||
| 8 | $this->array = [ |
||
| 9 | 'a' => 123, |
||
| 10 | 'b' => 'hello', |
||
| 11 | 'c' => [ |
||
| 12 | 'r' => '#f00', |
||
| 13 | 'g' => '#0f0', |
||
| 14 | 'b' => '#00f', |
||
| 15 | ], |
||
| 16 | ]; |
||
| 17 | |||
| 18 | $this->object = (object)[ |
||
| 19 | 'a' => 123, |
||
| 20 | 'b' => 'hello', |
||
| 21 | 'c' => (object)[ |
||
| 22 | 'r' => '#f00', |
||
| 23 | 'g' => '#0f0', |
||
| 24 | 'b' => '#00f', |
||
| 25 | ], |
||
| 26 | ]; |
||
| 27 | |||
| 28 | } |
||
| 29 | |||
| 30 | public function testAccess(){ |
||
| 31 | $test = new Object($this->array, false); |
||
| 32 | $this->assertEquals($test['a'] ,123); // Access as Array from Array |
||
| 33 | $this->assertEquals($test->b ,'hello'); // Access as Object from Array |
||
| 34 | } |
||
| 35 | |||
| 36 | public function testDeepArray(){ |
||
| 37 | $test = new Object($this->array); |
||
| 38 | |||
| 39 | $this->assertEquals($test->c['r'] ,'#f00'); // Deep access as Object from Array |
||
| 40 | $this->assertEquals($test['c']->g ,'#0f0'); // Deep access as Array from Array |
||
| 41 | $this->assertEquals($test['c']['b'] ,'#00f'); // Deep access as DoubleArray from Array |
||
| 42 | $this->assertEquals($test->c->b ,'#00f'); // Deep access as DoubleObject from Array |
||
| 43 | } |
||
| 44 | |||
| 45 | public function testDeepObject(){ |
||
| 46 | $test = new Object($this->object); |
||
| 47 | |||
| 48 | $this->assertEquals($test->c['r'] ,'#f00'); // Deep access as Object from Object |
||
| 49 | $this->assertEquals($test['c']->g ,'#0f0'); // Deep access as Array from Object |
||
| 50 | $this->assertEquals($test['c']['b'] ,'#00f'); // Deep access as DoubleArray from Object |
||
| 51 | $this->assertEquals($test->c->b ,'#00f'); // Deep access as DoubleObject from Object |
||
| 52 | } |
||
| 53 | |||
| 54 | } |
||
| 55 |