Test Setup Failed
Push — master ( e53ccf...6b6842 )
by Georgi
03:45
created

HomePage::list()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Epesi\Core\HomePage\Model;
4
5
use atk4\data\Model;
6
use Epesi\Core\Data\HasEpesiConnection;
7
use Spatie\Permission\Models\Role;
8
use Epesi\Core\HomePage\Integration\Joints\HomePageJoint;
9
use Illuminate\Support\Facades\Auth;
10
use atk4\ui\Table;
11
12
class HomePage extends Model
13
{
14
    use HasEpesiConnection;
15
    
16
	public $table = 'home_pages';
17
	
18
	public $caption = 'Home Page';
19
	
20
	public $title_field = 'path';
21
	
22
	/**
23
	 * Fallback path in case no home page set for the user
24
	 *
25
	 * @var string
26
	 */
27
	protected static $defaultPath = 'view/user.settings';
28
	
29
	protected function init(): void
30
	{
31
		parent::init();
32
33
		$this->addFields([
34
		        'path' => [
35
						'caption' => __('Page'),
36
						'values' => self::list(),
37
						'ui' => [
38
								'table' => [
39
										Table\Column\KeyValue::class,
40
								],
41
								'filter' => true
42
						],
43
				],
44
		        'role' => [
45
						'caption' => __('Role'), 
46
						'values' => Role::get()->pluck('name', 'name')->all(), 
47
						'ui' => [
48
								'filter' => true
49
						]
50
				],
51
		        'date' => [
52
						'type' => 'date', 
53
						'caption' => __('Date'),
54
		                'never_persist' => true,
55
						'ui' => [
56
								'filter' => true
57
						]
58
				],
59
				'priority' => [
60
				        'default' => 0
61
				],
62
		]);
63
		
64
		$this->setOrder('priority');
65
66
		$this->onHook(\atk4\data\Model::HOOK_BEFORE_INSERT, function($model, & $data) {
67
			$data['priority'] = $data['priority']?: $this->action('fx', ['max', 'priority'])->getOne() + 1;
68
		});
69
	}
70
	
71
	/**
72
	 * Collect all home pages from module joints
73
	 *
74
	 * @return array
75
	 */
76
	public static function list()
77
	{
78
		static $cache;
79
		
80
		if (! isset($cache)) {
81
			$cache = [];
82
			foreach (HomePageJoint::collect() as $joint) {
83
				$cache[$joint->link()] = $joint->caption();
84
			}
85
		}
86
		
87
		return $cache;
88
	}
89
		
90
	/**
91
	 * Get the current user home page
92
	 *
93
	 * @return HomePage|null
94
	 */
95
	public static function ofUser()
96
	{
97
		if (! $user = Auth::user()) return;
98
		
99
		return self::create()->addCondition('role', $user->roles()->pluck('name')->toArray())->loadAny();
100
	}
101
	
102
	/**
103
	 * Get the current user home page path
104
	 *
105
	 * @return string
106
	 */
107
	public static function pathOfUser()
108
	{
109
		return HomePage::ofUser()->get('path') ?: self::$defaultPath;
110
	}
111
}
112