Skip to content

Instantly share code, notes, and snippets.

@sanchezzzhak
Created January 13, 2022 08:45
Show Gist options
  • Save sanchezzzhak/da7c4f5957bc8fd777bc5f8f75a32930 to your computer and use it in GitHub Desktop.
Save sanchezzzhak/da7c4f5957bc8fd777bc5f8f75a32930 to your computer and use it in GitHub Desktop.
counts the number of stars based on like, unlike for PHP
<?php
// ...
trait CalculateStars {
/**
* подсчитывает количество звезд на основе like, unlike
*
* @param int $stars - количество звезд
* @param int $round - округление по умолчанию до целого
* @return float|int
*/
public function calculateStars(int $stars = 5, $round = 0)
{
$likesTotal = (int)$this->count_like; // prop for yii2 model or other class
$dislikeTotal = (int)$this->count_unlike;
$total = $dislikeTotal + $likesTotal;
if ($total === 0 || $stars === 0) {
return 0;
}
$value = ($stars-($dislikeTotal/($likesTotal/$stars)));
$rate = round($value, $round);
return $rate >=0 ? $rate: 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment