3 * A shipping company may be founded with this class
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class ShippingCompany extends BaseSimulator implements Customer, ContractPartner {
26 * Full name of this company
28 private $companyName = "Namenlose Reederei";
31 * Shorted name of this company
33 private $shortName = "";
36 * Instance of the founder
38 private $founderInstance = null;
41 * Headquarter harbor instance
43 private $hqInstance = null;
46 * Employed people by this company
48 private $employeeList = null;
51 * List of all assigned shipyards
53 private $shipyardList = null;
58 private $ownedShips = null;
61 * Work constracts this company is currently working on
63 private $contractList = null;
65 // Exception constants
66 const EXCEPTION_USER_OWNS_NO_COMPANY = 0x200;
69 * Protected constructor
73 protected function __construct () {
74 // Call parent constructor
75 parent::__construct(__CLASS__);
78 $this->setObjectDescription("A shipping company class");
80 // Generate unique ID number
81 $this->generateUniqueId();
84 $this->removeSystemArray();
88 * Creates an instance of this company class or throws an exception if the
89 * given user owns no company.
91 * @param $userInstance A user class
92 * @return $companyInstance Prepared company instance
94 public final static function createShippingCompany (BaseUser $userInstance) {
96 $companyInstance = new ShippingCompany();
98 // Does the given user owns a company?
99 if ($companyInstance->ifUserParticipatesInCompany($userInstance)) {
100 // Then do some nastly caching here but don't throw an exception
101 // because then you will hurt our web helpers... :/
102 $companyInstance->partialStub("Don't throw exceptions here.");
106 $companyInstance->initCompanyLists();
109 return $companyInstance;
113 * Checks wether the given user participates in a company
115 * @param $userInstance An instance of a user class
116 * @return $participates Wether the user participates at lease in one company
118 protected function ifUserParticipatesInCompany (BaseUser $userInstance) {
119 // By default no user owns any company... ;)
120 $participates = false;
122 // Get a company database wrapper class
123 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('company_db_wrapper_class');
125 // Ask the wrapper if this user participates
126 $participates = $wrapperInstance->ifUserParticipatesInCompany($userInstance);
128 // Get the result instance
129 $resultInstance = $wrapperInstance->getResultInstance();
131 // Caches the result instance here, if set (we don't the wrapper anymore!)
132 if ($resultInstance instanceof SearchableResult) {
133 // Set the result instance
134 $this->setResultInstance($resultInstance);
138 return $participates;
142 * Checks wether the current user in registry is the company founder
144 * @return $isFounder Wether the current user is the company founder
146 public function ifUserIsFounder () {
147 // Default is not the founder
150 // Get result instance
151 $resultInstance = $this->getResultInstance();
154 if ($resultInstance instanceof SearchableResult) {
155 // Result found so analyse it
156 $this->partialStub("Check if user is company founder.");
164 * Checks wether the current user in registry is the company owner
166 * @return $isOwner Wether the current user is the company owner
168 public function ifUserIsOwner () {
169 // Default is not the owner
172 // Get result instance
173 $resultInstance = $this->getResultInstance();
176 if ($resultInstance instanceof SearchableResult) {
177 // Result found so analyse it
178 $this->partialStub("Check if user is company owner.");
186 * Checks wether the current user in registry is an employee in this company
188 * @return $isOwner Wether the current user is an employee in this company
190 public function ifUserIsEmployee () {
191 // Default is no employee
194 // Get result instance
195 $resultInstance = $this->getResultInstance();
198 if ($resultInstance instanceof SearchableResult) {
199 // Result found so he is employee
207 //----------------------------------------------------------------------------
208 // From here is very old code which needs to be translated and changed heavily
209 //----------------------------------------------------------------------------
212 * Intialize all lists
215 * @todo Maybe we don't need these big lists anymore?! So we can deprecate/remove it
217 protected function initCompanyLists () {
219 $this->employeeList = new FrameworkArrayObject("FakedEmployeeList");
222 $this->shipyardList = new FrameworkArrayObject("FakedShipyardList");
225 $this->contractList = new FrameworkArrayObject("FakedContractList");
228 // Setter-Methode fuer Firmennamen
229 public final function setCompanyName ($companyName) {
230 $this->companyName = (string) $companyName;
233 // Getter-Methode fuer Firmennamen
234 public final function getCompanyName () {
235 return $this->companyName;
238 // Setter-Methode fuer Firmensitz
239 public final function setHQInstance (Harbor $hqInstance) {
240 $this->hqInstance = $hqInstance;
244 private function initShortName () {
245 // Mindestens eine Leerstelle?
246 $dummy = explode(" ", $this->getCompanyName());
247 foreach ($dummy as $part) {
248 $this->shortName .= substr($part, 0, 1);
252 // Reedereien Werften bauen lassen
253 public function createShipyardInHarbor($shipyardName, Harbor $harborInstance) {
254 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> baut im <strong>%s</strong> eine Werft <strong>%s</strong>.",
257 $this->getCompanyName(),
258 $harborInstance->getHarborName(),
262 // Wird im HQ gebaut?
263 if ($this->hqInstance->equals($harborInstance)) {
264 // Die neue Werft wird im HQ gebaut!
265 $this->hqInstance->addNewShipyardNotify($shipyardName, $this);
266 // Die Werft drueber in Kenntnis setzen, welcher Reederei sie angehoert
268 // Ausserhalb des Heimathafens soll eine Werft gebaut werden
269 $harborInstance->addNewShipyardNotify($shipyardName, $this);
273 // Setter fuer Reederei-Gruender
274 public final function setCompanyFounder(CompanyEmployee $founderInstance) {
275 $this->founderInstance = $founderInstance;
278 // Getter for founder instance
279 public final function getFounderInstance () {
280 return $this->founderInstance;
283 // Neue(n) Angestellte(n) in Angestellten-Liste aufnehmen
284 public function addNewEmployee (SimulatorPersonell $employeeInstance) {
285 $this->employeeList->append($employeeInstance);
288 // Neue Werft in Liste aufnehmen
289 public function addNewShipyard (Shipyard $shipyardInstance) {
290 $this->shipyardList->append($shipyardInstance);
293 // Neue Mitarbeiter per Zufall einstellen/rekrutieren
294 public function recruitRandomEmployees($amount, SimulatorPersonell $personellInstance) {
295 // Anzahl Mitarbeiter absichern
296 $amount = (int) $amount;
298 // Debug-Meldung ausgeben
299 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> stellt per Zufall <strong>%d</strong> neue Mitarbeiter ein.",
302 $this->getCompanyName(),
306 // Gesamtanzahl verfuegbarer Erwerbsloser holen
307 $totalUnemployed = $personellInstance->getAllUnemployed();
309 // Existiert die gewuenschte Anzahl freier Arbeiter? (doppelt geht derzeit nicht)
310 if ($totalUnemployed < $amount) {
311 // Reichte nicht aus!
312 throw new ToMuchEmployeesException(array($amount, $personellInstance->getAllUnemployed()), self::EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES);
315 // Get list for all unemployed people
316 $list = $personellInstance->getSpecialPersonellList(false); // Should be cached
318 // Get iterator of the list
319 $iterator = $list->getIterator();
321 // Get the requested amount of personell
322 for ($idx = 0; $idx < $amount; $idx++) {
324 // Is this personl unemployed?
325 while (is_null($employee) || $employee->isEmployed()) {
326 // Generate random number
327 $pos = mt_rand(0, ($totalUnemployed - 1)); // Don't remove the -1 here:
328 // E.g. 100 entries means latest position is 99...
330 // Seek for the position
331 $iterator->seek($pos);
333 // Is the current position valid?
334 if ($iterator->valid()) {
336 $employee = $iterator->current();
338 // Should normally not happen... :(
339 throw new StructuresOutOfBoundsException($idx, self::EXCEPTION_INDEX_OUT_OF_BOUNDS);
343 // A dummy just for the description and real class
344 $dummy = CompanyEmployee::createCompanyEmployee("", "", "M", 1970, 1, 1, $employee->isMarried(), 0);
346 // Make this person employed and give him some money to work
347 $employee->setEmployed(true);
348 $employee->setObjectDescription($dummy->getObjectDescription());
349 $employee->setRealClass($dummy->__toString());
350 $employee->increaseSalary((mt_rand(7, 14) * 100)); // Are 700 to 1400 EUR for the begin okay?
353 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> stellt den/die Angestellte(n) <strong>%s %s</strong> ein.",
356 $this->getCompanyName(),
357 $employee->getSurname(),
358 $employee->getFamily()
362 $this->addNewEmployee($employee);
366 $personellInstance->resetCache();
368 // Debug-Meldung ausgeben
369 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat per Zufall <strong>%d</strong> neue Mitarbeiter eingestellt.",
372 $this->getCompanyName(),
377 // Distribute all personells on all shipyards
378 public function distributeAllPersonellOnShipyards () {
379 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> verteilt alle ihre <strong>%d</strong> Mitarbeiter auf alle <strong>%d</strong> Werft(en).",
382 $this->getCompanyName(),
383 $this->getTotalEmployee(),
384 $this->getTotalShipyards()
387 // Do we have some shipyards?
388 if (is_null($this->shipyardList)) {
389 // No shipyards created
390 throw new NoShipyardsConstructedException($this, self::EXCEPTION_HARBOR_HAS_NO_SHIPYARDS);
393 // Get iterator for shipyards
394 $shipyardIter = $this->shipyardList->getIterator();
396 // Iterate through all employees
397 for ($idx = $this->employeeList->getIterator(); $idx->valid(); $idx->next()) {
398 // Is the shipyard iterator still okay?
399 if (!$shipyardIter->valid()) {
400 // Rewind to first position
401 $shipyardIter->seek(0);
404 // Get Shipyard object
405 $shipyard = $shipyardIter->current();
407 // Is this a Shipyard object?
408 if (is_null($shipyard)) {
410 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
411 } elseif (!is_object($shipyard)) {
412 // Not an object! ;-(
413 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
414 } elseif (!$shipyard->isClass("Shipyard")) {
415 // Nope, so throw exception
416 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
419 // Add employee to the shipyard
420 $shipyard->addNewPersonell($idx->current());
422 // Continue to next shipyard
423 $shipyardIter->next();
427 // Getter for total employees
428 public final function getTotalEmployee () {
430 $total = $this->employeeList->count();
433 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat <strong>%d</strong> Mitarbeiter.",
436 $this->getCompanyName(),
444 // Getter for total shipyards
445 public final function getTotalShipyards () {
446 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Für die Reederei <strong>%s</strong> werden die Anzahl der Werften in allen Häfen ermittelt.",
449 $this->getCompanyName()
452 // Do we have some shipyards?
453 if (is_null($this->shipyardList)) {
454 // No shipyards created
455 throw new NoShipyardsConstructedException($this, self::EXCEPTION_HARBOR_HAS_NO_SHIPYARDS);
459 $total = $this->shipyardList->count();
462 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat <strong>%d</strong> Werft(en).",
465 $this->getCompanyName(),
473 // Add a ship type (class) to all shipyards
474 public function addShipTypeToAllShipyards ($shipType) {
476 $shipType = (string) $shipType;
478 // Is the class there?
479 if (!class_exists($shipType)) {
481 throw new ClassNotFoundException($shipType, self::EXCEPTION_CLASS_NOT_FOUND);
485 eval(sprintf("\$shipInstance = %s::create%s(\"M/S Dummy\");",
491 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> baut in allen Werften bald Schiffe vom Typ <strong>%s</strong>.",
494 $this->getCompanyName(),
495 $shipInstance->getObjectDescription()
498 // Iterate shipyard list
499 for ($idx = $this->shipyardList->getIterator(); $idx->valid(); $idx->next()) {
500 // Get current element
501 $shipyard = $idx->current();
503 // Is this a shipyard?
504 if (is_null($shipyard)) {
506 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
507 } elseif (!is_object($shipyard)) {
508 // Not an object! ;-(
509 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
510 } elseif (!$shipyard->isClass("Shipyard")) {
511 // Class is not a shipyard
512 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
515 // Add the new ship type to the shipyard
516 $shipyard->addNewConstructableShipType($shipType);
520 // Validate the requested ship type with the company if they can construct it
521 public function validateWorksContractShipType (SignableContract $contractInstance) {
522 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> prüft den Bauauftrag der <strong>%s</strong>.",
525 $this->getCompanyName(),
526 $contractInstance->getShipName()
529 // First get the ship type
530 $shipInstance = $contractInstance->getShipInstance();
532 // Ist there a ship instance?
533 if (is_null($shipInstance)) {
534 // Opps! Empty entry?
535 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
536 } elseif (!is_object($shipInstance)) {
537 // Not an object! ;-(
538 throw new NoObjectException($shipInstance, self::EXCEPTION_IS_NO_OBJECT);
541 // Get it's real class name
542 $shipType = $shipInstance->__toString();
545 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> prüft, ob die <strong>%s</strong> (Typ:<strong>%s</strong>) gebaut werden kann.",
548 $this->getCompanyName(),
549 $contractInstance->getShipName(),
550 $shipInstance->getObjectDescription()
553 // Now check if the ship type is in any list and return the result
554 return ($this->isShipTypeConstructable($shipType));
557 // Is the ship type constructable?
558 public function isShipTypeConstructable ($shipType) {
559 // The type must be a string!
560 $shipType = (string) $shipType;
563 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> fragt alle Werften ab, ob diese Schiffe vom Typ <strong>%s</strong> bauen können.",
566 $this->getCompanyName(),
570 // First everthing is failed...
573 // Iterate through all shipyards
574 for ($idx = $this->shipyardList->getIterator(); $idx->valid(); $idx->next()) {
575 // Get current Shipyard instance
576 $shipyard = $idx->current();
578 // Is this a shipyard?
579 if (is_null($shipyard)) {
581 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
582 } elseif (!is_object($shipyard)) {
583 // Not an object! ;-(
584 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
585 } elseif (!$shipyard->isClass("Shipyard")) {
586 // Class is not a shipyard
587 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
590 // Validate if the first found shipyard can construct the requested type
591 $result = $shipyard->isShipTypeConstructable($shipType);
593 // Does this shipyard construct the requested ship type?
594 if ($result) break; // Then abort the search!
598 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat die Suche nach einer Werft beendet, die Schiffe vom Typ <strong>%s</strong> bauen kann.",
601 $this->getCompanyName(),
609 // As a customer the shipping company can add new contracts
610 public function addNewWorksContract (SignableContract $contractInstance) {
611 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> erstellt einen Bauauftrag für ein <strong>%s</strong> mit dem Namen <strong>%s</strong>.",
614 $this->getCompanyName(),
615 $contractInstance->getShipInstance()->getObjectDescription(),
616 $contractInstance->getShipInstance()->getShipName()
618 $this->contractList->append($contractInstance);
621 // As a customer the shippng company can withdraw from a contract
622 public function withdrawFromContract (SignableContract $contractInstance) {
623 ApplicationEntryPoint::app_die("WITHDRAW:<pre>".print_r($contractInstance, true)."</pre>");
626 // Get latest added contract instance
627 public final function getLastContractInstance () {
629 $iter = $this->contractList->getIterator();
631 // Get latest entry (total - 1)
632 $iter->seek($iter->count() - 1);
635 return $iter->current();
638 // Sign a contract with an other party which must also implement Customer
639 public function signContract (SignableContract $contractInstance, ContractPartner $partnerInstance) {
640 // Check wether the other party is our contract partner
641 if (!$partnerInstance->isContractPartner($contractInstance)) {
642 // Invalid contract partner!
643 throw new InvalidContractPartnerException($partnerInstance, self::EXCEPTION_CONTRACT_PARTNER_INVALID);
646 // Determine if company "signs" own contract (must be done) or with an other party
647 if ($this->equals($partnerInstance)) {
649 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> erteilt an sich selbst einen Bauauftrag für das <strong>%s</strong> "<strong>%s</strong>".",
652 $this->getCompanyName(),
653 $contractInstance->getShipInstance()->getObjectDescription(),
654 $contractInstance->getShipInstance()->getShipName()
657 // Other external company
658 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->getDebugInstance()->output(sprintf("[%s:%d] Die Reederei <strong>%s</strong> unterzeichnet einen Bauauftrag für das <strong>%s</strong> "<strong>%s</strong>" mit der <strong>%s</strong>.",
661 $this->getCompanyName(),
662 $contractInstance->getShipInstance()->getObjectDescription(),
663 $contractInstance->getShipInstance()->getShipName(),
664 $partnerInstance->getCompanyName()
669 $contractInstance->signContract($this, $partnerInstance);
672 * @todo Maybe do something more here...
676 // Is this the right contract partner?
677 public function isContractPartner (SignableContract $contractInstance) {
678 // Get contract partner instance and compare it with $this contract partner
679 return ($this->equals($contractInstance->getContractPartner()));
682 // Setter for merchant instance
683 public final function setMerchantInstance (Merchant $merchantInstance) {
685 $contractInstance = $this->getLastContractInstance();
687 if (is_null($contractInstance)) {
688 // Opps! Empty contract instance?
689 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
690 } elseif (!is_object($contractInstance)) {
691 // Not an object! ;-(
692 throw new NoObjectException($contractInstance, self::EXCEPTION_IS_NO_OBJECT);
693 } elseif (!$contractInstance->isClass('WorksContract')) {
695 throw new ClassMismatchException(array($contractInstance->__toString(), "WorksContract"), self::EXCEPTION_CLASSES_NOT_MATCHING);
698 // Set the merchant in the contract (for getting prices)
699 $contractInstance->setMerchantInstance($merchantInstance);