Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jreviews/cdcfba03e3aa5e0f804cbab9a0eea311 to your computer and use it in GitHub Desktop.
Save jreviews/cdcfba03e3aa5e0f804cbab9a0eea311 to your computer and use it in GitHub Desktop.
Calculating a paid price average from user reviews https://www.jreviews.com/blog/calculating-paid-price-average-from-user-reviews
<?php
namespace JReviews\Listeners;
defined( 'MVC_FRAMEWORK') or die;
use JReviews\Listeners\Traits\ListenerSetting;
use Clickfwd\Listener\QueueableListener;
use League\Event\EventInterface;
use GuzzleHttp\Client as Guzzle;
\S2App::import('ListenerTrait','listener_setting','jreviews');
class UpdateListingAveragePrice extends QueueableListener
{
use ListenerSetting;
protected $queue = false;
/**
* Execution delay in seconds when using the Queue Add-on
* @var int
*/
protected $queue_delay = 60;
protected $reviewPriceField = 'jr_pricepaid';
protected $listingPriceField = 'jr_averagepricepaid';
public function handle(EventInterface $event)
{
$review = $event->getReview();
// Check if the submitted review includes a price
$pricePaid = (float) \S2Array::get($review,'Field.pairs.'.$this->reviewPriceField.'.value.0');
if ( $pricePaid && $review['Review']['extension'] == 'com_content' )
{
$model = new \S2Model();
switch($event->getName())
{
case 'JReviews\Events\ReviewWasDeleted':
// Excludes current review (in process of being deleted) from average
$averageQuery = sprintf('
SELECT
AVG(%s)
FROM #__jreviews_comments AS Review
LEFT JOIN #__jreviews_review_fields AS Field on Review.id = Field.reviewid
WHERE Review.pid = %d and Review.mode = "com_content" AND Review.published = 1 AND Review.id != %d AND Field.%s > 0
', $this->reviewPriceField, $review['Review']['listing_id'], $review['Review']['review_id'], $this->reviewPriceField);
break;
default:
$averageQuery = sprintf('
SELECT
AVG(%s)
FROM #__jreviews_comments AS Review
LEFT JOIN #__jreviews_review_fields AS Field on Review.id = Field.reviewid
WHERE Review.pid = %d and Review.mode = "com_content" AND Review.published = 1 AND Field.%s > 0
', $this->reviewPriceField, $review['Review']['listing_id'],$this->reviewPriceField);
break;
}
$averagePrice = $model->query($averageQuery,'loadResult');
$query = sprintf('
UPDATE
#__jreviews_content
SET %s = %s WHERE contentid = %d
', $this->listingPriceField, $averagePrice, $review['Review']['listing_id']);
$model->query($query);
}
}
}
<?php
defined( 'MVC_FRAMEWORK') or die;
use Clickfwd\Listener\ListenerProvider;
class CustomListenerProvider extends ListenerProvider
{
protected $listen = [
'JReviews\Events\ReviewWasFirstPublished' => [
'JReviews\Listeners\UpdateListingAveragePrice',
],
'JReviews\Events\ReviewWasUpdated' => [
'JReviews\Listeners\UpdateListingAveragePrice',
],
'JReviews\Events\ReviewWasDeleted' => [
'JReviews\Listeners\UpdateListingAveragePrice',
]
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment