2018-11-05 09:26:30 +08:00

88 lines
2.4 KiB
PHP

<?php
namespace Dipper\FlashMessage;
use Illuminate\Support\Facades\View;
use InvalidArgumentException;
use BadMethodCallException;
/**
* @method info($message, $url = '', $options = [])
* @method success($message, $url = '', $options = [])
* @method warn($message, $url = '', $options = [])
*/
class Messager
{
protected $config;
protected $view;
protected $options;
public function __construct($config)
{
$this->config = $config;
$this->view();
}
public function __call($method, $args)
{
if (in_array($method, ['info', 'success', 'warn'])) {
$this->show($args[0], $args[1], $args[2], $method);
}
throw new BadMethodCallException();
}
public function error($message, $url = '', $options = [], $code = -1, $httpStatus = 200)
{
$this->show($message, $url, $options, 'error', $code, $httpStatus);
}
public function show($message, $url = '', $options = [], $level = 'info', $code = 0, $httpStatus = 200)
{
$return = [
'code' => $code,
'message' => $message,
'data' => array_merge($this->options, (array)$options)
];
if (app('request')->ajax() || app('request')->pjax() || app('request')->is('api/*')) {
$response = response()->json($return);
} else {
if ($url) {
$return['url'] = $url;
}
$return['level'] = $level;
$return['message'] = nl2br($message);
$response = response($this->view->with($return));
}
$response->setStatusCode($httpStatus)->send();
exit;
}
public function notify($message, $options = [], $level = 'info')
{
View::share('flashmessage', ['message' => $message, 'options' => array_merge($this->options, (array)$options), 'level' => $level]);
}
public function with($key, $value = null)
{
$this->view->with($key, $value);
return $this;
}
public function view($name = '')
{
$name = $name ?: $this->config['default'];
if (isset($this->config['views'][$name])) {
$this->options = (array)$this->config['views'][$name]['options'];
$this->view = view($this->config['views'][$name]['view']);
return $this;
}
throw new InvalidArgumentException("FlashMessage view [{$name}] is not defined");
}
}