1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
|
<?php
/**
* Normalizing import data.
*
* PHP Version 5.3
*
* LICENSE: This source file is subject to LGPLv2.1 license
* that is available through the world-wide-web at the following URI:
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* @author Shirley Chan, CUNY SPS
*
* Copyright of the Sahana Software Foundation, sahanafoundation.org
*
*/
abstract class agImportNormalization extends agImportHelper
{
public $summary = array(),
$batchSize;
protected $newEntityCount = 0,
$errMsg,
$warningMessages = array(),
$nonprocessedRecords = array(),
$totalProcessedRecordCount = 0,
$helperObjects = array(),
$defaultBatchSize,
$tempOffset,
// array( [order] => array(componentName => component name, helperName => Name of the helper object, throwOnError => boolean, methodName => method name) )
$importComponents = array(),
//array( [importRowId] => array( _rawData => array(fetched data), primaryKeys => array(keyName => keyValue), success => boolean)
$importData = array();
public function __construct()
{
parent::__construct();
}
public function __destruct()
{
// //drop temp table.
// $this->conn->export->dropTable($this->sourceTable);
// $this->conn->close();
}
protected function loadHelperObject($helperClassName)
{
if (! array_key_exists($helperClassName, $this->helperObjects))
{
$this->helperObjects[$helperClassName] = new $helperClassName ;
}
}
protected function loadImportRawData()
{
}
protected function normalizeData()
{
$err = NULL ;
// get our connection object and start an outer transaction for the batch
$conn = $this->getConnection() ;
$conn->beginTransaction() ;
foreach ($this->importComponents as $index => $componentData)
{
// start an inner transaction / savepoint per component
$conn->beginTransaction($componentData['component']) ;
try
{
// Calling method to set data.
$componentData['method']($componentData['throwOnError']);
$conn->commit($conn->beginTransaction($componentData['component']));
}
catch(Exception $e)
{
$errMsg = sprintf('agImportNormalization failed during method: %s.',
$componentData['method']);
// our rollback and error logging happen regardless of whether this is an optional component
sfContext::getInstance()->getLogger()->err($errMsg) ;
$conn->rollback($conn->beginTransaction($componentData['componentName']));
// if it's not an optional component, we do a bit more and stop execution entirely
if($componentData['throwOnError'])
{
$conn->rollback() ;
throw new Exception($e) ;
}
}
// you'll want to do your records keeping here (eg, counts or similar)
// be sure to use class properties to store that info so additional loops can
// reference it
}
// since we encountered no throw-able errors up to this point, we can commit
$conn->commit() ;
}
/**
* Simple method for instantiating what are effectively blank records.
* @param string $recordName The name of the record / model that will be created.
* @param array $foreignKeys An array of foreign keys that will be set with the new record.
* <code>array( $columnName => $columnValue, ...)</code>
* @return integer The newly instantiated record's ID
*/
protected function createNewRec( $recordName, $foreignKeys )
{
// instantiate the new record object
$newRec = new $recordName();
// loop through our keys and set values
foreach($foreignKeys as $columnName => $columnValue)
{
$newRec[$columnName] = $columnValue;
}
// save and return our new id
$newRec->save($this->conn);
return $newRec->getId();
}
//
// /**
// * Method to define status and type variables.
// */
// protected function defineStatusTypes()
// {
// // Override by child class.
// }
//
// /**
// * Verify data in record for required fields and valid statuses and types
// *
// * @param array $record
// * @return boolean TRUE if data in record satisfies all requirements for processing.
// * FALSE otherwise.
// */
// protected function dataValidation(array $record)
// {
// // Check for required fields
// // Check for full address?
// // Check for geo info
// // Check for email
// // Check for phone number
// // Check for valid status and types.
//
// return array('pass' => TRUE,
// 'status' => 'SUCCESS',
// 'type' => null,
// 'message' => null);
// }
//
// /**
// * Method to replace a white space with underscore.
// *
// * @param string $name A string for replacement.
// * @return string $name A reformatted string.
// */
// protected function stripName($name = NULL)
// {
// if (is_null($name) || !is_string($name)) {
// return $name;
// }
//
// $strippedName = strtolower(str_replace(' ', '_', $name));
// return $strippedName;
// }
//
// /**
// * Method to normalize data from temp table.
// */
// public function normalizeImport()
// {
// // Declare static variables.
// $facilityContactType = $this->facilityContactType;
//
// // Setup db connection.
// $conn = Doctrine_Manager::connection();
//
// // Fetch import data.
// $query = 'SELECT * FROM ' . $this->sourceTable . ' AS i';
// $pdo = $conn->execute($query);
// $pdo->setFetchMode(Doctrine_Core::FETCH_ASSOC);
// $sourceRecords = $pdo->fetchAll();
//
// // Grab the dynamical columns of staff requirements.
// if (count($sourceRecords) > 0) {
// $this->getImportStaffList(array_keys($sourceRecords[0]));
// }
//
// //loop through records.
// foreach ($sourceRecords as $record) {
// $validEmail = 1;
// $validPhone = 1;
// $validAddress = 1;
// $isNewFacilityRecord = 0;
// $isNewFacilityGroupRecord = 0;
//
// $isValidData = $this->dataValidation($record);
// if (!$isValidData['pass']) {
// switch ($isValidData['status']) {
// case 'ERROR':
// $this->nonprocessedRecords[] = array('message' => $isValidData['message'],
// 'record' => $record);
// continue 2;
// case 'WARNING':
// switch ($isValidData['type']) {
// case 'Email':
// $validEmail = 0;
// $this->warningMessages[] = array('message' => $isValidData['message'],
// 'record' => $record);
// break;
// case 'Phone':
// $validPhone = 0;
// $this->warningMessages[] = array('message' => $isValidData['message'],
// 'record' => $record);
// break;
// case 'Mail Address':
// $validAddress = 0;
// $this->warningMessages[] = array('message' => $isValidData['message'],
// 'record' => $record);
// break;
// }
// break;
// default:
// $this->nonprocessedRecords[] = array('message' => $isValidData['message'],
// 'record' => $record);
// continue 2;
// }
// }
//
// // Declare variables.
// $facility_name = $record['facility_name'];
// $facility_code = $record['facility_code'];
// $facility_resource_type_abbr = strtolower($record['facility_resource_type_abbr']);
// $facility_resource_status = strtolower($record['facility_resource_status']);
// $capacity = $record['facility_capacity'];
// $facility_activation_sequence = $record['facility_activation_sequence'];
// $facility_allocation_status = strtolower($record['facility_allocation_status']);
// $facility_group = $record['facility_group'];
// $facility_group_type = strtolower($record['facility_group_type']);
// $facility_group_allocation_status = strtolower($record['facility_group_allocation_status']);
// $facility_group_activation_sequence = $record['facility_group_activation_sequence'];
// $email = $record['work_email'];
// $phone = $record['work_phone'];
// $fullAddress = $this->fullAddress;
// $geoInfo = array('longitude' => $record['longitude'], 'latitude' => $record['latitude']);
// $staffing = $this->dynamicStaffing($record);
//
// $facility_resource_type_id = $this->facilityResourceTypes[$facility_resource_type_abbr];
// $facility_resource_status_id = $this->facilityResourceStatuses[$facility_resource_status];
// $facility_group_type_id = $this->facilityGroupTypes[$facility_group_type];
// $facility_group_allocation_status_id = $this->facilityGroupAllocationStatuses[$facility_group_allocation_status];
// $facility_resource_allocation_status_id = $this->facilityResourceAllocationStatuses[$facility_allocation_status];
// $workEmailTypeId = $this->emailContactTypes[$facilityContactType];
// $workPhoneTypeId = $this->phoneContactTypes[$facilityContactType];
// $defaultPhoneFormatTypes = $this->defaultPhoneFormatTypes;
// $workPhoneFormatId = $this->phoneFormatTypes[$defaultPhoneFormatTypes[(preg_match('/^\d{10}$/', $phone) ? 0 : 1)]];
// $workAddressTypeId = $this->addressContactTypes[$facilityContactType];
// $workAddressStandardId = $this->addressStandards;
// $addressElementIds = $this->addressElements;
//
// try {
// // here we check our current transaction scope and create a transaction or savepoint based on need
// $useSavepoint = ($conn->getTransactionLevel() > 0) ? TRUE : FALSE;
// if ($useSavepoint) {
// $conn->beginTransaction(__FUNCTION__);
// } else {
// $conn->beginTransaction();
// }
//
// // facility
// // tries to find an existing record based on a unique identifier.
// $facility = agDoctrineQuery::create($conn)
// ->from('agFacility f')
// ->where('f.facility_code = ?', $facility_code)
// ->fetchOne();
// $facilityResource = NULL;
// $scenarioFacilityResource = NULL;
//
// if (empty($facility)) {
// $facility = $this->createFacility($facility_name, $facility_code, $conn);
// $isNewFacilityRecord = 1;
// } else {
// $facility = $this->updateFacility($facility, $facility_name, $conn);
//
// // tries to find an existing record based on a set of unique identifiers.
// $facilityResource = agDoctrineQuery::create($conn)
// ->from('agFacilityResource fr')
// ->where('fr.facility_id = ?', $facility->id)
// ->andWhere('fr.facility_resource_type_id = ?', $facility_resource_type_id)
// ->fetchOne();
// }
//
// // Facility Resource
// if (empty($facilityResource)) {
// $facilityResource
// = $this
// ->createFacilityResource(
// $facility,
// $facility_resource_type_id,
// $facility_resource_status_id,
// $capacity,
// $conn
// );
// } else {
// $facilityResource
// = $this->
// updateFacilityResource(
// $facilityResource,
// $facility_resource_status_id,
// $capacity,
// $conn
// );
//
// $scenarioFacilityResource = agDoctrineQuery::create($conn)
// ->from('agScenarioFacilityResource sfr')
// ->innerJoin('sfr.agScenarioFacilityGroup sfg')
// ->where('sfg.scenario_id = ?', $this->scenarioId)
// ->andWhere('facility_resource_id = ?', $facilityResource->id)
// ->fetchOne();
// }
//
// // facility group
//
// $scenarioFacilityGroup = agDoctrineQuery::create()
// ->from('agScenarioFacilityGroup')
// ->where('scenario_id = ?', $this->scenarioId)
// ->andWhere('scenario_facility_group = ?', $facility_group)
// ->fetchOne();
//
// if (empty($scenarioFacilityGroup)) {
// $scenarioFacilityGroup
// = $this
// ->createScenarioFacilityGroup(
// $facility_group,
// $facility_group_type_id,
// $facility_group_allocation_status_id,
// $facility_group_activation_sequence,
// $conn
// );
// $isNewFacilityGroupRecord = 1;
// } else {
// $scenarioFacilityGroup
// = $this
// ->updateScenarioFacilityGroup(
// $scenarioFacilityGroup,
// $facility_group_type_id,
// $facility_group_allocation_status_id,
// $facility_group_activation_sequence,
// $conn
// );
// }
//
// // facility resource
// if (empty($scenarioFacilityResource)) {
// $scenarioFacilityResource
// = $this
// ->createScenarioFacilityResource(
// $facilityResource,
// $scenarioFacilityGroup,
// $facility_resource_allocation_status_id,
// $facility_activation_sequence,
// $conn
// );
// } else {
// $scenarioFacilityResource
// = $this
// ->updateScenarioFacilityResource(
// $scenarioFacilityResource,
// $scenarioFacilityGroup->id,
// $facility_resource_allocation_status_id,
// $facility_activation_sequence,
// $conn
// );
// }
//
// //facility staff resource
// $this->updateFacilityStaffResources($scenarioFacilityResource->getId(), $staffing, $conn);
//
// // email
// if ($validEmail) {
// $this->updateFacilityEmail($facility, $email, $workEmailTypeId, $conn);
// }
//
// // phone
// if ($validPhone) {
// $this
// ->updateFacilityPhone(
// $facility,
// $phone,
// $workPhoneTypeId,
// $workPhoneFormatId,
// $conn
// );
// }
//
// // address
// if ($validAddress) {
// $addressId
// = $this
// ->updateFacilityAddress(
// $facility,
// $fullAddress,
// $workAddressTypeId,
// $workAddressStandardId,
// $addressElementIds,
// $conn
// );
// }
//
// $this
// ->updateFacilityGeo(
// $facility,
// $addressId,
// $workAddressTypeId,
// $workAddressStandardId,
// $geoInfo,
// $conn
// );
//
// // Set summary counts
// if ($isNewFacilityRecord) {
// $this->totalNewFacilityCount++;
// }
// if ($isNewFacilityGroupRecord) {
// $this->totalNewFacilityGroupCount++;
// }
// $this->totalProcessedRecordCount++;
//
// $facilityId = $facility->id;
// if (!is_integer(array_search($facilityId, $this->processedFacilityIds))) {
// array_push($this->processedFacilityIds, $facilityId);
// }
//
// if ($useSavepoint) {
// $conn->commit(__FUNCTION__);
// } else {
// $conn->commit();
// }
// } catch (Exception $e) {
// $this->errMsg .= ' Unable to normalize data. Exception error message: ' . $e->getMessage();
// $this->nonprocessedRecords[] = array('message' => $this->errMsg, 'record' => $record);
// sfContext::getInstance()->getLogger()->err($errMsg);
//
// // if we started with a savepoint, let's end with one, otherwise, rollback globally
// if ($useSavepoint) {
// $conn->rollback(__FUNCTION__);
// } else {
// $conn->rollback();
// }
//
// break;
// }
// } // end foreach
// //drop temp table.
// $conn->export->dropTable($this->sourceTable);
// $conn->close();
//
// $this->summary = array(
// 'totalProcessedRecordCount' => $this->totalProcessedRecordCount,
// 'nonprocessedRecords' => $this->nonprocessedRecords,
// 'warningMessages' => $this->warningMessages
// );
// }
}
|