<?php
 namespace App\Utils\InvoiceDueDate; class Profile { protected $elements = []; public function addElement(\App\Utils\InvoiceDueDate\Element $element) { $this->elements[] = $element; } public function getElements() { return $this->elements; } public function reset() { $this->elements = []; } public function check() { if (!$this->elements) { throw new \RuntimeException('No elements defined this profile.'); } $foundServiceCodes = []; $defaultServiceCode = false; foreach ($this->elements as $element) { $element->check(); foreach ($element->getServiceCodes() as $sc) { if (!$sc) { $defaultServiceCode = true; } if ($foundServiceCodes[$sc]) { throw new \RuntimeException(sprintf('Multiple elements defined for service code: %s', $sc)); } $foundServiceCodes[$sc] = true; } } if (!$defaultServiceCode) { throw new \RuntimeException('You must include the default service code on a profile element.'); } } public function exportAsArray() { $this->check(); $return = []; foreach ($this->elements as $element) { $return[] = $element->exportAsArray(); } return $return; } public function importFromArray(array $profile) { $this->reset(); foreach ($profile as $elArr) { $elObj = new \App\Utils\InvoiceDueDate\Element(); $elObj->importFromArray($elArr); $this->addElement($elObj); } } public function calculateDueDate($invoiceDate, $serviceCode) { $elementByServiceCode = null; $elementDefault = null; foreach ($this->elements as $element) { if ($serviceCode and in_array($serviceCode, $element->getServiceCodes())) { $elementByServiceCode = $element; } if (in_array('', $element->getServiceCodes())) { $elementDefault = $element; } } $elementFinal = null; if ($elementByServiceCode) { $elementFinal = $elementByServiceCode; } elseif ($elementDefault) { $elementFinal = $elementDefault; } else { throw new \RuntimeException('Invalid due profile used - not even the default service code is found in the profile.'); } return $elementFinal->calculateDueDate($invoiceDate); } } 