Skip to content

Instantly share code, notes, and snippets.

@james0r
Created September 6, 2022 05:02
Show Gist options
  • Save james0r/8d271290b593e6695bf2f737b0fe1d3c to your computer and use it in GitHub Desktop.
Save james0r/8d271290b593e6695bf2f737b0fe1d3c to your computer and use it in GitHub Desktop.
<?php
public function onTotalsCalculate() {
$storedPassword = $this->config->get('plugins.gravel.webhook_password');
$providedPassword = $this->grav['uri']->param('p');
if ($storedPassword === $providedPassword) {
$flex = Grav::instance()['flex'];
$reviewsCol = $flex->getCollection('reviews');
$locationsDir = $flex->getDirectory('locations');
$reviewsApproved = $reviewsCol->filterBy(['approved' => true, 'processed' => false]);
$reviewsProcessed = $reviewsCol->filterBy(['processed' => true]);
$locationsProcessedInTask = [];
$totalProcessedInTask = 0;
foreach ($reviewsApproved as $ra) {
$cafeKey = $ra->getProperty('cafe_key');
$locationObj = $locationsDir->getObject($cafeKey);
if (!$locationObj) {
continue;
}
$ratingsKeyList = $this->getRatingsKeyList();
$total_numbers = 1;
foreach ($reviewsProcessed as $rp) {
if ($rp->getProperty('cafe_key') == $cafeKey) {
$total_numbers++;
}
}
foreach ($ratingsKeyList as $key) {
$new_number = $ra->getProperty($key);
$key = str_replace('cafe_', '', $key);
$last_average = $locationObj->getProperty($key);
$new_average = (($last_average * $total_numbers) + $new_number) / ($total_numbers + 1);
$locationObj->setProperty($key, round($new_average));
$locationObj->save();
}
array_push($locationsProcessedInTask, $locationObj);
$totalProcessedInTask++;
}
$this->json([
'success' => true,
'rating_keys' => $this->getRatingsKeyList(),
'locations_processed_in_task' => $locationsProcessedInTask
]);
} else {
$response = new Response(403);
$this->grav->close($response);
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment