Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat] Json Printer with Variable #19

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 40 additions & 5 deletions src/JsonPrinter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Here;

use Here\Abstracts\Printer;
use ReflectionClass;

class JsonPrinter extends Printer
{
Expand All @@ -27,9 +28,10 @@ public function dump(...$var)
$snapshot = Here::getCapture($file, $capture);

$this->sendJson([
'file' => $this->content['file'],
'line' => $this->content['line'],
'snapshot' => array_map(fn ($trim) => trim($trim), $snapshot),
'file' => $this->content['file'],
'line' => $this->content['line'],
'snapshot' => array_map(fn ($trim) => trim($trim), $snapshot),
'var' => $this->encodeVar($var),
]);
}

Expand Down Expand Up @@ -109,7 +111,7 @@ public function countAll()
*/
private function sendJson($out)
{
$this->send(json_encode($out));
$this->send(json_encode($out, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, 512));
}

/**
Expand All @@ -127,7 +129,7 @@ protected function send($out)
$connector = new \React\Socket\Connector();

$connector->connect($uri)->then(function (\React\Socket\ConnectionInterface $connection) use ($out) {
$connection->end($out);
$connection->end(PHP_EOL . $out);
}, function (\Exception $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
});
Expand All @@ -146,4 +148,37 @@ protected function printInfo(&$print, $content, $with_counter = false)
protected function printSnapshot(&$print, $content, ...$var)
{
}

/**
* Encode variable.
*
* @param array<int, mixed> $var
*
* @return string
*/
private function encodeVar($var)
{
$var = $var[0];

$encode = [];
if (is_callable($var)) {
$var = call_user_func($var);
}

if (is_object($var)) {
$obj = (object) $var;
$class = new ReflectionClass($obj);

$encode['name'] = $class->name;
foreach ($class->getDefaultProperties() as $name => $value) {
$property = $class->getProperty($name);
$property->setAccessible(true);
$value = $property->getValue($obj);

$encode[$name] = $value;
}
}

return json_encode($encode, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, 512);
}
}