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
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Review\Model\ResourceModel;
use Magento\Framework\Model\AbstractModel;
/**
* Review resource model
*
* @api
* @since 100.0.2
*/
class Review extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
/**
* Review table
*
* @var string
*/
protected $_reviewTable;
/**
* Review Detail table
*
* @var string
*/
protected $_reviewDetailTable;
/**
* Review status table
*
* @var string
*/
protected $_reviewStatusTable;
/**
* Review entity table
*
* @var string
*/
protected $_reviewEntityTable;
/**
* Review store table
*
* @var string
*/
protected $_reviewStoreTable;
/**
* Review aggregate table
*
* @var string
*/
protected $_aggregateTable;
/**
* Cache of deleted rating data
*
* @var array
*/
private $_deleteCache = [];
/**
* Core date model
*
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $_date;
/**
* Core model store manager interface
*
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* Rating model
*
* @var \Magento\Review\Model\RatingFactory
*/
protected $_ratingFactory;
/**
* Rating resource model
*
* @var \Magento\Review\Model\ResourceModel\Rating\Option
*/
protected $_ratingOptions;
/**
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Magento\Review\Model\RatingFactory $ratingFactory
* @param \Magento\Review\Model\ResourceModel\Rating\Option $ratingOptions
* @param string $connectionName
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Review\Model\RatingFactory $ratingFactory,
Rating\Option $ratingOptions,
$connectionName = null
) {
$this->_date = $date;
$this->_storeManager = $storeManager;
$this->_ratingFactory = $ratingFactory;
$this->_ratingOptions = $ratingOptions;
parent::__construct($context, $connectionName);
}
/**
* Define main table. Define other tables name
*
* @return void
*/
protected function _construct()
{
$this->_init('review', 'review_id');
$this->_reviewTable = $this->getTable('review');
$this->_reviewDetailTable = $this->getTable('review_detail');
$this->_reviewStatusTable = $this->getTable('review_status');
$this->_reviewEntityTable = $this->getTable('review_entity');
$this->_reviewStoreTable = $this->getTable('review_store');
$this->_aggregateTable = $this->getTable('review_entity_summary');
}
/**
* Retrieve select object for load object data
*
* @param string $field
* @param mixed $value
* @param AbstractModel $object
* @return \Magento\Framework\DB\Select
*/
protected function _getLoadSelect($field, $value, $object)
{
$select = parent::_getLoadSelect($field, $value, $object);
$select->join(
$this->_reviewDetailTable,
$this->getMainTable() . ".review_id = {$this->_reviewDetailTable}.review_id"
);
return $select;
}
/**
* Perform actions before object save
*
* @param AbstractModel $object
* @return $this
*/
protected function _beforeSave(AbstractModel $object)
{
if (!$object->getId()) {
$object->setCreatedAt($this->_date->gmtDate());
}
if ($object->hasData('stores') && is_array($object->getStores())) {
$stores = $object->getStores();
$stores[] = 0;
$object->setStores($stores);
} elseif ($object->hasData('stores')) {
$object->setStores([$object->getStores(), 0]);
}
return $this;
}
/**
* Perform actions after object save
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
protected function _afterSave(AbstractModel $object)
{
$connection = $this->getConnection();
/**
* save detail
*/
$detail = [
'title' => $object->getTitle(),
'detail' => $object->getDetail(),
'nickname' => $object->getNickname(),
];
$select = $connection->select()->from($this->_reviewDetailTable, 'detail_id')->where('review_id = :review_id');
$detailId = $connection->fetchOne($select, [':review_id' => $object->getId()]);
if ($detailId) {
$condition = ["detail_id = ?" => $detailId];
$connection->update($this->_reviewDetailTable, $detail, $condition);
} else {
$detail['store_id'] = $object->getStoreId();
$detail['customer_id'] = $object->getCustomerId();
$detail['review_id'] = $object->getId();
$connection->insert($this->_reviewDetailTable, $detail);
}
/**
* save stores
*/
$stores = $object->getStores();
if (!empty($stores)) {
$condition = ['review_id = ?' => $object->getId()];
$connection->delete($this->_reviewStoreTable, $condition);
$insertedStoreIds = [];
foreach ($stores as $storeId) {
if (in_array($storeId, $insertedStoreIds)) {
continue;
}
$insertedStoreIds[] = $storeId;
$storeInsert = ['store_id' => $storeId, 'review_id' => $object->getId()];
$connection->insert($this->_reviewStoreTable, $storeInsert);
}
}
// reaggregate ratings, that depend on this review
$this->_aggregateRatings($this->_loadVotedRatingIds($object->getId()), $object->getEntityPkValue());
return $this;
}
/**
* Perform actions after object load
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
protected function _afterLoad(AbstractModel $object)
{
$connection = $this->getConnection();
$select = $connection->select()->from(
$this->_reviewStoreTable,
['store_id']
)->where(
'review_id = :review_id'
);
$stores = $connection->fetchCol($select, [':review_id' => $object->getId()]);
if (empty($stores) && $this->_storeManager->hasSingleStore()) {
$object->setStores([$this->_storeManager->getStore(true)->getId()]);
} else {
$object->setStores($stores);
}
return $this;
}
/**
* Action before delete
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
protected function _beforeDelete(AbstractModel $object)
{
// prepare rating ids, that depend on review
$this->_deleteCache = [
'ratingIds' => $this->_loadVotedRatingIds($object->getId()),
'entityPkValue' => $object->getEntityPkValue(),
];
return $this;
}
/**
* Perform actions after object delete
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return $this
*/
public function afterDeleteCommit(AbstractModel $object)
{
$this->aggregate($object);
// reaggregate ratings, that depended on this review
$this->_aggregateRatings($this->_deleteCache['ratingIds'], $this->_deleteCache['entityPkValue']);
$this->_deleteCache = [];
return $this;
}
/**
* Retrieves total reviews
*
* @param int $entityPkValue
* @param bool $approvedOnly
* @param int $storeId
* @return int
*/
public function getTotalReviews($entityPkValue, $approvedOnly = false, $storeId = 0)
{
$connection = $this->getConnection();
$select = $connection->select()->from(
$this->_reviewTable,
['review_count' => new \Zend_Db_Expr('COUNT(*)')]
)->where(
"{$this->_reviewTable}.entity_pk_value = :pk_value"
);
$bind = [':pk_value' => $entityPkValue];
if ($storeId > 0) {
$select->join(
['store' => $this->_reviewStoreTable],
$this->_reviewTable . '.review_id=store.review_id AND store.store_id = :store_id',
[]
);
$bind[':store_id'] = (int) $storeId;
}
if ($approvedOnly) {
$select->where("{$this->_reviewTable}.status_id = :status_id");
$bind[':status_id'] = \Magento\Review\Model\Review::STATUS_APPROVED;
}
return $connection->fetchOne($select, $bind);
}
/**
* Aggregate
*
* @param \Magento\Framework\Model\AbstractModel $object
* @return void
*/
public function aggregate($object)
{
if (!$object->getEntityPkValue() && $object->getId()) {
$object->load($object->getReviewId());
}
$ratingModel = $this->_ratingFactory->create();
$ratingSummaries = $ratingModel->getEntitySummary($object->getEntityPkValue(), false);
foreach ($ratingSummaries as $ratingSummaryObject) {
$this->aggregateReviewSummary($object, $ratingSummaryObject);
}
}
/**
* Aggregate review summary
*
* @param \Magento\Framework\Model\AbstractModel $object
* @param \Magento\Review\Model\Rating $ratingSummaryObject
* @return void
*/
protected function aggregateReviewSummary($object, $ratingSummaryObject)
{
$connection = $this->getConnection();
if ($ratingSummaryObject->getCount()) {
$ratingSummary = round($ratingSummaryObject->getSum() / $ratingSummaryObject->getCount());
} else {
$ratingSummary = $ratingSummaryObject->getSum();
}
$reviewsCount = $this->getTotalReviews(
$object->getEntityPkValue(),
true,
$ratingSummaryObject->getStoreId()
);
$select = $connection->select()->from($this->_aggregateTable)
->where('entity_pk_value = :pk_value')
->where('entity_type = :entity_type')
->where('store_id = :store_id');
$bind = [
':pk_value' => $object->getEntityPkValue(),
':entity_type' => $object->getEntityId(),
':store_id' => $ratingSummaryObject->getStoreId(),
];
$oldData = $connection->fetchRow($select, $bind);
$data = new \Magento\Framework\DataObject();
$data->setReviewsCount($reviewsCount)
->setEntityPkValue($object->getEntityPkValue())
->setEntityType($object->getEntityId())
->setRatingSummary($ratingSummary > 0 ? $ratingSummary : 0)
->setStoreId($ratingSummaryObject->getStoreId());
$this->writeReviewSummary($oldData, $data);
}
/**
* Write rating summary
*
* @param array|bool $oldData
* @param \Magento\Framework\DataObject $data
* @return void
*/
protected function writeReviewSummary($oldData, \Magento\Framework\DataObject $data)
{
$connection = $this->getConnection();
$connection->beginTransaction();
try {
if (isset($oldData['primary_id']) && $oldData['primary_id'] > 0) {
$condition = ["{$this->_aggregateTable}.primary_id = ?" => $oldData['primary_id']];
$connection->update($this->_aggregateTable, $data->getData(), $condition);
} else {
$connection->insert($this->_aggregateTable, $data->getData());
}
$connection->commit();
} catch (\Exception $e) {
$connection->rollBack();
}
}
/**
* Get rating IDs from review votes
*
* @param int $reviewId
* @return array
*/
protected function _loadVotedRatingIds($reviewId)
{
$connection = $this->getConnection();
if (empty($reviewId)) {
return [];
}
$select = $connection->select()->from(['v' => $this->getTable('rating_option_vote')], 'r.rating_id')
->joinInner(['r' => $this->getTable('rating')], 'v.rating_id=r.rating_id')
->where('v.review_id = :revire_id');
return $connection->fetchCol($select, [':revire_id' => $reviewId]);
}
/**
* Aggregate this review's ratings.
* Useful, when changing the review.
*
* @param int[] $ratingIds
* @param int $entityPkValue
* @return $this
*/
protected function _aggregateRatings($ratingIds, $entityPkValue)
{
if ($ratingIds && !is_array($ratingIds)) {
$ratingIds = [(int)$ratingIds];
}
if ($ratingIds && $entityPkValue) {
foreach ($ratingIds as $ratingId) {
$this->_ratingOptions->aggregateEntityByRatingId($ratingId, $entityPkValue);
}
}
return $this;
}
/**
* Reaggregate this review's ratings.
*
* @param int $reviewId
* @param int $entityPkValue
* @return void
*/
public function reAggregateReview($reviewId, $entityPkValue)
{
$this->_aggregateRatings($this->_loadVotedRatingIds($reviewId), $entityPkValue);
}
/**
* Get review entity type id by code
*
* @param string $entityCode
* @return int|bool
*/
public function getEntityIdByCode($entityCode)
{
$connection = $this->getConnection();
$select = $connection->select()->from($this->_reviewEntityTable, ['entity_id'])
->where('entity_code = :entity_code');
return $connection->fetchOne($select, [':entity_code' => $entityCode]);
}
/**
* Delete reviews by product id.
* Better to call this method in transaction, because operation performed on two separated tables
*
* @param int $productId
* @return $this
*/
public function deleteReviewsByProductId($productId)
{
$this->getConnection()->delete(
$this->_reviewTable,
[
'entity_pk_value=?' => $productId,
'entity_id=?' => $this->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)
]
);
$this->getConnection()->delete(
$this->getTable('review_entity_summary'),
[
'entity_pk_value=?' => $productId,
'entity_type=?' => $this->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE)
]
);
return $this;
}
}