Files
pollux/app/Http/helpers.php
T

122 lines
3.0 KiB
PHP

<?php
/**
* Returns true with a given percentage.
*
* @param int $prob Probability for true in percent.
* @return boolean
*/
function rand_bool($prob = 50)
{
if ($prob < 0 or $prob > 100) {
throw new InvalidArgumentException('The value for the probability '.
'must be in a range from 0 to 100.');
} else if (!is_int($prob)) {
throw new InvalidArgumentException('rand_bool only accepts integers.');
}
$rand = rand(1, 100);
return $rand <= $prob;
}
/**
* Return the formatted string representation of a floatng point number.
*
* The decimal point is a ',', the thousands seperator ist set to '.'.
* The number of decimals is 2 by default but can be set by the $decimals
* argument.
*
* @param integer $decimals Sets the number of decimal points.
* @return string
*/
function formatAmount(float $amount, $cash = true, $text = false,
$decimals = 2)
{
$euro = ($cash) ? ' €' : '';
if (!$text) {
$sign = ($amount < 0) ? '- ' : '';
$left = '<span style=\'float: left;\'>';
$right = '<span style=\'float: right;\'>';
$span = '</span>';
if ($amount == 0) {
return $right . '-&nbsp;' . $euro . $span;
}
return $left . $sign . $span . $right .
number_format(abs($amount), $decimals, ',', '.') . $euro . $span;
}
return number_format($amount, $decimals, ',', '.') . $euro;
}
/**
* Replace all commas in a string by a dot. This can be useful to convert
* strings that represent a float and use a comma as decimal point to a string
* of the same float but with a dot as decimal point.
*
* @return string
*/
function swapComma(string $floatString) {
return str_replace(',', '.', $floatString);
}
/**
* Return a formatted date string.
*
* @param string $date
* @param string $format
* @return string
*/
function formatDate($date, $format='d.m.Y')
{
return Carbon\Carbon::parse($date)->format($format);
}
/**
* Return the string that is the first day of the month, given by the year and
* the month.
*
* @param string $year
* @param string $month
* @return string
*/
function startOfMonth($year, $month, $format='d.m.Y')
{
return Carbon\Carbon::createFromDate($year, $month)
->startOfMonth()->format($format);
}
/**
* Return the string that is the last day of the month, given by the year and
* the month.
*
* @param string $year
* @param string $month
* @return string
*/
function endOfMonth($year, $month, $format='d.m.Y') {
return Carbon\Carbon::createFromDate($year, $month)
->endOfMonth()->format($format);
}
/**
* Check, if all fields of an array are null.
* Returns true, if all fields of $array are null. Returns fals,e otherwise
*
* @param array $array
* @return boolean
*/
function allEmpty($array)
{
foreach ($array as $item) {
if ($item !== null) {
return false;
}
}
return true;
}