Overview

Namespaces

  • chippyash
    • Type
      • Exceptions
      • Interfaces
      • Number
        • Complex
        • Rational
      • String

Classes

  • AbstractRationalType
  • GMPRationalType
  • RationalType
  • RationalTypeFactory
  • Overview
  • Namespace
  • Class
  • Tree
 1: <?php
 2: 
 3: /**
 4:  * Hard type support
 5:  * For when you absolutely want to know what you are getting
 6:  *
 7:  * Thanks to Florian Wolters for the inspiration
 8:  * @link http://github.com/FlorianWolters/PHP-Component-Number-Fraction
 9:  *
10:  * @author Ashley Kitson <akitson@zf4.biz>
11:  * @copyright Ashley Kitson, UK, 2014
12:  * @licence GPL V3 or later : http://www.gnu.org/licenses/gpl.html
13:  */
14: 
15: namespace chippyash\Type\Number\Rational;
16: 
17: use chippyash\Type\Number\IntType;
18: use chippyash\Type\BoolType;
19: 
20: /**
21:  * A rational number (i.e a fraction)
22:  *
23:  */
24: class RationalType extends AbstractRationalType
25: {
26:     /**
27:      * Map of values for this type
28:      * @var array
29:      */
30:     protected $valueMap = array(
31:         0 => array('name' => 'num', 'class' => 'chippyash\Type\Number\IntType'),
32:         1 => array('name' => 'den', 'class' => 'chippyash\Type\Number\IntType')
33:     );
34:     
35:     /**
36:      * Construct new rational
37:      * Use the RationalTypeFactory to create rationals from native PHP types
38:      *
39:      * @param \chippyash\Type\Number\IntType $num numerator
40:      * @param \chippyash\Type\Number\IntType $den denominator
41:      * @param \chippyash\Type\BoolType $reduce -optional: default = true
42:      */
43:     public function __construct(IntType $num, IntType $den, BoolType $reduce = null)
44:     {
45:         if ($reduce != null) {
46:             $this->reduce = $reduce();
47:         }
48:         parent::__construct($num, $den);
49:     }
50: 
51:     /**
52:      * Reduce this number to it's lowest form
53:      *
54:      * @return void
55:      */
56:     protected function reduce()
57:     {
58:         /** @noinspection PhpUndefinedMethodInspection */
59:         $gcd = $this->gcd($this->value['num']->get(), $this->value['den']->get());
60:         if ($gcd > 1) {
61:             $this->value['num']->set($this->value['num']->get() / $gcd) ;
62:             $this->value['den']->set($this->value['den']->get() / $gcd);
63:         }
64:     }
65: 
66:     /**
67:      * Return GCD of two numbers
68:      *
69:      * @param int $a
70:      * @param int $b
71:      *
72:      * @return int
73:      */
74:     private function gcd($a, $b)
75:     {
76:         return $b ? $this->gcd($b, $a % $b) : $a;
77:     }
78: }
79: 
Chippyash Strong Types API documentation generated by ApiGen 2.8.0