-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator.php
87 lines (74 loc) · 1.7 KB
/
Calculator.php
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
<?php
/**
* Class that perform operations on numbers
*/
function cleanDelimiter($input)
{
if(strlen($input) > 1){
return preg_quote(substr($input, 1, strlen($input) - 2));
} else {
return preg_quote($input);
}
}
class Calculator
{
private $logger;
private $webservice;
function __construct(Logger $logger = null, Webservice $webservice = null)
{
$logger ? $this->logger = $logger : $this->logger = new Logger();
$webservice ? $this->webservice = $webservice : $this->webservice = new Webservice();
}
private function analyse($input){
$custom = "#^//(.+)\n(.*)$#";
$separator = "#([^\[]|\[[^\]]+\])#";
if(preg_match($custom, $input, $match)) {
preg_match_all($separator, $match[1], $customDelimiters);
return Array(
"content" => $match[2],
"delimiters" => $customDelimiters[0]
);
} else {
return Array(
"content" => $input,
"delimiters" => Array(",", "\n")
);
}
}
function add($string)
{
$sum = 0;
$input = $this->analyse($string);
$regex = "#(".implode("|", array_map("cleanDelimiter", $input['delimiters'])).")#";
$tokens = preg_split($regex, $input['content']);
$negatives = Array();
for($i = 0; $i < count($tokens); $i++) {
$tok = $tokens[$i];
if($tok < 0) {
$negatives[] = $tok;
} else if($tok > 1000) {
$tok = 0;
}
$sum += $tok;
}
if(count($negatives) > 0) {
throw new NegativeNumberException("Negative numbers : " + implode(",",$negatives));
}
try {
$this->logger->log($sum);
} catch(Exception $e) {
$this->webservice->notify();
}
return $sum;
}
}
class NegativeNumberException extends Exception
{}
class Logger
{
public function log($input){}
}
class Webservice
{
public function notify(){}
}