Browse Source

added PropertyAccessTrait

Fabian Peter Hammerle 7 years ago
parent
commit
fdf85ed702
3 changed files with 117 additions and 0 deletions
  1. 34 0
      PropertyAccessTrait.php
  2. 82 0
      tests/PropertyAccessTraitTest.php
  3. 1 0
      tests/autoload.php

+ 34 - 0
PropertyAccessTrait.php

@@ -0,0 +1,34 @@
+<?php
+
+namespace fphammerle\helpers;
+
+trait PropertyAccessTrait
+{
+    /**
+     * @param string $name
+     * @return mixed
+     */
+    public function __get($name)
+    {
+        $getter_name = 'get' . $name;
+        if(!method_exists($this, $getter_name)) {
+            throw new \Exception('unknown property ' . $name);
+        } else {
+            return $this->$getter_name();
+        }
+    }
+
+    /**
+     * @param string $name
+     * @param mixed $value
+     */
+    public function __set($name, $value)
+    {
+        $setter_name = 'set' . $name;
+        if(!method_exists($this, $setter_name)) {
+            throw new \Exception('unknown property ' . $name);
+        } else {
+            $this->$setter_name($value);
+        }
+    }
+}

+ 82 - 0
tests/PropertyAccessTraitTest.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace fphammerle\helpers\tests;
+
+class TestClass
+{
+    use \fphammerle\helpers\PropertyAccessTrait;
+
+    private $_a;
+
+    public function __construct($a)
+    {
+        $this->_a = $a;
+    }
+
+    public function getA()
+    {
+        return $this->_a;
+    }
+
+    public function setA($value)
+    {
+        $this->_a = $value;
+    }
+
+    public function getSquare()
+    {
+        return $this->_a * $this->_a;
+    }
+
+    public function setCubic($c)
+    {
+        $this->_a = pow($c, 1/3);
+    }
+}
+
+class PropertyAccessTraitTest extends \PHPUnit_Framework_TestCase
+{
+    public function testGetPublic()
+    {
+        $o = new TestClass(2);
+        $this->assertEquals(2, $o->a);
+    }
+
+    public function testGetPublic2()
+    {
+        $o = new TestClass(3);
+        $this->assertEquals(9, $o->square);
+    }
+
+    /**
+     * @expectedException \Exception
+     */
+    public function testGetUnknown()
+    {
+        $o = new TestClass(2);
+        $o->cubic;
+    }
+
+    public function testSetPublic()
+    {
+        $o = new TestClass(1);
+        $o->a = 2;
+        $this->assertEquals(2, $o->getA());
+    }
+
+    public function testSetPublic2()
+    {
+        $o = new TestClass(3);
+        $o->cubic = 8;
+        $this->assertEquals(2, $o->getA(), '', 0.1);
+    }
+
+    /**
+     * @expectedException \Exception
+     */
+    public function testSetUnknown()
+    {
+        $o = new TestClass(1);
+        $o->square = 4;
+    }
+}

+ 1 - 0
tests/autoload.php

@@ -6,4 +6,5 @@ error_reporting(-1);
 require_once(__DIR__ . '/../ArrayHelper.php');
 require_once(__DIR__ . '/../DateTimeHelper.php');
 require_once(__DIR__ . '/../Image.php');
+require_once(__DIR__ . '/../PropertyAccessTrait.php');
 require_once(__DIR__ . '/../StringHelper.php');