Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Corregido comprobación campo totales #1683

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions Core/Model/Base/JoinModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,13 @@ public function primaryColumnValue()
return null;
}

/**
* Returns the total sum of the indicated field.
*
* @param string $field
* @param array $where
* @return float
*/
public function totalSum(string $field, array $where = []): float
{
// buscamos en caché
Expand All @@ -334,9 +341,9 @@ public function totalSum(string $field, array $where = []): float
$fields = $this->getFields();
$field = $fields[$field] ?? $field;

$sql = false !== strpos($field, '(') ?
'SELECT ' . $field . ' AS total_sum' . ' FROM ' . $this->getSQLFrom() . DataBaseWhere::getSQLWhere($where) :
'SELECT SUM(' . $field . ') AS total_sum' . ' FROM ' . $this->getSQLFrom() . DataBaseWhere::getSQLWhere($where);
$sql = $this->checkTotalField($field)
? 'SELECT SUM(' . $field . ') AS total_sum' . ' FROM ' . $this->getSQLFrom() . DataBaseWhere::getSQLWhere($where)
: 'SELECT ' . $field . ' AS total_sum' . ' FROM ' . $this->getSQLFrom() . DataBaseWhere::getSQLWhere($where);

$data = self::$dataBase->select($sql);
$sum = count($data) == 1 ? (float)$data[0]['total_sum'] : 0.0;
Expand Down Expand Up @@ -384,6 +391,26 @@ private function checkTables(): bool
return true;
}

/**
* Check if the field can be a total field.
*
* @param string $field
* @return bool
*/
private function checkTotalField(string $field): bool
{
$field = strtolower($field);
if (is_numeric(strpos($field, 'sum('))
|| is_numeric(strpos($field, 'max('))
|| is_numeric(strpos($field, 'min('))
|| is_numeric(strpos($field, 'avg('))
|| is_numeric(strpos($field, '(select'))
) {
return false;
}
return true;
}

/**
* Convert the list of fields into a string to use as a select clause
*
Expand Down