-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCalculator.php
More file actions
90 lines (75 loc) · 3.05 KB
/
Copy pathCalculator.php
File metadata and controls
90 lines (75 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* @author Pierre-Henry Soria <pierrehenrysoria@gmail.com>
* @copyright (c) 2015, Pierre-Henry Soria. All Rights Reserved.
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
* @link http://github.com/pH-7/
*/
class Calculator
{
private $_iLeftOpr, $_iRightOpr, $_sSummary, $_mResult;
public function __construct($sOperation, $iLeftOpr, $iRightOpr)
{
$this->_iLeftOpr = (int) $iLeftOpr;
$this->_iRightOpr = (int) $iRightOpr;
$this->exec($sOperation);
}
/**
* Return the summary & result in XML format.
*/
public function xmlOutput()
{
header('Content-Type:text/xml'); // Set the XML header
/*
* Thanks htmlspecialchars(), I make the summary text safe for XML syntax */
return
'<output>
<result>' . $this->_mResult . '</result>
<summary>' . htmlspecialchars($this->_sSummary) . '</summary>
</output>';
}
public function result()
{
return $this->_mResult;
}
public function summary()
{
return $this->_sSummary;
}
protected function exec($sOperation)
{
switch ($sOperation)
{
case 'add':
$this->_mResult = ($this->_iLeftOpr+$this->_iRightOpr);
$this->_sSummary = $this->_iLeftOpr . ' + ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'subtract':
$this->_mResult = ($this->_iLeftOpr-$this->_iRightOpr);
$this->_sSummary = $this->_iLeftOpr . ' - ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'multiply':
$this->_mResult = ($this->_iLeftOpr*$this->_iRightOpr);
$this->_sSummary = $this->_iLeftOpr . ' * ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'divide':
$this->_mResult = ($this->_iLeftOpr/$this->_iRightOpr);
$this->_sSummary = $this->_iLeftOpr . ' / ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'logical_and':
$this->_mResult = ($this->_iLeftOpr === $this->_iRightOpr) ? 'true' : 'false';
$this->_sSummary = $this->_iLeftOpr . ' && ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'logical_or':
$this->_mResult = ($this->_iLeftOpr === $this->_iRightOpr || $this->_iRightOpr === $this->_iLeftOpr) ? 'true' : 'false';
$this->_sSummary = $this->_iLeftOpr . ' || ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
case 'power':
$this->_mResult = ($this->_iLeftOpr^$this->_iRightOpr);
$this->_sSummary = $this->_iLeftOpr . ' ^ ' . $this->_iRightOpr . ' = ' . $this->_mResult;
break;
default:
throw new InvalidArgumentException(sprintf('"%s" is an invalid operation.', str_replace('_', '', $sOperation)));
}
}
}