Last active
January 28, 2016 20:59
How to validate relationships on object creation. ---> code execution: https://3v4l.org/t7JqO#v700
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
namespace App | |
{ | |
class Product | |
{ | |
private $id; | |
private $name; | |
private $volumes; | |
/** | |
* Product constructor. | |
* @param int $id | |
* @param string $name | |
* @param array $volumes | |
* @throws \InvalidArgumentException | |
*/ | |
public function __construct(int $id, string $name, array $volumes) | |
{ | |
$this->id = $id; | |
$this->name = $name; | |
if (count($volumes) === 0) { | |
throw new \InvalidArgumentException('Your product must have 1 product at least.'); | |
} | |
$this->volumes = $this->prepareVolumes($volumes); | |
} | |
private function prepareVolumes(array $volumes) | |
{ | |
foreach ($volumes as $volume) { | |
$volume->setProduct($this); | |
} | |
return $volumes; | |
} | |
} | |
class Volume | |
{ | |
protected $id; | |
protected $product; | |
protected $description; | |
public function __construct(string $description) | |
{ | |
$this->description = $description; | |
} | |
public function setProduct(Product $product) | |
{ | |
$this->product = $product; | |
} | |
} | |
class ProductTest | |
{ | |
public function __construct() | |
{ | |
$volume1 = new Volume('part-1'); | |
$volume2 = new Volume('part-2'); | |
$volume3 = new Volume('part-3'); | |
$product = new Product(1, 'BED', [$volume1, $volume2, $volume3]); | |
$invalidProduct = new Product(2, 'Table', []); | |
} | |
} | |
return new ProductTest(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment