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__);
79 * Creates an instance of this company class or throws an exception if the
80 * given user owns no company.
82 * @param $userInstance A user class
83 * @return $companyInstance Prepared company instance
85 public final static function createShippingCompany (ManageableAccount $userInstance) {
87 $companyInstance = new ShippingCompany();
89 // Does the given user owns a company?
90 if ($companyInstance->ifUserParticipatesInCompany($userInstance)) {
91 // Then do some nasty caching here but don't throw an exception
92 // because then you will hurt our web helpers... :/
93 $companyInstance->partialStub("Don't throw exceptions here.");
97 $companyInstance->initCompanyLists();
100 return $companyInstance;
104 * Checks wether the given user participates in a company
106 * @param $userInstance An instance of a user class
107 * @return $participates Wether the user participates at lease in one company
109 protected function ifUserParticipatesInCompany (ManageableAccount $userInstance) {
110 // By default no user owns any company... ;)
111 $participates = false;
113 // Get a company database wrapper class
114 $wrapperInstance = ObjectFactory::createObjectByConfiguredName('company_db_wrapper_class', array($this));
116 // Ask the wrapper if this user participates
117 $participates = $wrapperInstance->ifUserParticipatesInCompany($userInstance);
119 // Get the result instance
120 $resultInstance = $wrapperInstance->getResultInstance();
122 // Caches the result instance here, if set (we don't the wrapper anymore!)
123 if ($resultInstance instanceof SearchableResult) {
124 // Set the result instance
125 $this->setResultInstance($resultInstance);
129 return $participates;
133 * Checks wether the current user in registry is the company founder
135 * @return $isFounder Wether the current user is the company founder
137 public function ifUserIsFounder () {
138 // Default is not the founder
141 // Get result instance
142 $resultInstance = $this->getResultInstance();
145 if ($resultInstance instanceof SearchableResult) {
146 // Result found so analyse it
147 $this->partialStub("Check if user is company founder.");
155 * Checks wether the current user in registry is the company owner
157 * @return $isOwner Wether the current user is the company owner
159 public function ifUserIsOwner () {
160 // Default is not the owner
163 // Get result instance
164 $resultInstance = $this->getResultInstance();
167 if ($resultInstance instanceof SearchableResult) {
168 // Result found so analyse it
169 $this->partialStub("Check if user is company owner.");
177 * Checks wether the current user in registry is an employee in this company
179 * @return $isOwner Wether the current user is an employee in this company
181 public function ifUserIsEmployee () {
182 // Default is no employee
185 // Get result instance
186 $resultInstance = $this->getResultInstance();
189 if ($resultInstance instanceof SearchableResult) {
190 // Result found so he is employee
198 //------------------------------------------------------------------------------\
199 // Below here is very old code which needs to be translated and changed heavily |
200 //------------------------------------------------------------------------------/
203 * Intialize all lists
206 * @todo Maybe we don't need these big lists anymore?! So we can deprecate/remove it
208 protected function initCompanyLists () {
210 $this->employeeList = new FrameworkArrayObject("FakedEmployeeList");
213 $this->shipyardList = new FrameworkArrayObject("FakedShipyardList");
216 $this->contractList = new FrameworkArrayObject("FakedContractList");
219 // Setter-Methode fuer Firmennamen
220 public final function setCompanyName ($companyName) {
221 $this->companyName = (string) $companyName;
224 // Getter-Methode fuer Firmennamen
225 public final function getCompanyName () {
226 return $this->companyName;
229 // Setter-Methode fuer Firmensitz
230 public final function setHQInstance (Harbor $hqInstance) {
231 $this->hqInstance = $hqInstance;
235 private function initShortName () {
236 // Mindestens eine Leerstelle?
237 $dummy = explode(" ", $this->getCompanyName());
238 foreach ($dummy as $part) {
239 $this->shortName .= substr($part, 0, 1);
243 // Reedereien Werften bauen lassen
244 public function createShipyardInHarbor($shipyardName, Harbor $harborInstance) {
245 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> baut im <strong>%s</strong> eine Werft <strong>%s</strong>.",
248 $this->getCompanyName(),
249 $harborInstance->getHarborName(),
253 // Wird im HQ gebaut?
254 if ($this->hqInstance->equals($harborInstance)) {
255 // Die neue Werft wird im HQ gebaut!
256 $this->hqInstance->addNewShipyardNotify($shipyardName, $this);
257 // Die Werft drueber in Kenntnis setzen, welcher Reederei sie angehoert
259 // Ausserhalb des Heimathafens soll eine Werft gebaut werden
260 $harborInstance->addNewShipyardNotify($shipyardName, $this);
264 // Setter fuer Reederei-Gruender
265 public final function setCompanyFounder(CompanyEmployee $founderInstance) {
266 $this->founderInstance = $founderInstance;
269 // Getter for founder instance
270 public final function getFounderInstance () {
271 return $this->founderInstance;
274 // Neue(n) Angestellte(n) in Angestellten-Liste aufnehmen
275 public function addNewEmployee (SimulatorPersonell $employeeInstance) {
276 $this->employeeList->append($employeeInstance);
279 // Neue Werft in Liste aufnehmen
280 public function addNewShipyard (Shipyard $shipyardInstance) {
281 $this->shipyardList->append($shipyardInstance);
284 // Neue Mitarbeiter per Zufall einstellen/rekrutieren
285 public function recruitRandomEmployees($amount, SimulatorPersonell $personellInstance) {
286 // Anzahl Mitarbeiter absichern
287 $amount = (int) $amount;
289 // Debug-Meldung ausgeben
290 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> stellt per Zufall <strong>%d</strong> neue Mitarbeiter ein.",
293 $this->getCompanyName(),
297 // Gesamtanzahl verfuegbarer Erwerbsloser holen
298 $totalUnemployed = $personellInstance->getAllUnemployed();
300 // Existiert die gewuenschte Anzahl freier Arbeiter? (doppelt geht derzeit nicht)
301 if ($totalUnemployed < $amount) {
302 // Reichte nicht aus!
303 throw new ToMuchEmployeesException(array($amount, $personellInstance->getAllUnemployed()), self::EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES);
306 // Get list for all unemployed people
307 $list = $personellInstance->getSpecialPersonellList(false); // Should be cached
309 // Get iterator of the list
310 $iterator = $list->getIterator();
312 // Get the requested amount of personell
313 for ($idx = 0; $idx < $amount; $idx++) {
315 // Is this personl unemployed?
316 while (is_null($employee) || $employee->isEmployed()) {
317 // Generate random number
318 $pos = mt_rand(0, ($totalUnemployed - 1)); // Don't remove the -1 here:
319 // E.g. 100 entries means latest position is 99...
321 // Seek for the position
322 $iterator->seek($pos);
324 // Is the current position valid?
325 if (!$iterator->valid()) {
326 // Should normally not happen... :(
327 throw new StructuresOutOfBoundsException($idx, self::EXCEPTION_INDEX_OUT_OF_BOUNDS);
330 // Get current element
331 $employee = $iterator->current();
334 // A dummy just for the description and real class
335 $dummy = CompanyEmployee::createCompanyEmployee("", "", "M", 1970, 1, 1, $employee->isMarried(), 0);
337 // Make this person employed and give him some money to work
338 $employee->setEmployed(true);
339 $employee->setRealClass($dummy->__toString());
340 $employee->increaseSalary((mt_rand(7, 14) * 100)); // Are 700 to 1400 EUR for the begin okay?
343 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> stellt den/die Angestellte(n) <strong>%s %s</strong> ein.",
346 $this->getCompanyName(),
347 $employee->getSurname(),
348 $employee->getFamily()
352 $this->addNewEmployee($employee);
356 $personellInstance->resetCache();
358 // Debug-Meldung ausgeben
359 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat per Zufall <strong>%d</strong> neue Mitarbeiter eingestellt.",
362 $this->getCompanyName(),
367 // Distribute all personells on all shipyards
368 public function distributeAllPersonellOnShipyards () {
369 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> verteilt alle ihre <strong>%d</strong> Mitarbeiter auf alle <strong>%d</strong> Werft(en).",
372 $this->getCompanyName(),
373 $this->getTotalEmployee(),
374 $this->getTotalShipyards()
377 // Do we have some shipyards?
378 if (is_null($this->shipyardList)) {
379 // No shipyards created
380 throw new NoShipyardsConstructedException($this, self::EXCEPTION_HARBOR_HAS_NO_SHIPYARDS);
383 // Get iterator for shipyards
384 $shipyardIter = $this->shipyardList->getIterator();
386 // Iterate through all employees
387 for ($idx = $this->employeeList->getIterator(); $idx->valid(); $idx->next()) {
388 // Is the shipyard iterator still okay?
389 if (!$shipyardIter->valid()) {
390 // Rewind to first position
391 $shipyardIter->seek(0);
394 // Get Shipyard object
395 $shipyard = $shipyardIter->current();
397 // Is this a Shipyard object?
398 if (is_null($shipyard)) {
400 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
401 } elseif (!is_object($shipyard)) {
402 // Not an object! ;-(
403 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
404 } elseif (!$shipyard->isClass("Shipyard")) {
405 // Nope, so throw exception
406 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
409 // Add employee to the shipyard
410 $shipyard->addNewPersonell($idx->current());
412 // Continue to next shipyard
413 $shipyardIter->next();
417 // Getter for total employees
418 public final function getTotalEmployee () {
420 $total = $this->employeeList->count();
423 if ((defined('DEBUG_COMPANY_EMPLOYEE')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat <strong>%d</strong> Mitarbeiter.",
426 $this->getCompanyName(),
434 // Getter for total shipyards
435 public final function getTotalShipyards () {
436 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Für die Reederei <strong>%s</strong> werden die Anzahl der Werften in allen Häfen ermittelt.",
439 $this->getCompanyName()
442 // Do we have some shipyards?
443 if (is_null($this->shipyardList)) {
444 // No shipyards created
445 throw new NoShipyardsConstructedException($this, self::EXCEPTION_HARBOR_HAS_NO_SHIPYARDS);
449 $total = $this->shipyardList->count();
452 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat <strong>%d</strong> Werft(en).",
455 $this->getCompanyName(),
463 // Add a ship type (class) to all shipyards
464 public function addShipTypeToAllShipyards ($shipType) {
466 $shipType = (string) $shipType;
468 // Is the class there?
469 if (!class_exists($shipType)) {
471 throw new ClassNotFoundException($shipType, self::EXCEPTION_CLASS_NOT_FOUND);
475 eval(sprintf("\$shipInstance = %s::create%s(\"M/S Dummy\");",
480 // Iterate shipyard list
481 for ($idx = $this->shipyardList->getIterator(); $idx->valid(); $idx->next()) {
482 // Get current element
483 $shipyard = $idx->current();
485 // Is this a shipyard?
486 if (is_null($shipyard)) {
488 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
489 } elseif (!is_object($shipyard)) {
490 // Not an object! ;-(
491 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
492 } elseif (!$shipyard->isClass("Shipyard")) {
493 // Class is not a shipyard
494 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
497 // Add the new ship type to the shipyard
498 $shipyard->addNewConstructableShipType($shipType);
502 // Validate the requested ship type with the company if they can construct it
503 public function validateWorksContractShipType (SignableContract $contractInstance) {
504 // First get the ship type
505 $shipInstance = $contractInstance->getShipInstance();
507 // Ist there a ship instance?
508 if (is_null($shipInstance)) {
509 // Opps! Empty entry?
510 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
511 } elseif (!is_object($shipInstance)) {
512 // Not an object! ;-(
513 throw new NoObjectException($shipInstance, self::EXCEPTION_IS_NO_OBJECT);
516 // Get it's real class name
517 $shipType = $shipInstance->__toString();
519 // Now check if the ship type is in any list and return the result
520 return ($this->isShipTypeConstructable($shipType));
523 // Is the ship type constructable?
524 public function isShipTypeConstructable ($shipType) {
525 // The type must be a string!
526 $shipType = (string) $shipType;
529 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> fragt alle Werften ab, ob diese Schiffe vom Typ <strong>%s</strong> bauen können.",
532 $this->getCompanyName(),
536 // First everthing is failed...
539 // Iterate through all shipyards
540 for ($idx = $this->shipyardList->getIterator(); $idx->valid(); $idx->next()) {
541 // Get current Shipyard instance
542 $shipyard = $idx->current();
544 // Is this a shipyard?
545 if (is_null($shipyard)) {
547 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
548 } elseif (!is_object($shipyard)) {
549 // Not an object! ;-(
550 throw new NoObjectException($shipyard, self::EXCEPTION_IS_NO_OBJECT);
551 } elseif (!$shipyard->isClass("Shipyard")) {
552 // Class is not a shipyard
553 throw new ClassMismatchException(array($shipyard->__toString(), "Shipyard"), self::EXCEPTION_CLASSES_NOT_MATCHING);
556 // Validate if the first found shipyard can construct the requested type
557 $result = $shipyard->isShipTypeConstructable($shipType);
559 // Does this shipyard construct the requested ship type?
560 if ($result) break; // Then abort the search!
564 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> hat die Suche nach einer Werft beendet, die Schiffe vom Typ <strong>%s</strong> bauen kann.",
567 $this->getCompanyName(),
575 // As a customer the shipping company can add new contracts
576 public function addNewWorksContract (SignableContract $contractInstance) {
577 $this->contractList->append($contractInstance);
580 // As a customer the shippng company can withdraw from a contract
581 public function withdrawFromContract (SignableContract $contractInstance) {
582 ApplicationEntryPoint::app_die("WITHDRAW:<pre>".print_r($contractInstance, true)."</pre>");
585 // Get latest added contract instance
586 public final function getLastContractInstance () {
588 $iter = $this->contractList->getIterator();
590 // Get latest entry (total - 1)
591 $iter->seek($iter->count() - 1);
594 return $iter->current();
597 // Sign a contract with an other party which must also implement Customer
598 public function signContract (SignableContract $contractInstance, ContractPartner $partnerInstance) {
599 // Check wether the other party is our contract partner
600 if (!$partnerInstance->isContractPartner($contractInstance)) {
601 // Invalid contract partner!
602 throw new InvalidContractPartnerException($partnerInstance, self::EXCEPTION_CONTRACT_PARTNER_INVALID);
605 // Determine if company "signs" own contract (must be done) or with an other party
606 if ($this->equals($partnerInstance)) {
608 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(sprintf("[%s:%d] Die Reederei <strong>%s</strong> erteilt an sich selbst einen Bauauftrag für das <strong>%s</strong> "<strong>%s</strong>".",
611 $this->getCompanyName(),
612 $contractInstance->getShipInstance()->getObjectDescription(),
613 $contractInstance->getShipInstance()->getShipName()
616 // Other external company
617 if ((defined('DEBUG_COMPANY')) || (defined('DEBUG_ALL'))) $this->debugOutput(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>.",
620 $this->getCompanyName(),
621 $contractInstance->getShipInstance()->getObjectDescription(),
622 $contractInstance->getShipInstance()->getShipName(),
623 $partnerInstance->getCompanyName()
628 $contractInstance->signContract($this, $partnerInstance);
631 * @todo Maybe do something more here...
635 // Is this the right contract partner?
636 public function isContractPartner (SignableContract $contractInstance) {
637 // Get contract partner instance and compare it with $this contract partner
638 return ($this->equals($contractInstance->getContractPartner()));
641 // Setter for merchant instance
642 public final function setMerchantInstance (Merchant $merchantInstance) {
644 $contractInstance = $this->getLastContractInstance();
646 if (is_null($contractInstance)) {
647 // Opps! Empty contract instance?
648 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
649 } elseif (!is_object($contractInstance)) {
650 // Not an object! ;-(
651 throw new NoObjectException($contractInstance, self::EXCEPTION_IS_NO_OBJECT);
652 } elseif (!$contractInstance->isClass('WorksContract')) {
654 throw new ClassMismatchException(array($contractInstance->__toString(), "WorksContract"), self::EXCEPTION_CLASSES_NOT_MATCHING);
657 // Set the merchant in the contract (for getting prices)
658 $contractInstance->setMerchantInstance($merchantInstance);