-
Notifications
You must be signed in to change notification settings - Fork 550
/
Abstract.php
719 lines (638 loc) · 18.4 KB
/
Abstract.php
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Abstract Core Resource Collection
*
* @category Mage
* @package Mage_Core
* @author Magento Core Team <core@magentocommerce.com>
*/
abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Data_Collection_Db
{
const CACHE_TAG = 'COLLECTION_DATA';
/**
* Model name
*
* @var string
*/
protected $_model;
/**
* Resource model name
*
* @var string
*/
protected $_resourceModel;
/**
* Resource instance
*
* @var Mage_Core_Model_Resource_Db_Abstract
*/
protected $_resource;
/**
* Fields to select in query
*
* @var array|null
*/
protected $_fieldsToSelect = null;
/**
* Fields initial fields to select like id_field
*
* @var array|null
*/
protected $_initialFieldsToSelect = null;
/**
* Fields to select changed flag
*
* @var booleam
*/
protected $_fieldsToSelectChanged = false;
/**
* Store joined tables here
*
* @var array
*/
protected $_joinedTables = array();
/**
* Collection main table
*
* @var string
*/
protected $_mainTable = null;
/**
* Reset items data changed flag
*
* @var boolean
*/
protected $_resetItemsDataChanged = false;
/**
* Name prefix of events that are dispatched by model
*
* @var string
*/
protected $_eventPrefix = '';
/**
* Name of event parameter
*
* @var string
*/
protected $_eventObject = '';
/**
* Use analytic function flag
* If true - allows to prepare final select with analytic function
*
* @var bool
*/
protected $_useAnalyticFunction = false;
/**
* Collection constructor
*
* @param Mage_Core_Model_Resource_Db_Abstract $resource
*/
public function __construct($resource = null)
{
parent::__construct();
$this->_construct();
$this->_resource = $resource;
$this->setConnection($this->getResource()->getReadConnection());
$this->_initSelect();
}
/**
* Initialization here
*
*/
protected function _construct()
{
}
/**
* Retrieve main table
*
* @return string
*/
public function getMainTable()
{
if ($this->_mainTable === null) {
$this->setMainTable($this->getResource()->getMainTable());
}
return $this->_mainTable;
}
/**
* Set main collection table
*
* @param string $table
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function setMainTable($table)
{
if (strpos($table, '/') !== false) {
$table = $this->getTable($table);
}
if ($this->_mainTable !== null && $table !== $this->_mainTable && $this->getSelect() !== null) {
$from = $this->getSelect()->getPart(Zend_Db_Select::FROM);
if (isset($from['main_table'])) {
$from['main_table']['tableName'] = $table;
}
$this->getSelect()->setPart(Zend_Db_Select::FROM, $from);
}
$this->_mainTable = $table;
return $this;
}
/**
* Init collection select
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _initSelect()
{
$this->getSelect()->from(array('main_table' => $this->getMainTable()));
return $this;
}
/**
* Get Zend_Db_Select instance and applies fields to select if needed
*
* @return Varien_Db_Select
*/
public function getSelect()
{
if ($this->_select && $this->_fieldsToSelectChanged) {
$this->_fieldsToSelectChanged = false;
$this->_initSelectFields();
}
return parent::getSelect();
}
/**
* Init fields for select
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _initSelectFields()
{
$columns = $this->_select->getPart(Zend_Db_Select::COLUMNS);
$columnsToSelect = array();
foreach ($columns as $columnEntry) {
list($correlationName, $column, $alias) = $columnEntry;
if ($correlationName !== 'main_table') { // Add joined fields to select
if ($column instanceof Zend_Db_Expr) {
$column = $column->__toString();
}
$key = ($alias !== null ? $alias : $column);
$columnsToSelect[$key] = $columnEntry;
}
}
$columns = $columnsToSelect;
$columnsToSelect = array_keys($columnsToSelect);
if ($this->_fieldsToSelect !== null) {
$insertIndex = 0;
foreach ($this->_fieldsToSelect as $alias => $field) {
if (!is_string($alias)) {
$alias = null;
}
if ($field instanceof Zend_Db_Expr) {
$column = $field->__toString();
} else {
$column = $field;
}
if (($alias !== null && in_array($alias, $columnsToSelect)) ||
// If field already joined from another table
($alias === null && isset($alias, $columnsToSelect))) {
continue;
}
$columnEntry = array('main_table', $field, $alias);
array_splice($columns, $insertIndex, 0, array($columnEntry)); // Insert column
$insertIndex ++;
}
} else {
array_unshift($columns, array('main_table', '*', null));
}
$this->_select->setPart(Zend_Db_Select::COLUMNS, $columns);
return $this;
}
/**
* Retrieve initial fields to select like id field
*
* @return array
*/
protected function _getInitialFieldsToSelect()
{
if ($this->_initialFieldsToSelect === null) {
$this->_initialFieldsToSelect = array();
$this->_initInitialFieldsToSelect();
}
return $this->_initialFieldsToSelect;
}
/**
* Initialize initial fields to select like id field
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _initInitialFieldsToSelect()
{
$idFieldName = $this->getResource()->getIdFieldName();
if ($idFieldName) {
$this->_initialFieldsToSelect[] = $idFieldName;
}
return $this;
}
/**
* Add field to select
*
* @param string|array $field
* @param string|null $alias
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function addFieldToSelect($field, $alias = null)
{
if ($field === '*') { // If we will select all fields
$this->_fieldsToSelect = null;
$this->_fieldsToSelectChanged = true;
return $this;
}
if (is_array($field)) {
if ($this->_fieldsToSelect === null) {
$this->_fieldsToSelect = $this->_getInitialFieldsToSelect();
}
foreach ($field as $key => $value) {
$this->addFieldToSelect(
$value,
(is_string($key) ? $key : null),
false
);
}
$this->_fieldsToSelectChanged = true;
return $this;
}
if ($alias === null) {
$this->_fieldsToSelect[] = $field;
} else {
$this->_fieldsToSelect[$alias] = $field;
}
$this->_fieldsToSelectChanged = true;
return $this;
}
/**
* Add attribute expression (SUM, COUNT, etc)
* Example: ('sub_total', 'SUM({{attribute}})', 'revenue')
* Example: ('sub_total', 'SUM({{revenue}})', 'revenue')
* For some functions like SUM use groupByAttribute.
*
* @param string $alias
* @param string $expression
* @param array $fields
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function addExpressionFieldToSelect($alias, $expression, $fields)
{
// validate alias
if (!is_array($fields)) {
$fields = array($fields=>$fields);
}
$fullExpression = $expression;
foreach ($fields as $fieldKey=>$fieldItem) {
$fullExpression = str_replace('{{' . $fieldKey . '}}', $fieldItem, $fullExpression);
}
$this->getSelect()->columns(array($alias=>$fullExpression));
return $this;
}
/**
* Removes field from select
*
* @param string|null $field
* @param boolean $isAlias Alias identifier
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function removeFieldFromSelect($field, $isAlias = false)
{
if ($isAlias) {
if (isset($this->_fieldsToSelect[$field])) {
unset($this->_fieldsToSelect[$field]);
}
} else {
foreach ($this->_fieldsToSelect as $key => $value) {
if ($value === $field) {
unset($this->_fieldsToSelect[$key]);
break;
}
}
}
$this->_fieldsToSelectChanged = true;
return $this;
}
/**
* Removes all fields from select
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function removeAllFieldsFromSelect()
{
$this->_fieldsToSelect = $this->_getInitialFieldsToSelect();
$this->_fieldsToSelectChanged = true;
return $this;
}
/**
* Standard resource collection initialization
*
* @param string $model
* @param Mage_Core_Model_Resource_Db_Abstract $resourceModel
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _init($model, $resourceModel = null)
{
$this->setModel($model);
if (is_null($resourceModel)) {
$resourceModel = $model;
}
$this->setResourceModel($resourceModel);
return $this;
}
/**
* Set model name for collection items
*
* @param string $model
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function setModel($model)
{
if (is_string($model)) {
$this->_model = $model;
$this->setItemObjectClass(Mage::getConfig()->getModelClassName($model));
}
return $this;
}
/**
* Get model instance
*
* @param array $args
* @return Varien_Object
*/
public function getModelName($args = array())
{
return $this->_model;
}
/**
* Set resource model name for collection items
*
* @param string $model
*/
public function setResourceModel($model)
{
$this->_resourceModel = $model;
}
/**
* Retrieve resource model name
*
* @return string
*/
public function getResourceModelName()
{
return $this->_resourceModel;
}
/**
* Get resource instance
*
* @return Mage_Core_Model_Resource_Db_Abstract
*/
public function getResource()
{
if (empty($this->_resource)) {
$this->_resource = Mage::getResourceModel($this->getResourceModelName());
}
return $this->_resource;
}
/**
* Retrieve table name
*
* @param string $table
* @return string
*/
public function getTable($table)
{
return $this->getResource()->getTable($table);
}
/**
* Retrieve all ids for collection
*
* @return array
*/
public function getAllIds()
{
$idsSelect = clone $this->getSelect();
$idsSelect->reset(Zend_Db_Select::ORDER);
$idsSelect->reset(Zend_Db_Select::LIMIT_COUNT);
$idsSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
$idsSelect->reset(Zend_Db_Select::COLUMNS);
$idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
return $this->getConnection()->fetchCol($idsSelect);
}
public function getData()
{
if ($this->_data === null) {
$this->_renderFilters()
->_renderOrders()
->_renderLimit();
/**
* Prepare select for execute
* @var string $query
*/
$query = $this->_prepareSelect($this->getSelect());
$this->_data = $this->_fetchAll($query, $this->_bindParams);
$this->_afterLoadData();
}
return $this->_data;
}
/**
* Prepare select for load
*
* @return string
*/
protected function _prepareSelect(Varien_Db_Select $select)
{
$helper = Mage::getResourceHelper('core');
$unionParts = $select->getPart(Zend_Db_Select::UNION);
if (!empty($unionParts)) {
$select = $helper->limitUnion($select);
}
if ($this->_useAnalyticFunction) {
return $helper->getQueryUsingAnalyticFunction($select);
}
return (string)$select;
}
/**
* Join table to collection select
*
* @param string $table
* @param string $cond
* @param string $cols
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function join($table, $cond, $cols = '*')
{
if (is_array($table)) {
foreach ($table as $k => $v) {
$alias = $k;
$table = $v;
break;
}
} else {
$alias = $table;
}
if (!isset($this->_joinedTables[$table])) {
$this->getSelect()->join(
array($alias => $this->getTable($table)),
$cond,
$cols
);
$this->_joinedTables[$alias] = true;
}
return $this;
}
/**
* Redeclare before load method for adding event
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _beforeLoad()
{
parent::_beforeLoad();
Mage::dispatchEvent('core_collection_abstract_load_before', array('collection' => $this));
if ($this->_eventPrefix && $this->_eventObject) {
Mage::dispatchEvent($this->_eventPrefix.'_load_before', array(
$this->_eventObject => $this
));
}
return $this;
}
/**
* Set reset items data changed flag
*
* @param boolean $flag
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function setResetItemsDataChanged($flag)
{
$this->_resetItemsDataChanged = (bool)$flag;
return $this;
}
/**
* Set flag data has changed to all collection items
*
* @return Mage_Core_Model_Mysql4_Collection_Abstract
*/
public function resetItemsDataChanged()
{
foreach ($this->_items as $item) {
$item->setDataChanges(false);
}
return $this;
}
/**
* Redeclare after load method for specifying collection items original data
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _afterLoad()
{
parent::_afterLoad();
foreach ($this->_items as $item) {
$item->setOrigData();
if ($this->_resetItemsDataChanged) {
$item->setDataChanges(false);
}
}
Mage::dispatchEvent('core_collection_abstract_load_after', array('collection' => $this));
if ($this->_eventPrefix && $this->_eventObject) {
Mage::dispatchEvent($this->_eventPrefix.'_load_after', array(
$this->_eventObject => $this
));
}
return $this;
}
/**
* Save all the entities in the collection
*
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
public function save()
{
foreach ($this->getItems() as $item) {
$item->save();
}
return $this;
}
/**
* Check if cache can be used for collection
*
* @return bool
*/
protected function _canUseCache()
{
return Mage::app()->useCache('collections') && !empty($this->_cacheConf);
}
/**
* Load cached data for select
*
* @param Zend_Db_Select $select
* @return string | false
*/
protected function _loadCache($select)
{
$data = Mage::app()->loadCache($this->_getSelectCacheId($select));
return $data;
}
/**
* Save collection data to cache
*
* @param array $data
* @param Zend_Db_Select $select
* @return Mage_Core_Model_Resource_Db_Collection_Abstract
*/
protected function _saveCache($data, $select)
{
Mage::app()->saveCache(serialize($data), $this->_getSelectCacheId($select), $this->_getCacheTags());
return $this;
}
/**
* Redeclared for processing cache tags throw application object
*
* @return array
*/
protected function _getCacheTags()
{
$tags = parent::_getCacheTags();
$tags[] = Mage_Core_Model_App::CACHE_TAG;
$tags[] = self::CACHE_TAG;
return $tags;
}
/**
* Format Date to internal database date format
*
* @param int|string|Zend_Date $date
* @param boolean $includeTime
* @return string
*/
public function formatDate($date, $includeTime = true)
{
return Varien_Date::formatDate($date, $includeTime);
}
}