Skip to content
This repository was archived by the owner on Sep 10, 2020. It is now read-only.

Commit 20689dc

Browse files
authored
Merge pull request #24 from avto-dev/add-dev-functions
Add helpers functions and `VarDumper` service
2 parents aa9a32a + 19504cf commit 20689dc

14 files changed

Lines changed: 733 additions & 6 deletions

CHANGELOG.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog][keepachangelog] and this project adheres to [Semantic Versioning][semver].
66

7+
## v1.9.0
8+
9+
### Added
10+
11+
- Service `Laravel\VarDumper` (with middleware and stack instance)
12+
- Global helpers file (namespace `\dev\...`)
13+
- Function `\dev\dump(...$arguments)`
14+
- Function `\dev\dd(...$arguments)`
15+
716
## v1.8.0
817

918
### Added

Makefile

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/make
2+
# Makefile readme (ru): <http://linux.yaroslavl.ru/docs/prog/gnu_make_3-79_russian_manual.html>
3+
# Makefile readme (en): <https://www.gnu.org/software/make/manual/html_node/index.html#SEC_Contents>
4+
5+
docker_bin := $(shell command -v docker 2> /dev/null)
6+
7+
SHELL = /bin/sh
8+
PHP_IMAGE = composer:1.8
9+
RUN_ARGS = --rm -v "$(shell pwd):/src:cached" -v "/etc/passwd:/etc/passwd:ro" -v "/etc/group:/etc/group:ro" \
10+
--workdir "/src" -u "$(shell id -u):$(shell id -g)"
11+
RUN_INTERACTIVE ?= --tty --interactive
12+
13+
.PHONY : help install test shell
14+
.SILENT : help install shell test
15+
.DEFAULT_GOAL : help
16+
17+
# This will output the help for each task. thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
18+
help: ## Show this help
19+
@printf "\033[33m%s:\033[0m\n" 'Available commands'
20+
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " \033[32m%-14s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
21+
22+
install: ## Install all php dependencies
23+
$(docker_bin) run $(RUN_ARGS) $(RUN_INTERACTIVE) "$(PHP_IMAGE)" composer install --no-interaction --ansi --no-suggest --prefer-dist
24+
25+
test: ## Execute php tests and linters
26+
$(docker_bin) run $(RUN_ARGS) $(RUN_INTERACTIVE) "$(PHP_IMAGE)" composer test
27+
28+
shell: ## Start shell into container with php
29+
$(docker_bin) run $(RUN_ARGS) $(RUN_INTERACTIVE) \
30+
-e "PS1=\[\033[1;32m\]🐳 \[\033[1;36m\][\u@\h] \[\033[1;34m\]\w\[\033[0;35m\] \[\033[1;36m\]# \[\033[0m\]" \
31+
"$(PHP_IMAGE)" bash
32+
33+
clean: ## Remove all dependencies and unimportant files
34+
-rm -Rf ./composer.lock ./vendor

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,23 @@ $ composer require --dev avto-dev/dev-tools "^1.7.1"
2828

2929
Данный пакет позволяет легко интегрировать в ваше приложение вспомогательные инструменты, позволяющие более эффективно вести разработку. Разделить их можно на следующие группы:
3030

31+
## Вспомогательные функции
32+
33+
Имя функции | Её назначение
34+
----------- | -------------
35+
`\dev\dd(...$arguments)` | Выводит удобочитаемый дамп переданных в функцию значений, бросив специальным образом оформленное исключение (при вызове в HTTP-контексте; в CLI контексте работает как обычная `\dd(...)`) <sup>*</sup>
36+
`\dev\dump(...$arguments)` | Выводит удобочитаемый дамп переданных в функцию значений не прерывая обработку запроса. Необходима регистрация сервис-провайдера [VarDumper](./src/Laravel/VarDumper/ServiceProvider.php) (при вызове в HTTP-контексте; в CLI контексте работает как обычная `\dump(...)`) <sup>*</sup>
37+
38+
> **<sup> * </sup>** корректно работает в связке Laravel + [RoadRunner][roadrunner] (возможно и ReactPHP - не проверено)
39+
3140
## Вспомогательные сервисы для Laravel
3241

3342
Для Laravel-приложений вы можете подключать следующие сервис-провайдеры:
3443

3544
Сервис-провайдер | Его назначение
3645
---------------- | --------------
3746
[DatabaseQueriesLogger](./src/Laravel/DatabaseQueriesLogger/ServiceProvider.php) | Производит запись всех обращений к базе данных в лог-файл приложения
47+
[VarDumper](./src/Laravel/VarDumper/ServiceProvider.php) | Модифицирует HTTP-ответ приложения, добавляя в него результат работы вызовов функции `\dev\dump()`. Данный сервис-провайдер регистрируется **автоматически**
3848

3949
## Unit-тестирование приложения
4050

@@ -180,3 +190,4 @@ This is open-sourced software licensed under the [MIT License][link_license].
180190
[link_pulls]:https://github.com/avto-dev/dev-tools/pulls
181191
[link_license]:https://github.com/avto-dev/dev-tools/blob/master/LICENSE
182192
[getcomposer]:https://getcomposer.org/download/
193+
[roadrunner]:https://github.com/spiral/roadrunner

composer.json

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,42 @@
1515
],
1616
"require": {
1717
"php": ">=7.0",
18-
"phpunit/phpunit": "^6.5 || ~7.0 <7.5.0"
18+
"phpunit/phpunit": "^6.5 || ~7.0 <7.5.0",
19+
"symfony/var-dumper": "~3.3 || ^4.0"
1920
},
2021
"require-dev": {
2122
"ext-pdo_sqlite": "*",
2223
"ext-sqlite3": "*",
2324
"jeremeamia/superclosure": "^2.4",
2425
"nikic/php-parser": "^2.0 || ^3.0 || ^4.0",
2526
"laravel/laravel": ">=5.5 <5.8.0",
26-
"mockery/mockery": "~1.0",
27-
"symfony/var-dumper": "~3.3 || ^4.0"
27+
"phpstan/phpstan": "~0.9 || ^0.10",
28+
"mockery/mockery": "~1.0"
2829
},
2930
"autoload": {
3031
"psr-4": {
3132
"AvtoDev\\DevTools\\": "src"
32-
}
33+
},
34+
"files": [
35+
"src/functions/dump.php"
36+
]
3337
},
3438
"autoload-dev": {
3539
"psr-4": {
3640
"Tests\\AvtoDev\\DevTools\\": "tests"
3741
}
3842
},
43+
"extra": {
44+
"laravel": {
45+
"providers": [
46+
"AvtoDev\\DevTools\\Laravel\\VarDumper\\ServiceProvider"
47+
]
48+
}
49+
},
3950
"scripts": {
40-
"test": "@php ./vendor/bin/phpunit --no-coverage",
41-
"test-cover": "@php ./vendor/bin/phpunit"
51+
"test": "@php ./vendor/bin/phpunit --no-coverage --testdox --colors=always",
52+
"test-cover": "@php ./vendor/bin/phpunit",
53+
"phpstan": "@php ./vendor/bin/phpstan analyze --no-progress --ansi --level=max ./src"
4254
},
4355
"suggest": {
4456
"jeremeamia/superclosure": "Library for closures serialization and hashing",
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace AvtoDev\DevTools\Exceptions;
6+
7+
use Throwable;
8+
use Symfony\Component\HttpFoundation\Request;
9+
use Symfony\Component\HttpFoundation\Response;
10+
11+
class VarDumperException extends \Exception
12+
{
13+
/**
14+
* VarDumperException constructor.
15+
*
16+
* @param string $message
17+
* @param int $code
18+
* @param Throwable|null $previous
19+
*/
20+
public function __construct(string $message,
21+
int $code = Response::HTTP_INTERNAL_SERVER_ERROR,
22+
Throwable $previous = null)
23+
{
24+
parent::__construct($message, $code, $previous);
25+
}
26+
27+
/**
28+
* Report the exception.
29+
*
30+
* Since "illuminate/framework" v5.5.
31+
*
32+
* @link https://laravel.com/docs/5.5/errors#renderable-exceptions
33+
*
34+
* @return void
35+
*/
36+
public function report()
37+
{
38+
// Do nothing
39+
}
40+
41+
/**
42+
* Render the exception into an HTTP response.
43+
*
44+
* Since "illuminate/framework" v5.5.
45+
*
46+
* @link https://laravel.com/docs/5.5/errors#renderable-exceptions
47+
*
48+
* @param Request|null $request
49+
*
50+
* @return Response
51+
*/
52+
public function render(Request $request = null): Response
53+
{
54+
return new Response(static::generateView($this->getMessage()), $this->getCode());
55+
}
56+
57+
/**
58+
* Generate HTML representation of some content.
59+
*
60+
* @param string $content
61+
*
62+
* @return string
63+
*/
64+
protected static function generateView($content):string
65+
{
66+
return <<<EOT
67+
<html>
68+
<head></head>
69+
<body>
70+
$content
71+
</body>
72+
</html>
73+
EOT;
74+
}
75+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace AvtoDev\DevTools\Laravel\VarDumper;
6+
7+
class DumpStack implements DumpStackInterface
8+
{
9+
/**
10+
* @var string[]
11+
*/
12+
protected $stack = [];
13+
14+
/**
15+
* {@inheritdoc}
16+
*/
17+
public function push(string $data)
18+
{
19+
$this->stack[] = $data;
20+
}
21+
22+
/**
23+
* {@inheritdoc}
24+
*/
25+
public function clear()
26+
{
27+
$this->stack = [];
28+
}
29+
30+
/**
31+
* {@inheritdoc}
32+
*/
33+
public function all(): array
34+
{
35+
return $this->stack;
36+
}
37+
38+
/**
39+
* {@inheritdoc}
40+
*/
41+
public function count(): int
42+
{
43+
return \count($this->stack);
44+
}
45+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace AvtoDev\DevTools\Laravel\VarDumper;
6+
7+
use Countable;
8+
9+
interface DumpStackInterface extends Countable
10+
{
11+
/**
12+
* Push an element into stack.
13+
*
14+
* @param string $data
15+
*/
16+
public function push(string $data);
17+
18+
/**
19+
* Clear stack.
20+
*
21+
* @return void
22+
*/
23+
public function clear();
24+
25+
/**
26+
* Get all stack elements.
27+
*
28+
* @return string[]
29+
*/
30+
public function all(): array;
31+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace AvtoDev\DevTools\Laravel\VarDumper;
6+
7+
use Illuminate\Contracts\Http\Kernel;
8+
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
9+
10+
class ServiceProvider extends IlluminateServiceProvider
11+
{
12+
/**
13+
* Register service and listener.
14+
*
15+
* @return void
16+
*/
17+
public function boot()
18+
{
19+
$this->app->make(Kernel::class)->pushMiddleware(VarDumperMiddleware::class);
20+
}
21+
22+
/**
23+
* Register services.
24+
*
25+
* @return void
26+
*/
27+
public function register()
28+
{
29+
$this->app->singleton(DumpStackInterface::class, DumpStack::class);
30+
}
31+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace AvtoDev\DevTools\Laravel\VarDumper;
6+
7+
use Closure;
8+
use Illuminate\Http\Request;
9+
use Illuminate\Http\Response;
10+
11+
/**
12+
* @link https://laravel.com/docs/5.5/middleware#defining-middleware Before & After Middleware
13+
*/
14+
class VarDumperMiddleware
15+
{
16+
/**
17+
* @var DumpStackInterface
18+
*/
19+
protected $stack;
20+
21+
/**
22+
* Middleware constructor.
23+
*
24+
* @param DumpStackInterface $stack
25+
*/
26+
public function __construct(DumpStackInterface $stack)
27+
{
28+
$this->stack = $stack;
29+
}
30+
31+
/**
32+
* Modify response after the request is handled by the application.
33+
*
34+
* @param Request $request
35+
* @param Closure $next
36+
*
37+
* @return mixed
38+
*/
39+
public function handle(Request $request, Closure $next)
40+
{
41+
/** @var Response $response */
42+
$response = $next($request);
43+
44+
if ($this->stack->count() > 0) {
45+
$dumped = \implode(\PHP_EOL, $this->stack->all());
46+
47+
$this->stack->clear();
48+
49+
$response->setContent($dumped . $response->getContent());
50+
}
51+
52+
return $response;
53+
}
54+
}

0 commit comments

Comments
 (0)