Skip to content

Instantly share code, notes, and snippets.

@pekhota
Created December 26, 2017 17:46
Show Gist options
  • Save pekhota/7082c899534f9d06f9e1b7daab1b6e42 to your computer and use it in GitHub Desktop.
Save pekhota/7082c899534f9d06f9e1b7daab1b6e42 to your computer and use it in GitHub Desktop.
Быстрая telegram интеграция
<?php
namespace App\Exceptions;
use Throwable;
class GroupOfExceptions extends \RuntimeException
{
protected $_groupOfExceptions;
public function __construct($groupOfExceptions, $message = "Group Of Exceptions", $code = 0, Throwable $previous = null)
{
$this->_groupOfExceptions = $groupOfExceptions;
parent::__construct($message, $code, $previous);
}
public function getExceptions() {
return $this->_groupOfExceptions;
}
}
<?php
namespace App\Exceptions;
use App\Exceptions\JsonExceptionHandlers\HandlersFactory;
use App\Services\Telegram;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
NotFoundHttpException::class
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
*
* @return void
*/
public function report(Exception $exception)
{
if($exception instanceof SkipLogException) {
// do nothing
} else {
parent::report($exception);
}
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
*/
public function render($request, Exception $exception)
{
if ($this->shouldReport($exception) && !\App::environment('local')) {
Telegram::init()->notifyAboutException($exception, $request);
}
// If the request wants JSON (AJAX doesn't always want JSON)
if ($request->wantsJson()) {
// Define the response
$response = [];
$handler = (new HandlersFactory())->getHandler($exception);
$status = $handler->getStatusCode();
$response['message'] = $handler->getMessage();
$response['error'] = $handler->getError();
$response['data'] = $handler->getData();
// If the app is in debug mode
if (config('app.debug')) {
// Add the exception class name, message and stack trace to response
$response['exception'] = get_class($exception); // Reflection might be better here
$response['trace'] = $exception->getTrace();
}
// Return a JSON response with the response array and status code
return response()->json($response, $status);
}
return parent::render($request, $exception);
}
public function renderForConsole($output, Exception $exception)
{
Telegram::init()->notifyAboutException($exception);
parent::renderForConsole($output, $exception);
}
}
<?php
namespace App\Services;
use App\Exceptions\GroupOfExceptions;
use Illuminate\Http\Request;
class Telegram
{
/**
* @return Telegram
*/
public static function init(): Telegram
{
return new self();
}
protected function debug()
{
return false;
}
/**
* https://segment.com/blog/how-to-make-async-requests-in-php/
* @param $url
* @param $payload
*
* @return bool
*/
public function request($url, $payload)
{
$cmd = "curl -X POST -H 'Content-Type: application/json'";
$cmd .= " -d '" . $payload . "' " . "'" . $url . "'";
if ( ! $this->debug()) {
$cmd .= ' > /dev/null 2>&1 &';
}
exec($cmd, $output, $exit);
return $exit === 0;
}
public static function messageFromArray(array $msg) {
return implode("\n", $msg);
}
/**
* @param $text
* @param null $chatId
*/
public function sendMessage($text, $chatId = null): void
{
if ($chatId === null) {
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$chatId = config('telegram.chat_id');
}
$botToken = config('telegram.bot_token');
// todo check length for the message and split it for 2 if needed
$this->request('https://api.telegram.org/bot' . $botToken . '/sendMessage', json_encode([
'chat_id' => $chatId,
'text' => $text
]));
}
/**
* @param \Throwable $exception
*
* @param Request|null $request
*
* @return string
*/
public function exceptionToMsg(\Throwable $exception, Request $request = null): string
{
$text = '';
$text .= 'Class: ' . \get_class($exception) . ";\n"
. 'Message: ' . $exception->getMessage() . ";\n"
. 'Originates: ' . $exception->getFile() . ' (' . $exception->getLine() . ")\n"
. 'Trace: ' . $exception->getTraceAsString() . ";\n";
if($request !== null) {
$text .= 'Url: '.$request->fullUrl().";\n";
}
$text .= str_repeat('+', 50) . "\n";
return $text;
}
/**
* @param \Throwable $exception
* @param Request|null $request
*/
public function notifyAboutException(\Throwable $exception, Request $request = null): void
{
if ($exception instanceof GroupOfExceptions) {
/** @var \Throwable[] $exceptions */
$exceptions = $exception->getExceptions();
foreach ($exceptions as $singleException) {
$this->sendMessage($this->exceptionToMsg($singleException, $request));
}
} else {
$this->sendMessage($this->exceptionToMsg($exception, $request));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment