| Current Path : /home/wirbesti/unwaehlbar.ch/ |
| Current File : /home/wirbesti/unwaehlbar.ch/PopularityProvider.php |
<?php
require __DIR__.'/Popularity.php';
use unelectable\Popularity;
class PopularityProvider
{
private $_database;
function __construct(DBConnection $database)
{
//$this->database = new DbConnection($config);
$this->_database = $database;
}
public function getPopularity($politicians)
{
$popularities = $this->_initArray($politicians);
if (count($popularities) == 0) {
return $popularities;
}
$filter = $this->_createFilter($popularities);
if (count($popularities) > 0) {
$polfilter = "`politicianid` in ".$filter." AND ";
} else {
$polfilter = '';
}
$query = "SELECT `politicianid`, COUNT(`vote`) upvotes, 0 as downvotes FROM `vote` v WHERE ".$polfilter." v.`vote` > 0 GROUP BY `politicianid` ".
"UNION SELECT `politicianid`, 0 as upvotes, COUNT(`vote`) as downvotes FROM `vote` v WHERE ".$polfilter." v.`vote` < 0 GROUP BY `politicianid`";
//echo 'sql = '.$query.'<br/>';
$rows = $this->_database->getQuery($query);
foreach ($rows as $row)
{
if ($row['upvotes'] > 0) {
$popularities[$row['politicianid']]->upvotes = $row['upvotes'];
}
if ($row['downvotes'] > 0) {
$popularities[$row['politicianid']]->downvotes = $row['downvotes'];
}
}
return $popularities;
}
public function getVotable($politicians)
{
$popularity = $this->getPopularity($politicians);
$votable = array();
foreach ($popularity as $key => $value)
{
$total = $value->upvotes + $value->downvotes;
if ($total > 0) {
$percent = $value->downvotes * 100 / $total;
if ($percent <= 50) {
$votable[$key] = $value;
}
}
}
return $votable;
}
public function getUnvotable($politicians)
{
$popularity = $this->getPopularity($politicians);
$unvotable = array();
foreach ($popularity as $key => $value)
{
$total = $value->upvotes + $value->downvotes;
if ($total > 0) {
$percent = $value->downvotes * 100 / $total;
if ($percent > 50) {
$unvotable[$key] = $value;
}
}
}
return $unvotable;
}
private function _initArray($politicians)
{
$popularities = array();
foreach ($politicians as $politician) {
$popularities[$politician['aid']] = new Popularity();
}
return $popularities;
}
private function _createFilter($popularities) {
$filter = "(";
foreach ($popularities as $key => $value) {
$filter = $filter.$key.",";
}
$filter = substr($filter, 0, -1);
$filter = $filter.")";
return $filter;
}
}
?>