Skip to content

Instantly share code, notes, and snippets.

@pH-7
Last active March 28, 2022 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pH-7/5ba7f83a9e1befc46a68379301eec41e to your computer and use it in GitHub Desktop.
Save pH-7/5ba7f83a9e1befc46a68379301eec41e to your computer and use it in GitHub Desktop.
Source code of my YouTube tutorial about handling multiple exceptions with PHP 7.1 - https://www.youtube.com/channel/UCGqLuT0upPiocwYSnnmqt2g
<?php
require 'Person.php';
try {
$person = new Person('Pierre');
echo $person->greeting('morning'); // can be 'morning', 'afternoon', or 'evening'
} catch(InvalidNameException | InvalidDayMomentException $err) { // Handling multiple exceptions with PHP 7.1
echo $err->getMessage();
}
<?php
class InvalidDayMomentException extends InvalidArgumentException
{
}
<?php
class InvalidNameException extends InvalidArgumentException
{
}
<?php
/**
* (c) Pierre-Henry Soria <hi@ph7.me> - All Rights Reserved.
*/
declare(strict_types=1);
require_once 'InvalidNameException.php';
require_once 'InvalidDayMomentException.php';
class Person
{
private const MIN_NAME_LENGTH = 2;
private const MAX_NAME_LENGTH = 20;
private const MORNING = 'morning';
private const AFTERNOON = 'afternoon';
private const EVENING = 'evening';
private const VALID_DAY_MOMENTS = [
self::MORNING,
self::AFTERNOON,
self::EVENING
];
private string $name;
public function __construct(string $name)
{
if (!$this->isNameValid($name)) {
throw new InvalidNameException(
sprintf('"%s" name is invalid.', $name)
);
}
$this->name = $name;
}
public function greeting($time): string
{
if (!$this->isTimeOfTheDayValid($time)) {
throw new InvalidDayMomentException(
sprintf('"%s" is an invalid moment of the day.', $time)
);
}
return 'Good ' . $time . ' ' . $this->name . ' ' . $this->getEmoji($time);
}
private function isNameValid(string $value): bool
{
return strlen($value) > self::MIN_NAME_LENGTH && strlen($value) < self::MAX_NAME_LENGTH;
}
private function isTimeOfTheDayValid(string $time): bool
{
return in_array($time, self::VALID_DAY_MOMENTS);
}
private function getEmoji(string $type): string
{
if ($type === self::MORNING) {
return '☀️';
}
if ($type === self::AFTERNOON) {
return '🕶';
}
if ($type === self::EVENING) {
return '🌝️';
}
return '👋'; // Default value
}
}
@pH-7
Copy link
Author

pH-7 commented Mar 28, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment