File: D:/HostingSpaces/SBogers10/hours.komma.pro/app/Komma/Absences/AbsencesService.php
<?php
namespace App\Komma\Absences;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
class AbsencesService
{
protected $absenceRepository;
/**
* AbsencesService constructor.
* @param AbsencesRepository $absenceRepository
*/
public function __construct(AbsencesRepository $absenceRepository)
{
$this->absenceRepository = $absenceRepository;
}
/**
* @param $begin
* @param $end
* @param $user
* @return mixed
*/
public function filterAbsenceAndGroup($begin, $end, $user)
{
$absenceTypes = [];
//get absences
$fullAbsenceTypes = $this->absenceRepository->AbsenceTypes();
//loop though absences
foreach ($fullAbsenceTypes as $absenceType) {
//filter absences
$absenceTypes[] = $this->filterAbsence($absenceType, $begin, $end, $user);
}
return $absenceTypes;
}
/**
* @param $absences
* @param $begin
* @param $end
* @param $user
* @return mixed
*/
public function filterAbsence($absenceType, $begin, $end, $user)
{
//create correct begin and end date
$begin = !empty($begin) ? Carbon::parse($begin) : "";
$end = !empty($end) ? Carbon::parse($end) : "";
//loop though absences
foreach ($absenceType->Absences as $key => $absence) {
//check if hour date is between begin and end date
if (Carbon::parse($absence->date)->between($begin, $end)) {
//get other user
if (!empty($user) && $absence->User->name != $user) {
//if not all users is selected
if ($user != "all") {
//remove absence from collection
unset($absenceType->Absences[$key]);
}
}
} else {
//remove absence from collection
unset($absenceType->Absences[$key]);
}
}
$absenceType->Absences = $absenceType->Absences->sortByDesc('date');
//return
return $absenceType;
}
/**
* @param $absences
* @param $userId
* @return array
*/
public function getAbsenceTotals($absenceType, $userId, $begin, $end)
{
//get a begin and end date
$yearBegin = Carbon::parse($begin)->format('Y');
$yearEnd = Carbon::parse($end)->format('Y');
//create empty array
$sumValue = [];
$balance = null;
//loop trough balances
foreach ($absenceType->AbsenceBalances as $absenceBalance) {
//if is user and correct year
if ($absenceBalance->user_id == $userId and $absenceBalance->year == $yearBegin) {
//get balance
$balance = $absenceBalance->balance;
//if there is a second year chosen
if ($yearBegin != $yearEnd) {
//sum second year balance
$balance = $absenceBalance->balance + $absenceType->AbsenceBalances->where('user_id', $userId)->where('absence_type_id', $absenceBalance->absence_type_id)->where('year', $yearEnd)->first()->balance;
}
}
}
foreach ($absenceType->Absences as $absence) {
//replace , to .
$sumValue[] = $absence->value;
}
//sum array
$sumValue = array_sum($sumValue);
//return
return compact('balance', 'sumValue');
}
}