AbstractCollection.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Model\ResourceModel\Db\Collection;
  7. use \Magento\Framework\App\ResourceConnection\SourceProviderInterface;
  8. use \Magento\Framework\Data\Collection\AbstractDb;
  9. /**
  10. * Abstract Resource Collection
  11. *
  12. * @api
  13. * @SuppressWarnings(PHPMD.NumberOfChildren)
  14. * @since 100.0.2
  15. */
  16. abstract class AbstractCollection extends AbstractDb implements SourceProviderInterface
  17. {
  18. /**
  19. * Model name
  20. *
  21. * @var string
  22. */
  23. protected $_model;
  24. /**
  25. * Resource model name
  26. *
  27. * @var string
  28. */
  29. protected $_resourceModel;
  30. /**
  31. * Resource instance
  32. *
  33. * @var \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  34. */
  35. protected $_resource;
  36. /**
  37. * Fields to select in query
  38. *
  39. * @var array|null
  40. */
  41. protected $_fieldsToSelect = null;
  42. /**
  43. * Expression fields to select in query.
  44. *
  45. * @var array
  46. */
  47. private $expressionFieldsToSelect = [];
  48. /**
  49. * Fields initial fields to select like id_field
  50. *
  51. * @var array|null
  52. */
  53. protected $_initialFieldsToSelect = null;
  54. /**
  55. * Fields to select changed flag
  56. *
  57. * @var boolean
  58. */
  59. protected $_fieldsToSelectChanged = false;
  60. /**
  61. * Store joined tables here
  62. *
  63. * @var array
  64. */
  65. protected $_joinedTables = [];
  66. /**
  67. * Collection main table
  68. *
  69. * @var string
  70. */
  71. protected $_mainTable = null;
  72. /**
  73. * Reset items data changed flag
  74. *
  75. * @var boolean
  76. */
  77. protected $_resetItemsDataChanged = false;
  78. /**
  79. * Name prefix of events that are dispatched by model
  80. *
  81. * @var string
  82. */
  83. protected $_eventPrefix = '';
  84. /**
  85. * Name of event parameter
  86. *
  87. * @var string
  88. */
  89. protected $_eventObject = '';
  90. /**
  91. * Event manager proxy
  92. *
  93. * @var \Magento\Framework\Event\ManagerInterface
  94. */
  95. protected $_eventManager = null;
  96. /**
  97. * @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
  98. * @param \Psr\Log\LoggerInterface $logger
  99. * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
  100. * @param \Magento\Framework\Event\ManagerInterface $eventManager
  101. * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection
  102. * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource
  103. */
  104. public function __construct(
  105. \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
  106. \Psr\Log\LoggerInterface $logger,
  107. \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
  108. \Magento\Framework\Event\ManagerInterface $eventManager,
  109. \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
  110. \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
  111. ) {
  112. $this->_eventManager = $eventManager;
  113. parent::__construct($entityFactory, $logger, $fetchStrategy, $connection);
  114. $this->_construct();
  115. $this->_resource = $resource;
  116. $this->setConnection($this->getResource()->getConnection());
  117. $this->_initSelect();
  118. }
  119. /**
  120. * Initialization here
  121. *
  122. * @return void
  123. */
  124. protected function _construct()
  125. {
  126. }
  127. /**
  128. * Retrieve main table
  129. *
  130. * @return string
  131. */
  132. public function getMainTable()
  133. {
  134. if ($this->_mainTable === null) {
  135. $this->setMainTable($this->getResource()->getMainTable());
  136. }
  137. return $this->_mainTable;
  138. }
  139. /**
  140. * Set main collection table
  141. *
  142. * @param string $table
  143. * @return $this
  144. */
  145. public function setMainTable($table)
  146. {
  147. $table = $this->getTable($table);
  148. if ($this->_mainTable !== null && $table !== $this->_mainTable && $this->getSelect() !== null) {
  149. $from = $this->getSelect()->getPart(\Magento\Framework\DB\Select::FROM);
  150. if (isset($from['main_table'])) {
  151. $from['main_table']['tableName'] = $table;
  152. }
  153. $this->getSelect()->setPart(\Magento\Framework\DB\Select::FROM, $from);
  154. }
  155. $this->_mainTable = $table;
  156. return $this;
  157. }
  158. /**
  159. * @inheritdoc
  160. */
  161. protected function _initSelect()
  162. {
  163. $this->getSelect()->from(['main_table' => $this->getMainTable()]);
  164. return $this;
  165. }
  166. /**
  167. * Get \Magento\Framework\DB\Select instance and applies fields to select if needed
  168. *
  169. * @return \Magento\Framework\DB\Select
  170. */
  171. public function getSelect()
  172. {
  173. if ($this->_select && $this->_fieldsToSelectChanged) {
  174. $this->_fieldsToSelectChanged = false;
  175. $this->_initSelectFields();
  176. }
  177. return parent::getSelect();
  178. }
  179. /**
  180. * Init fields for select
  181. *
  182. * @return $this
  183. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  184. * @SuppressWarnings(PHPMD.NPathComplexity)
  185. */
  186. protected function _initSelectFields()
  187. {
  188. $columns = $this->_select->getPart(\Magento\Framework\DB\Select::COLUMNS);
  189. $columnsToSelect = [];
  190. foreach ($columns as $columnEntry) {
  191. list($correlationName, $column, $alias) = $columnEntry;
  192. if ($correlationName !== 'main_table' || isset($this->expressionFieldsToSelect[$alias])) {
  193. // Add joined fields to select
  194. if ($column instanceof \Zend_Db_Expr) {
  195. $column = $column->__toString();
  196. }
  197. $key = $alias !== null ? $alias : $column;
  198. $columnsToSelect[$key] = $columnEntry;
  199. }
  200. }
  201. $columns = $columnsToSelect;
  202. $columnsToSelect = array_keys($columnsToSelect);
  203. if ($this->_fieldsToSelect !== null) {
  204. $insertIndex = 0;
  205. foreach ($this->_fieldsToSelect as $alias => $field) {
  206. if (!is_string($alias)) {
  207. $alias = null;
  208. }
  209. if ($field instanceof \Zend_Db_Expr) {
  210. $column = $field->__toString();
  211. } else {
  212. $column = $field;
  213. }
  214. if ($alias !== null &&
  215. in_array($alias, $columnsToSelect) ||
  216. // If field already joined from another table
  217. $alias === null &&
  218. isset($alias, $columnsToSelect)
  219. ) {
  220. continue;
  221. }
  222. $columnEntry = ['main_table', $field, $alias];
  223. array_splice($columns, $insertIndex, 0, [$columnEntry]);
  224. // Insert column
  225. $insertIndex++;
  226. }
  227. } else {
  228. array_unshift($columns, ['main_table', '*', null]);
  229. }
  230. $this->_select->setPart(\Magento\Framework\DB\Select::COLUMNS, $columns);
  231. return $this;
  232. }
  233. /**
  234. * Retrieve initial fields to select like id field
  235. *
  236. * @return array
  237. */
  238. protected function _getInitialFieldsToSelect()
  239. {
  240. if ($this->_initialFieldsToSelect === null) {
  241. $this->_initialFieldsToSelect = [];
  242. $this->_initInitialFieldsToSelect();
  243. }
  244. return $this->_initialFieldsToSelect;
  245. }
  246. /**
  247. * Initialize initial fields to select like id field
  248. *
  249. * @return $this
  250. */
  251. protected function _initInitialFieldsToSelect()
  252. {
  253. $idFieldName = $this->getResource()->getIdFieldName();
  254. if ($idFieldName) {
  255. $this->_initialFieldsToSelect[] = $idFieldName;
  256. }
  257. return $this;
  258. }
  259. /**
  260. * Add field to select
  261. *
  262. * @param string|array $field
  263. * @param string|null $alias
  264. * @return $this
  265. */
  266. public function addFieldToSelect($field, $alias = null)
  267. {
  268. if ($field === '*') {
  269. // If we will select all fields
  270. $this->_fieldsToSelect = null;
  271. $this->_fieldsToSelectChanged = true;
  272. return $this;
  273. }
  274. if (is_array($field)) {
  275. if ($this->_fieldsToSelect === null) {
  276. $this->_fieldsToSelect = $this->_getInitialFieldsToSelect();
  277. }
  278. foreach ($field as $key => $value) {
  279. $this->addFieldToSelect($value, is_string($key) ? $key : null);
  280. }
  281. $this->_fieldsToSelectChanged = true;
  282. return $this;
  283. }
  284. if ($alias === null) {
  285. $this->_fieldsToSelect[] = $field;
  286. } else {
  287. $this->_fieldsToSelect[$alias] = $field;
  288. }
  289. $this->_fieldsToSelectChanged = true;
  290. return $this;
  291. }
  292. /**
  293. * Add attribute expression (SUM, COUNT, etc)
  294. * Example: ('sub_total', 'SUM({{attribute}})', 'revenue')
  295. * Example: ('sub_total', 'SUM({{revenue}})', 'revenue')
  296. * For some functions like SUM use groupByAttribute.
  297. *
  298. * @param string $alias
  299. * @param string $expression
  300. * @param array|string $fields
  301. * @return $this
  302. */
  303. public function addExpressionFieldToSelect($alias, $expression, $fields)
  304. {
  305. // validate alias
  306. if (!is_array($fields)) {
  307. $fields = [$fields => $fields];
  308. }
  309. $fullExpression = $expression;
  310. foreach ($fields as $fieldKey => $fieldItem) {
  311. $fullExpression = str_replace('{{' . $fieldKey . '}}', $fieldItem, $fullExpression);
  312. }
  313. $this->getSelect()->columns([$alias => $fullExpression]);
  314. $this->expressionFieldsToSelect[$alias] = $fullExpression;
  315. return $this;
  316. }
  317. /**
  318. * Removes field from select
  319. *
  320. * @param string|null $field
  321. * @param bool $isAlias Alias identifier
  322. * @return $this
  323. */
  324. public function removeFieldFromSelect($field, $isAlias = false)
  325. {
  326. if ($isAlias) {
  327. if (isset($this->_fieldsToSelect[$field])) {
  328. unset($this->_fieldsToSelect[$field]);
  329. $this->_fieldsToSelectChanged = true;
  330. }
  331. } else {
  332. foreach ($this->_fieldsToSelect as $key => $value) {
  333. if ($value === $field) {
  334. unset($this->_fieldsToSelect[$key]);
  335. $this->_fieldsToSelectChanged = true;
  336. break;
  337. }
  338. }
  339. }
  340. return $this;
  341. }
  342. /**
  343. * Removes all fields from select
  344. *
  345. * @return $this
  346. */
  347. public function removeAllFieldsFromSelect()
  348. {
  349. $this->_fieldsToSelect = $this->_getInitialFieldsToSelect();
  350. $this->_fieldsToSelectChanged = true;
  351. return $this;
  352. }
  353. /**
  354. * Standard resource collection initialization
  355. *
  356. * @param string $model
  357. * @param string $resourceModel
  358. * @return $this
  359. */
  360. protected function _init($model, $resourceModel)
  361. {
  362. $this->setModel($model);
  363. $this->setResourceModel($resourceModel);
  364. return $this;
  365. }
  366. /**
  367. * Set model name for collection items
  368. *
  369. * @param string $model
  370. * @return $this
  371. */
  372. public function setModel($model)
  373. {
  374. if (is_string($model)) {
  375. $this->_model = $model;
  376. $this->setItemObjectClass($model);
  377. }
  378. return $this;
  379. }
  380. /**
  381. * Get model instance
  382. *
  383. * @return string
  384. */
  385. public function getModelName()
  386. {
  387. return $this->_model;
  388. }
  389. /**
  390. * Set resource model name for collection items
  391. *
  392. * @param string $model
  393. * @return void
  394. */
  395. public function setResourceModel($model)
  396. {
  397. $this->_resourceModel = $model;
  398. }
  399. /**
  400. * Retrieve resource model name
  401. *
  402. * @return string
  403. */
  404. public function getResourceModelName()
  405. {
  406. return $this->_resourceModel;
  407. }
  408. /**
  409. * Get resource instance
  410. *
  411. * @return \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  412. */
  413. public function getResource()
  414. {
  415. if (empty($this->_resource)) {
  416. $this->_resource = \Magento\Framework\App\ObjectManager::getInstance()->create(
  417. $this->getResourceModelName()
  418. );
  419. }
  420. return $this->_resource;
  421. }
  422. /**
  423. * Retrieve table name
  424. *
  425. * @param string $table
  426. * @return string
  427. */
  428. public function getTable($table)
  429. {
  430. return $this->getResource()->getTable($table);
  431. }
  432. /**
  433. * Retrieve all ids for collection
  434. *
  435. * @return array
  436. */
  437. public function getAllIds()
  438. {
  439. $idsSelect = clone $this->getSelect();
  440. $idsSelect->reset(\Magento\Framework\DB\Select::ORDER);
  441. $idsSelect->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
  442. $idsSelect->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET);
  443. $idsSelect->reset(\Magento\Framework\DB\Select::COLUMNS);
  444. $idsSelect->columns($this->getResource()->getIdFieldName(), 'main_table');
  445. return $this->getConnection()->fetchCol($idsSelect, $this->_bindParams);
  446. }
  447. /**
  448. * Join table to collection select
  449. *
  450. * @param string|array $table
  451. * @param string $cond
  452. * @param string|array $cols
  453. * @return $this
  454. */
  455. public function join($table, $cond, $cols = '*')
  456. {
  457. if (is_array($table)) {
  458. foreach ($table as $k => $v) {
  459. $alias = $k;
  460. $table = $v;
  461. break;
  462. }
  463. } else {
  464. $alias = $table;
  465. }
  466. if (!isset($this->_joinedTables[$alias])) {
  467. $this->getSelect()->join([$alias => $this->getTable($table)], $cond, $cols);
  468. $this->_joinedTables[$alias] = true;
  469. }
  470. return $this;
  471. }
  472. /**
  473. * Redeclare before load method for adding event
  474. *
  475. * @return $this
  476. */
  477. protected function _beforeLoad()
  478. {
  479. parent::_beforeLoad();
  480. $this->_eventManager->dispatch('core_collection_abstract_load_before', ['collection' => $this]);
  481. if ($this->_eventPrefix && $this->_eventObject) {
  482. $this->_eventManager->dispatch($this->_eventPrefix . '_load_before', [$this->_eventObject => $this]);
  483. }
  484. return $this;
  485. }
  486. /**
  487. * Set reset items data changed flag
  488. *
  489. * @param bool $flag
  490. * @return $this
  491. */
  492. public function setResetItemsDataChanged($flag)
  493. {
  494. $this->_resetItemsDataChanged = (bool)$flag;
  495. return $this;
  496. }
  497. /**
  498. * Set flag data has changed to all collection items
  499. *
  500. * @return $this
  501. */
  502. public function resetItemsDataChanged()
  503. {
  504. foreach ($this->_items as $item) {
  505. $item->setDataChanges(false);
  506. }
  507. return $this;
  508. }
  509. /**
  510. * Redeclare after load method for specifying collection items original data
  511. *
  512. * @return $this
  513. */
  514. protected function _afterLoad()
  515. {
  516. parent::_afterLoad();
  517. foreach ($this->_items as $item) {
  518. $item->setOrigData();
  519. if ($this->_resetItemsDataChanged && ($item instanceof \Magento\Framework\Model\AbstractModel)) {
  520. $item->setDataChanges(false);
  521. }
  522. }
  523. $this->_eventManager->dispatch('core_collection_abstract_load_after', ['collection' => $this]);
  524. if ($this->_eventPrefix && $this->_eventObject) {
  525. $this->_eventManager->dispatch($this->_eventPrefix . '_load_after', [$this->_eventObject => $this]);
  526. }
  527. return $this;
  528. }
  529. /**
  530. * Save all the entities in the collection
  531. *
  532. * @return $this
  533. */
  534. public function save()
  535. {
  536. foreach ($this->getItems() as $item) {
  537. $item->save();
  538. }
  539. return $this;
  540. }
  541. /**
  542. * @inheritdoc
  543. * @since 100.0.11
  544. */
  545. public function __sleep()
  546. {
  547. return array_diff(
  548. parent::__sleep(),
  549. ['_resource', '_eventManager']
  550. );
  551. }
  552. /**
  553. * @inheritdoc
  554. * @since 100.0.11
  555. */
  556. public function __wakeup()
  557. {
  558. parent::__wakeup();
  559. $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  560. $this->_eventManager = $objectManager->get(\Magento\Framework\Event\ManagerInterface::class);
  561. }
  562. }