]> git.mxchange.org Git - city.git/blob - application/city/classes/city_daemon/class_BaseCityDaemon.php
Continued:
[city.git] / application / city / classes / city_daemon / class_BaseCityDaemon.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\City\Daemon;
4
5 // Import application-specific stuff
6 use Org\Mxchange\City\Factory\Manager\ManagerFactory;
7 use Org\Mxchange\City\Factory\State\CityStateFactory;
8 use Org\Mxchange\City\Generic\BaseCitySystem;
9 use Org\Mxchange\City\Database\Frontend\Information\CityInformationDatabaseFrontend;
10
11 // Import framework stuff
12 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
13 use Org\Mxchange\CoreFramework\Criteria\Add\AddableCriteria;
14 use Org\Mxchange\CoreFramework\Criteria\Storing\StoreableCriteria;
15 use Org\Mxchange\CoreFramework\Database\Frontend\User\UserDatabaseFrontend;
16 use Org\Mxchange\CoreFramework\Database\Updateable;
17 use Org\Mxchange\CoreFramework\Factory\Database\Frontend\DatabaseFrontendFactory;
18 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
19 use Org\Mxchange\CoreFramework\Helper\Application\ApplicationHelper;
20 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
21 use Org\Mxchange\CoreFramework\Registry\Object\ObjectRegistry;
22 use Org\Mxchange\CoreFramework\Request\Requestable;
23 use Org\Mxchange\CoreFramework\Response\Responseable;
24 use Org\Mxchange\CoreFramework\Traits\Crypto\CryptoTrait;
25 use Org\Mxchange\CoreFramework\Traits\Database\Frontend\DatabaseFrontendTrait;
26 use Org\Mxchange\CoreFramework\Traits\State\StateableTrait;
27
28 /**
29  * A general City class
30  *
31  * @author              Roland Haeder <webmaster@shipsimu.org>
32  * @version             0.0.0
33  * @copyright   Copyright (c) 2015 - 2023 City Developer Team
34  * @license             GNU GPL 3.0 or any newer version
35  * @link                http://www.shipsimu.org
36  *
37  * This program is free software: you can redistribute it and/or modify
38  * it under the terms of the GNU General Public License as published by
39  * the Free Software Foundation, either version 3 of the License, or
40  * (at your option) any later version.
41  *
42  * This program is distributed in the hope that it will be useful,
43  * but WITHOUT ANY WARRANTY; without even the implied warranty of
44  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
45  * GNU General Public License for more details.
46  *
47  * You should have received a copy of the GNU General Public License
48  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
49  */
50 abstract class BaseCityDaemon extends BaseCitySystem implements Updateable, AddableCriteria {
51         // Load traits
52         use CryptoTrait;
53         use DatabaseFrontendTrait;
54         use StateableTrait;
55
56         /**
57          * City types
58          */
59         const CITY_TYPE_DEFAULT = 'default';
60         const CITY_TYPE_TESTING = 'testing';
61
62         /**
63          * Whether this City is active (default: FALSE)
64          */
65         private $isActive = FALSE;
66
67         /**
68          * Protected constructor
69          *
70          * @param       $className      Name of the class
71          * @return      void
72          */
73         protected function __construct (string $className) {
74                 // Call parent constructor
75                 parent::__construct($className);
76
77                 // Get a frontend instance
78                 $frontendInstance = DatabaseFrontendFactory::createFrontendByConfiguredName('city_info_db_frontend_class');
79
80                 // Set it here
81                 $this->setFrontendInstance($frontendInstance);
82
83                 // Get a crypto instance
84                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
85
86                 // Set it here
87                 $this->setCryptoInstance($cryptoInstance);
88
89                 // Add own instance to registry
90                 ObjectRegistry::getRegistry('factory')->addInstance('city', $this);
91
92                 // Init state which sets the state to 'init'
93                 $this->initState();
94         }
95
96         /**
97          * Initializes the City's state which sets it to 'init'
98          *
99          * @return      void
100          */
101         private function initState() {
102                 // Get the state factory and create the initial state.
103                 CityStateFactory::createCityStateInstanceByName('init');
104         }
105
106         /**
107          * Outputs the console teaser. This should only be executed on startup or
108          * full restarts. This method generates some space around the teaser.
109          *
110          * @return      void
111          */
112         public function outputConsoleTeaser () {
113                 // Get the app instance (for shortening our code)
114                 $applicationInstance = ApplicationHelper::getSelfInstance();
115
116                 // Output all lines
117                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(' ');
118                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage($applicationInstance->getAppName() . ' v' . $applicationInstance->getAppVersion() . ' - ' . FrameworkBootstrap::getRequestInstance()->getRequestElement('mode') . ' daemon starting');
119                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('Copyright (c) 2015 - 2023 City Developer Team');
120                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(' ');
121                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('This program comes with ABSOLUTELY NO WARRANTY; for details see docs/COPYING.');
122                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('This is free software, and you are welcome to redistribute it under certain');
123                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('conditions; see docs/COPYING for details.');
124                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(' ');
125         }
126
127         /**
128          * Adds City data elements to a given dataset instance
129          *
130          * @param       $criteriaInstance       An instance of a storeable criteria
131          * @param       $requestInstance        An instance of a Requestable class
132          * @return      void
133          */
134         public function addElementsToDataSet (StoreableCriteria $criteriaInstance, Requestable $requestInstance = NULL) {
135                 // Make sure the request instance is set as it is not optional.
136                 assert($requestInstance instanceof Requestable);
137
138                 // Add City number and type
139                 $criteriaInstance->addCriteria(CityInformationDatabaseFrontend::DB_COLUMN_CITY_ID  , 1);
140                 $criteriaInstance->addCriteria(CityInformationDatabaseFrontend::DB_COLUMN_CITY_MODE, $requestInstance->getRequestElement('mode'));
141
142                 // Add the City id
143                 $criteriaInstance->addCriteria(CityInformationDatabaseFrontend::DB_COLUMN_CITY_ID, $this->getCityId());
144         }
145
146         /**
147          * Updates a given field with new value
148          *
149          * @param       $fieldName              Field to update
150          * @param       $fieldValue             New value to store
151          * @return      void
152          * @throws      DatabaseUpdateSupportException  If this class does not support database updates
153          * @todo        Try to make this method more generic so we can move it in BaseFrameworkSystem
154          */
155         public function updateDatabaseField ($fieldName, $fieldValue) {
156                 // Unfinished
157                 DebugMiddleware::getSelfInstance()->partialStub('Unfinished: fieldName=' . $fieldName . ',fieldValue=' . $fieldValue);
158                 return;
159
160                 // Get a critieria instance
161                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
162
163                 // Add search criteria
164                 $searchInstance->addCriteria(UserDatabaseFrontend::DB_COLUMN_USERNAME, $this->getUserName());
165                 $searchInstance->setLimit(1);
166
167                 // Now get another criteria
168                 $updateInstance = ObjectFactory::createObjectByConfiguredName('update_criteria_class');
169
170                 // Add criteria entry which we shall update
171                 $updateInstance->addCriteria($fieldName, $fieldValue);
172
173                 // Add the search criteria for searching for the right entry
174                 $updateInstance->setSearchInstance($searchInstance);
175
176                 // Set frontend class name
177                 $updateInstance->setFrontendConfigEntry('user_db_frontend_class');
178
179                 // Remember the update in database result
180                 $this->getResultInstance()->add2UpdateQueue($updateInstance);
181         }
182
183         /**
184          * Activates the City by doing some final preparation and setting
185          * $CityIsActive to TRUE.
186          *
187          * @param       $requestInstance        A Requestable class
188          * @param       $responseInstance       A Responseable class
189          * @return      void
190          */
191         public function activateCityDaemon (Requestable $requestInstance, Responseable $responseInstance) {
192                 // Get the controller here
193                 $controllerInstance = ObjectRegistry::getRegistry('generic')->getInstance('controller');
194
195                 // Run all filters for the City activation
196                 $controllerInstance->executeActivationFilters($requestInstance, $responseInstance);
197
198                 // Make sure the city's state is 'init'
199                 $this->getStateInstance()->validateCityStateIsInit();
200
201                 // ----------------------- Last step from here ------------------------
202                 // Activate the city daemon. This is ALWAYS the last step in this method
203                 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CITY[' . __METHOD__ . ':' . __LINE__ . ']: state=' . $this->getStateInstance()->__toString() . ' - Activating ...');
204                 $this->getStateInstance()->citySimulationIsActivated();
205                 // ---------------------- Last step until here ------------------------
206         }
207
208         /**
209          * Getter for isActive attribute
210          *
211          * @return      $isActive       Whether the City is active
212          */
213         public final function isCityActive () {
214                 return $this->isActive;
215         }
216
217         /**
218          * Enables (default) or disables isActive flag
219          *
220          * @param       $isActive       Whether the City is active
221          * @return      void
222          */
223         public final function enableIsActive (bool $isActive = TRUE) {
224                 $this->isActive = $isActive;
225         }
226
227         /**
228          * Updates/refreshes City data (e.g. status).
229          *
230          * @return      void
231          * @todo        Find more to do here
232          */
233         public function updateCityData () {
234                 // Set some dummy configuration entries, e.g. city_status
235                 FrameworkBootstrap::getConfigurationInstance()->setConfigEntry('city_status', $this->getStateInstance()->getStateName());
236         }
237
238         /**
239          * Adds all required elements from given array into data set instance
240          *
241          * @param       $dataSetInstance        An instance of a StoreableCriteria class
242          * @param       $CityData                       An array with valid City data
243          * @return      void
244          */
245         public function addArrayToDataSet (StoreableCriteria $dataSetInstance, array $cityData) {
246                 // Add all data the array provides
247                 foreach (CityInformationDatabaseFrontend::getAllElements() as $element) {
248                         // Is the element there?
249                         if (isset($cityData[$element])) {
250                                 // Add it
251                                 $dataSetInstance->addCriteria($element, $cityData[$element]);
252                         } else {
253                                 // Output warning message
254                                 self::createDebugInstance(__CLASS__, __LINE__)->warningMessage(sprintf('BASE-CITY-DAEMON: Element %s not found in CityData array.', $element));
255                         }
256                 }
257         }
258
259         /**
260          * Initializes the city daemon
261          *
262          * @return      void
263          * @todo        0% done
264          */
265         public function bootstrapInitCityDaemon () {
266                 DebugMiddleware::getSelfInstance()->partialStub('Please add something here.');
267         }
268
269         /**
270          * Checks whether at least one map requires expansion
271          *
272          * @return      $requiresExpansion      Whether a map requires expansion
273          */
274         public function isMapPendingExpansion () {
275                 // @TODO Is the game paused by user?
276
277                 // Get sections manager
278                 $sectionsInstance = ManagerFactory::createManagerByType('city_sections');
279
280                 // Call it's method and return value
281                 return $sectionsInstance->isSectionPendingExpansion();
282         }
283
284         /**
285          * Expands any found map that requires expansion
286          *
287          * @return      void
288          */
289         public function expandMaps () {
290                 // Get sections manager
291                 $sectionsInstance = ManagerFactory::createManagerByType('city_sections');
292
293                 // Call it's method and return value
294                 $sectionsInstance->expandMaps();
295         }
296
297 }