121 lines
3.0 KiB
PHP
121 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\Exceptions\AdminOptionsInvalidException;
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Http\Request;
|
|
use Gate;
|
|
use Arr;
|
|
use mysql_xdevapi\Exception;
|
|
use Str;
|
|
use Validator;
|
|
|
|
/**
|
|
* 網站設定選項
|
|
* Class OptionsController
|
|
* @package App\Http\Controllers\Admin
|
|
*/
|
|
class OptionsController extends Controller
|
|
{
|
|
private $request;
|
|
|
|
public function __construct(Request $request)
|
|
{
|
|
$this->request = $request;
|
|
}
|
|
|
|
/**
|
|
* 檢查權限
|
|
*
|
|
* @param $gateName
|
|
*/
|
|
private function gate($gateName)
|
|
{
|
|
if(Gate::denies($gateName)) {
|
|
abort(403);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 驗證欄位
|
|
*
|
|
* @param $options
|
|
* @throws \Illuminate\Validation\ValidationException
|
|
*/
|
|
private function validateOptions($options)
|
|
{
|
|
$rules = collect($options['fields'])
|
|
->filter(function($item, $key){
|
|
return isset($item['validator']);
|
|
})
|
|
->map(function($item, $key){
|
|
return $item['validator'];
|
|
});
|
|
|
|
$this->validate($this->request, $rules->all());
|
|
}
|
|
|
|
/**
|
|
* 更新欄位資料
|
|
*
|
|
* @param $options
|
|
*/
|
|
private function update($options)
|
|
{
|
|
$fields = $this->request->only(array_keys($options['fields']));
|
|
|
|
$checkboxOptions = collect($options['fields'])
|
|
->filter(function($item, $key){
|
|
return isset($item['type']) && $item['type'] = 'checkbox';
|
|
});
|
|
|
|
foreach ($fields as $key => $value) {
|
|
app('Option')->$key = $value;
|
|
}
|
|
foreach ($checkboxOptions as $key => $checkboxOption) {
|
|
if(!$this->request->has($key)) {
|
|
app('Option')->$key = '';
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 處理更新選項的動作並回應
|
|
*
|
|
* @param $options
|
|
* @return \Illuminate\Http\RedirectResponse
|
|
* @throws \Illuminate\Validation\ValidationException
|
|
*/
|
|
private function generateResponse($options)
|
|
{
|
|
$this->validateOptions($options);
|
|
|
|
$this->update($options);
|
|
return back()->with(['updated' => trans('message.success')]);
|
|
}
|
|
|
|
/**
|
|
* 處理更新選項的動作
|
|
*
|
|
* @param string $method
|
|
* @param array $args
|
|
* @return \Illuminate\Http\RedirectResponse|mixed
|
|
* @throws \Exception
|
|
*/
|
|
public function __call($method, $args = [])
|
|
{
|
|
$config = config('admin.options');
|
|
if(preg_match('/^update/', $method)) {
|
|
$page = strtolower(preg_replace('/^update/', '', $method));
|
|
if(in_array($page, array_keys($config))) {
|
|
if(!empty($config[$page]['permission'])) {
|
|
$this->gate('permission:' . Str::kebab($config[$page]['permission']));
|
|
}
|
|
return $this->generateResponse($config[$page]);
|
|
}
|
|
}
|
|
throw new \Exception("method: $method dos not exist");
|
|
}
|
|
}
|