REFACTORING #1880 @20m: move action log logic into repository

This commit is contained in:
Michal Kváček
2016-11-23 01:03:37 +01:00
parent 2fffea39fa
commit 3aabb8fa7b
5 changed files with 37 additions and 41 deletions
@@ -0,0 +1,93 @@
<?php
namespace App\Cms\Repositories\ActionLog;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class Actions
{
/**
* @param null $userId
*
* @return array
*/
public function getLoggedActions($userId = null)
{
$actions = $this->getLogActionsQuery(true);
$user = null;
if ($userId) {
$user = User::findOrFail($userId);
$actions->where('users.id', $userId);
}
$actions = $actions->paginate(25);
$this->translateLogMessages($actions);
return [$user, $actions];
}
/**
* Query factory for loading action logs with their type (therefore with name and value)
*
* @param bool $joinUser
*
* @return mixed
*/
public function getLogActionsQuery($joinUser = false)
{
$actions = \DB::table('action_log')
->select('action_log.*', 'action_log_types.*')
->join('action_log_types', 'action_log_types.id', '=', 'action_log.type_id')
->orderBy('action_log.created_at', 'DESC');
if ($joinUser) {
$actions = $actions->join('users', 'users.id', '=', 'action_log.user_id')
->select('action_log.*', 'action_log_types.*', 'users.email', 'users.name as user_name');
}
return $actions;
}
/**
* Get last N user actions
*
* @param null $id
* @param int $limit
*
* @return array
*/
public function getUserActions($id = null, $limit = 15)
{
// if user is not specified, use logged one
if (is_null($id)) {
$id = Auth::user()->id;
}
// load last N actions of selected user
$actions = $this->getLogActionsQuery()
->limit($limit)
->where('user_id', $id)
->get();
// translate and return result
$this->translateLogMessages($actions);
return $actions;
}
/**
* Method used for translating and filling parameters into value of log.
*
* @param $messages
*/
public function translateLogMessages(&$messages)
{
// translate name and value of each record
foreach ($messages as $i => $action) {
$messages[$i]->name = trans($action->name);
$messages[$i]->value = trans($action->value, (array)json_decode($action->parameters));
}
}
}