Skip to content

Commit e4cc3c3

Browse files
author
Jordi Martinez
committed
PHP-Unit-Test Implements tests for chapter 9
Implements tests for Chapter 09
1 parent 0cb676b commit e4cc3c3

27 files changed

+787
-5
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ php -S localhost:8000
2222
## Dependencies
2323

2424
In order to run tests you would need to install some external dependencies, like PHP Unit. To do so, as you learned in
25-
the Book, you use **Composer**. If you look into the composer.json file included, you would see the following dependencies:
25+
the Book, you use **Composer**. If you look into the __composer.json__ file included, you would see the following dependencies:
2626

2727
- PHPUnit: it is the framework most used in the PHP community to run unit tests.
2828
- Symfony Dom Crawler: a library you would need to test the post of HTML forms to the web server. (you would not need this until
2929
Chapter 6).
30-
- Symfony CSS Selector: a library to filter the contents of HTML documents using HTML tags and CSS selectors.
30+
- Symfony CSS Selector: a library to filter the contents of HTML documents using HTML tags and CSS selectors.
31+
- Monolog: a library to handle logging.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
$exceptionHandler = function (Throwable $e) {
4+
$message = sprintf('%s [%d]: %s', get_class($e), $e->getCode(), $e->getMessage());
5+
$msgLength = mb_strlen($message);
6+
$line = str_repeat('-', $msgLength);
7+
echo $line, PHP_EOL;
8+
echo $message, PHP_EOL;
9+
echo '> File: ', $e->getFile(), PHP_EOL;
10+
echo '> Line: ', $e->getLine(), PHP_EOL;
11+
echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL;
12+
echo $line, PHP_EOL;
13+
};
14+
15+
$errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) {
16+
$exception = new ErrorException($message, $code, $code, $file, $line);
17+
$exceptionHandler($exception);
18+
if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) {
19+
exit(1);
20+
}
21+
};
22+
23+
set_error_handler($errorHandler);
24+
set_exception_handler($exceptionHandler);

app/Chapter08/Activity/factorial.php

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
3+
$exceptionHandler = function (Throwable $e) {
4+
static $fh;
5+
if (is_null($fh)) {
6+
$fh = fopen(__DIR__ . '/app.log', 'a');
7+
if (!$fh) {
8+
echo 'Unable to access the log file.', PHP_EOL;
9+
exit(1);
10+
}
11+
}
12+
$message = sprintf('%s [%d]: %s', get_class($e), $e->getCode(), $e->getMessage());
13+
$msgLength = mb_strlen($message);
14+
$line = str_repeat('-', $msgLength);
15+
$logMessage = sprintf(
16+
"%s\n%s\n> File: %s\n> Line: %d\n> Trace: %s\n%s\n",
17+
$line,
18+
$message,
19+
$e->getFile(),
20+
$e->getLine(),
21+
$e->getTraceAsString(),
22+
$line
23+
);
24+
fwrite($fh, $logMessage);
25+
};
26+
27+
$errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) {
28+
$exception = new ErrorException($message, $code, $code, $file, $line);
29+
$exceptionHandler($exception);
30+
if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) {
31+
exit(1);
32+
}
33+
};
34+
35+
set_error_handler($errorHandler);
36+
set_exception_handler($exceptionHandler);
37+
38+
class NotANumber extends Exception
39+
{
40+
}
41+
42+
class DecimalNumber extends Exception
43+
{
44+
}
45+
46+
class NumberIsZeroOrNegative extends Exception
47+
{
48+
}
49+
50+
function printError(string $message): void
51+
{
52+
echo '(!) ', $message, PHP_EOL;
53+
}
54+
55+
function calculateFactorial($number): int
56+
{
57+
if (!is_numeric($number)) {
58+
throw new NotANumber(sprintf('%s is not a number.', $number));
59+
}
60+
$number = $number * 1;
61+
if (is_float($number)) {
62+
throw new DecimalNumber(sprintf('%s is decimal; integer is expected.', $number));
63+
}
64+
if ($number < 1) {
65+
throw new NumberIsZeroOrNegative(sprintf('Given %d while higher than zero is expected.', $number));
66+
}
67+
$factorial = 1;
68+
for ($i = 2; $i <= $number; $i++) {
69+
$factorial *= $i;
70+
}
71+
return $factorial;
72+
}
73+
74+
$arguments = array_slice($argv, 1);
75+
if (!count($arguments)) {
76+
printError('At least one number is required.');
77+
} else {
78+
foreach ($arguments as $argument) {
79+
try {
80+
$factorial = calculateFactorial($argument);
81+
echo $argument, '! = ', $factorial, PHP_EOL;
82+
} catch (NotANumber | DecimalNumber | NumberIsZeroOrNegative $e) {
83+
printError(sprintf('[%s]: %s', get_class($e), $e->getMessage()));
84+
} catch (Throwable $e) {
85+
printError("Unexpected error occured for [$argument] input number.");
86+
$exceptionHandler($e);
87+
}
88+
}
89+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
$errorHandler = function (int $code, string $message, string $file, int $line) {
4+
echo date(DATE_W3C), " :: $message, in [$file] on line [$line] (error code $code)", PHP_EOL;
5+
};
6+
7+
set_error_handler($errorHandler, E_ALL);
8+
9+
echo $width / $height, PHP_EOL;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
$exceptionHandler = function (Throwable $e) {
4+
$message = sprintf('%s [%d]: %s', get_class($e), $e->getCode(), $e->getMessage());
5+
$msgLength = mb_strlen($message);
6+
$line = str_repeat('-', $msgLength);
7+
echo $line, PHP_EOL;
8+
echo $message, PHP_EOL;
9+
echo '> File: ', $e->getFile(), PHP_EOL;
10+
echo '> Line: ', $e->getLine(), PHP_EOL;
11+
echo '> Trace: ', PHP_EOL, $e->getTraceAsString(), PHP_EOL;
12+
echo $line, PHP_EOL;
13+
};
14+
15+
$errorHandler = function (int $code, string $message, string $file, int $line) use ($exceptionHandler) {
16+
$exception = new ErrorException($message, $code, $code, $file, $line);
17+
$exceptionHandler($exception);
18+
if (in_array($code, [E_ERROR, E_RECOVERABLE_ERROR, E_USER_ERROR])) {
19+
exit(1);
20+
}
21+
};
22+
23+
set_error_handler($errorHandler);
24+
set_exception_handler($exceptionHandler);

app/Chapter08/Exercise10/date.php

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
require_once 'all-errors-handler.php';
4+
5+
class Disposable extends Exception
6+
{
7+
}
8+
9+
function handle(array $input)
10+
{
11+
if (!isset($input[1])) {
12+
throw new Disposable('A class name is required as the first argument (one of DateTime or DateTimeImmutable).');
13+
}
14+
$calleeName = $input[1];
15+
if (!in_array($calleeName, [DateTime::class, DateTimeImmutable::class])) {
16+
throw new Disposable('One of DateTime or DateTimeImmutable is expected.');
17+
}
18+
$time = $input[2] ?? 'now';
19+
$timezone = $input[3] ?? 'UTC';
20+
try {
21+
$dateTimeZone = new DateTimeZone($timezone);
22+
} catch (Exception $e) {
23+
throw new Disposable(sprintf('Unknown/Bad timezone: [%s]', $timezone));
24+
}
25+
try {
26+
$dateTime = new $calleeName($time, $dateTimeZone);
27+
} catch (Exception $e) {
28+
throw new Disposable(sprintf('Cannot build date from [%s]', $time));
29+
}
30+
return $dateTime;
31+
}
32+
33+
try {
34+
$output = handle($argv);
35+
echo 'Result: ', print_r($output, true);
36+
} catch (Disposable $e) {
37+
echo '(!) ', $e->getMessage(), PHP_EOL;
38+
exit(1);
39+
}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
$errorHandler = function (int $code, string $message, string $file, int $line) {
4+
static $stream;
5+
if (is_null($stream)) {
6+
$stream = fopen(__DIR__ . '/app.log', 'a');
7+
}
8+
fwrite(
9+
$stream,
10+
date(DATE_W3C) . " :: $message, in [$file] on line [$line] (error code $code)" . PHP_EOL
11+
);
12+
};
13+
14+
set_error_handler($errorHandler, E_ALL);
15+
16+
echo $width / $height, PHP_EOL;
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
$errorHandler = function (int $code, string $message, string $file, int $line) {
4+
echo date(DATE_W3C), " :: $message, in [$file] on line [$line] (error code $code)", PHP_EOL;
5+
if ($code === E_USER_ERROR) {
6+
exit(1);
7+
}
8+
};
9+
10+
set_error_handler($errorHandler, E_ALL);
11+
12+
return $errorHandler;

app/Chapter08/Exercise3/sqrt.php

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
require_once 'error-handler.php';
4+
5+
if (!array_key_exists(1, $argv)) {
6+
trigger_error('This script requires a number as first argument.', E_USER_ERROR);
7+
}
8+
9+
$input = $argv[1];
10+
11+
if (!is_numeric($input)) {
12+
trigger_error(sprintf('A number is expected, got %s.', $input), E_USER_ERROR);
13+
}
14+
15+
if (is_float($input * 1)) {
16+
$input = round($input);
17+
trigger_error(
18+
sprintf(
19+
'Decimal numbers are not allowed for this operation. Will use the rounded integer value [%d].',
20+
$input
21+
),
22+
E_USER_WARNING
23+
);
24+
}
25+
26+
if ($input < 0) {
27+
$input = abs($input);
28+
trigger_error(
29+
sprintf(
30+
'A negative number is not allowed for this operation. Will use the absolute value [%d].',
31+
$input
32+
),
33+
E_USER_WARNING
34+
);
35+
}
36+
37+
echo sprintf('sqrt(%d) = ', $input), sqrt($input), PHP_EOL;
+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
$errorHandler = function (int $code, string $message, string $file, int $line) {
4+
echo date(DATE_W3C), " :: $message, in [$file] on line [$line] (error code $code)", PHP_EOL;
5+
if ($code === E_USER_ERROR) {
6+
exit(1);
7+
}
8+
};
9+
10+
set_error_handler($errorHandler, E_ALL);
11+
12+
return $errorHandler;
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
$errorHandler = require_once 'error-handler.php';
4+
5+
register_shutdown_function(
6+
function () use ($errorHandler) {
7+
if ($error = error_get_last()) {
8+
if (in_array($error['type'], [E_ERROR, E_RECOVERABLE_ERROR], true)) {
9+
$errorHandler(
10+
$error['type'],
11+
$error['message'],
12+
$error['file'],
13+
$error['line']
14+
);
15+
}
16+
}
17+
}
18+
);
19+
20+
new UnknownClass();
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
echo 'SCRIPT START.', PHP_EOL;
4+
5+
try {
6+
7+
echo 'Run TRY block.', PHP_EOL;
8+
if (!isset($argv[1])) {
9+
echo 'NO ARGUMENT: Will throw exception.', PHP_EOL;
10+
throw new LogicException('Argument #1 is required.');
11+
}
12+
13+
echo 'ARGUMENT: ', $argv[1], PHP_EOL;
14+
var_dump(new $argv[1]);
15+
16+
} catch (Exception $e) {
17+
18+
echo 'EXCEPTION: ', sprintf('%s in %s at line %d', $e->getMessage(), $e->getFile(), $e->getLine()), PHP_EOL;
19+
20+
} catch (Error $e) {
21+
22+
echo 'ERROR: ', sprintf('%s in %s at line %d', $e->getMessage(), $e->getFile(), $e->getLine()), PHP_EOL;
23+
24+
} finally {
25+
26+
echo "FINALLY block gets executed.\n";
27+
28+
}
29+
30+
echo "Outside TRY-CATCH.\n";
31+
32+
echo 'SCRIPT END.', PHP_EOL;

app/Chapter08/Exercise5/basic-try.php

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
echo 'SCRIPT START.', PHP_EOL;
4+
5+
try {
6+
7+
echo 'Run TRY block.', PHP_EOL;
8+
if (!isset($argv[1])) {
9+
echo 'NO ARGUMENT: Will throw exception.', PHP_EOL;
10+
throw new LogicException('Argument #1 is required.');
11+
}
12+
13+
echo 'ARGUMENT: ', $argv[1], PHP_EOL;
14+
var_dump(new $argv[1]);
15+
16+
} catch (Exception $e) {
17+
18+
echo 'EXCEPTION: ', sprintf('%s in %s at line %d', $e->getMessage(), $e->getFile(), $e->getLine()), PHP_EOL;
19+
20+
} finally {
21+
22+
echo "FINALLY block gets executed.\n";
23+
24+
}
25+
26+
echo "Outside TRY-CATCH.\n";
27+
28+
echo 'SCRIPT END.', PHP_EOL;

0 commit comments

Comments
 (0)