Skip to content

Instantly share code, notes, and snippets.

@brollypop
Created March 9, 2017 21:05
Show Gist options
  • Save brollypop/62a04d719306d55d78ae69a1465d0956 to your computer and use it in GitHub Desktop.
Save brollypop/62a04d719306d55d78ae69a1465d0956 to your computer and use it in GitHub Desktop.
Validation Problem Example
<?php
declare (strict_types = 1);
namespace Example\Domain;
use Example\Domain\CarInfo;
final class DriverParticipationRules
{
private $minimumAge;
private $maximumAge;
private $minimumPoints;
private $maximumMileage;
private $allowedCarTypes;
public function __construct(
int $minimumAge,
int $maximumAge,
int $minimumPoints,
int $maximumMileage,
array $allowedCarTypes
) {
$this->minimumAge = $minimumAge;
$this->maximumAge = $maximumAge;
$this->minimumPoints = $minimumPoints;
$this->maximumMileage = $maximumMileage;
$this->allowedCarTypes = $allowedCarTypes;
}
public function check(int $driverAge, int $driverPoints, CarInfo $carInfo): bool
{
return ($this->minimumAge <= $driverAge <= $this->maximumAge)
&& $driverPoints >= $this->minimumPoints
&& $carInfo->getMileage() <= $this->maximumMileage
&& in_array($carInfo->getType(), $this->allowedCarTypes);
}
}
<?php
declare (strict_types = 1);
namespace Example\Application\Command;
use Example\Domain\CarInfo;
final class ParticipateInRaceCommand
{
private $raceId;
private $driverId;
public function __construct(
int $raceId,
int $driverId
) {
$this->raceId = $raceId;
$this->driverId = $driverId;
}
public function getRaceId(): int
{
return $this->raceId;
}
public function getDriverId(): int
{
return $this->driverId;
}
}
<?php
declare (strict_types = 1);
namespace Example\Domain;
use Example\Domain\Exception\InvalidArgumentException;
use Example\Domain\Exception\ParticipationRequirementsNotMetException;
use Example\Domain\DriverParticipationRules;
final class Race
{
private $participants = [];
private $driverParticipationRules;
public function __construct(DriverParticipationRules $driverParticipationRules)
{
$this->driverParticipationRules = $driverParticipationRules;
}
public function addParticipant(Driver $driver)
{
if (false === $this->driverParticipationRules->check(
$driver->getAge(),
$driver->calculatePoints(),
$driver->getCarInfo()
)) {
throw new ParticipationRequirementsNotMetException('Driver does not meet the requirements.');
}
$this->participants[] = $driver;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment