Skip to content

Debug logger #213

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

Merged
merged 4 commits into from
May 21, 2021
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions app/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Colors\Color;
use PhpSchool\PhpWorkshop\Listener\InitialCodeListener;
use PhpSchool\PhpWorkshop\Logger\ConsoleLogger;
use PhpSchool\PhpWorkshop\Logger\Logger;
use Psr\Log\LoggerInterface;
use function DI\create;
Expand Down Expand Up @@ -96,6 +97,10 @@
$appName = $c->get('appName');
$globalDir = $c->get('phpschoolGlobalDir');

if ($c->get('debugMode')) {
return new ConsoleLogger($c->get(OutputInterface::class), $c->get(Color::class));
}

return new Logger("$globalDir/logs/$appName.log");
},
ExerciseDispatcher::class => function (ContainerInterface $c) {
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"php-school/keylighter": "^0.8.4",
"nikic/php-parser": "^4.0",
"guzzlehttp/guzzle": "^7.2",
"psr/log": "^1.1"
"psr/log": "^1.1",
"ext-json": "*"
},
"require-dev": {
"composer/composer": "^2.0",
Expand Down
22 changes: 17 additions & 5 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,13 @@ public function setBgColour(string $colour): void
$this->bgColour = $colour;
}

public function configure(): ContainerInterface
public function configure(bool $debugMode = false): ContainerInterface
{
if ($this->container instanceof ContainerInterface) {
return $this->container;
}

$container = $this->getContainer();
$container = $this->getContainer($debugMode);

foreach ($this->exercises as $exercise) {
if (false === $container->has($exercise)) {
Expand Down Expand Up @@ -221,10 +221,20 @@ public function configure(): ContainerInterface
*/
public function run(): int
{
$container = $this->configure();
$args = $_SERVER['argv'] ?? [];

$debug = any($args, function (string $arg) {
return $arg === '--debug';
});

$args = array_values(array_filter($args, function (string $arg) {
return $arg !== '--debug';
}));

$container = $this->configure($debug);

try {
$exitCode = $container->get(CommandRouter::class)->route();
$exitCode = $container->get(CommandRouter::class)->route($args);
} catch (MissingArgumentException $e) {
$container
->get(OutputInterface::class)
Expand Down Expand Up @@ -261,9 +271,10 @@ public function run(): int
}

/**
* @param bool $debugMode
* @return Container
*/
private function getContainer(): Container
private function getContainer(bool $debugMode): Container
{
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions(
Expand All @@ -276,6 +287,7 @@ private function getContainer(): Container
$containerBuilder->addDefinitions(
[
'workshopTitle' => $this->workshopTitle,
'debugMode' => $debugMode,
'exercises' => $this->exercises,
'workshopLogo' => $this->logo,
'bgColour' => $this->bgColour,
Expand Down
1 change: 0 additions & 1 deletion src/CommandRouter.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ public function addCommand(CommandDefinition $c): void
*/
public function route(array $args = null): int
{

if (null === $args) {
$args = $_SERVER['argv'] ?? [];
}
Expand Down
2 changes: 0 additions & 2 deletions src/ExerciseRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,6 @@ public function __construct(
*/
public function __invoke(CliMenu $menu): void
{
$menu->close();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just wondering why 👀


$item = $menu->getSelectedItem();
$exercise = $this->exerciseRepository->findByName($item->getText());
$exercises = $this->exerciseRepository->findAll();
Expand Down
1 change: 1 addition & 0 deletions src/Factory/MenuFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public function __invoke(ContainerInterface $c): CliMenu
$builder->addItem(
$exercise->getName(),
function (CliMenu $menu) use ($exerciseRenderer, $eventDispatcher, $exercise) {
$menu->close();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it moved here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, read the pr description!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah jesus, my bad 😂 🤦

$this->dispatchExerciseSelectedEvent($eventDispatcher, $exercise);
$exerciseRenderer->__invoke($menu);
},
Expand Down
44 changes: 44 additions & 0 deletions src/Logger/ConsoleLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Logger;

use Colors\Color;
use PhpSchool\PhpWorkshop\Output\OutputInterface;
use Psr\Log\AbstractLogger;
use Psr\Log\LoggerInterface;

class ConsoleLogger extends AbstractLogger implements LoggerInterface
{
/**
* @var OutputInterface
*/
private $output;

/**
* @var Color
*/
private $color;

public function __construct(OutputInterface $output, Color $color)
{
$this->output = $output;
$this->color = $color;
}

public function log($level, $message, array $context = []): void
{
$parts = [
sprintf(
'%s - %s - %s',
$this->color->fg('yellow', (new \DateTime())->format('H:i:s')),
$this->color->bg('red', strtoupper($level)),
$this->color->fg('red', $message)
),
json_encode($context, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
];

$this->output->writeLine(implode("\n", $parts));
}
}
16 changes: 16 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,19 @@ function collect(array $array): Collection
return new Collection($array);
}
}


if (!function_exists('any')) {

/**
* @param array<mixed> $values
* @param callable $cb
* @return bool
*/
function any(array $values, callable $cb): bool
{
return array_reduce($values, function (bool $carry, $value) use ($cb) {
return $carry || $cb($value);
}, false);
}
}
17 changes: 14 additions & 3 deletions test/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
use PhpSchool\PhpWorkshopTest\Asset\MockEventDispatcher;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use PhpSchool\PhpWorkshop\Logger\ConsoleLogger;
use PhpSchool\PhpWorkshop\Logger\Logger;
use PHPUnit\Framework\TestCase;

class ApplicationTest extends BaseTest
{
Expand Down Expand Up @@ -53,7 +56,7 @@ public function testEventListenersFromLocalAndWorkshopConfigAreMerged(): void
$rp->setAccessible(true);
$rp->setValue($app, $frameworkFile);

$container = $rm->invoke($app);
$container = $rm->invoke($app, false);

$eventListeners = $container->get('eventListeners');

Expand Down Expand Up @@ -162,8 +165,16 @@ public function testConfigureReturnsSameContainerInstance(): void
self::assertSame($application->configure(), $application->configure());
}

public function tearDown(): void
public function testDebugFlagSwitchesLoggerToConsoleLogger(): void
{
parent::tearDown();
$configFile = $this->getTemporaryFile('config.php', '<?php return [];');
$application = new Application('My workshop', $configFile);
$container = $application->configure(true);

$container->set('phpschoolGlobalDir', $this->getTemporaryDirectory());
$container->set('appName', 'my-workshop');

$logger = $container->get(LoggerInterface::class);
self::assertInstanceOf(ConsoleLogger::class, $logger);
}
}
6 changes: 2 additions & 4 deletions test/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ abstract class BaseTest extends TestCase
public function getTemporaryDirectory(): string
{
if (!$this->tempDirectory) {
$tempDirectory = System::tempDir($this->getName());
mkdir($tempDirectory, 0777, true);

$this->tempDirectory = realpath($tempDirectory);
$this->tempDirectory = System::tempDir($this->getName());
mkdir($this->tempDirectory, 0777, true);
}

return $this->tempDirectory;
Expand Down
4 changes: 0 additions & 4 deletions test/ExerciseRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,6 @@ public function testExerciseRendererSetsCurrentExerciseAndRendersExercise(): voi
->method('getSelectedItem')
->willReturn($item);

$menu
->expects($this->once())
->method('close');

$exercise1 = $this->createMock(ExerciseInterface::class);
$exercise2 = $this->createMock(ExerciseInterface::class);
$exercises = [$exercise1, $exercise2];
Expand Down
82 changes: 81 additions & 1 deletion test/Factory/MenuFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace PhpSchool\PhpWorkshopTest\Factory;

use PhpSchool\CliMenu\MenuItem\SelectableItem;
use PhpSchool\PhpWorkshop\Event\EventInterface;
use Psr\Container\ContainerInterface;
use PhpSchool\CliMenu\CliMenu;
use PhpSchool\PhpWorkshop\Command\CreditsCommand;
Expand Down Expand Up @@ -68,6 +70,84 @@ public function testFactoryReturnsInstance(): void


$factory = new MenuFactory();
$this->assertInstanceOf(CliMenu::class, $factory($container));

$factory($container);
}

public function testSelectExercise(): void
{
$container = $this->createMock(ContainerInterface::class);
$userStateSerializer = $this->createMock(UserStateSerializer::class);
$userStateSerializer
->expects($this->once())
->method('deSerialize')
->willReturn(new UserState());

$exerciseRepository = $this->createMock(ExerciseRepository::class);
$exercise = $this->createMock(ExerciseInterface::class);
$exercise
->method('getName')
->willReturn('Exercise');
$exerciseRepository
->expects($this->once())
->method('findAll')
->willReturn([$exercise]);

$terminal = $this->createMock(Terminal::class);
$terminal
->method('getWidth')
->willReturn(70);

$eventDispatcher = $this->createMock(EventDispatcher::class);
$eventDispatcher
->expects(self::exactly(2))
->method('dispatch')
->withConsecutive(
[
self::callback(function ($event) {
return $event instanceof EventInterface && $event->getName() === 'exercise.selected';
})
],
[
self::callback(function ($event) {
return $event instanceof EventInterface && $event->getName() === 'exercise.selected.exercise';
})
]
);

$exerciseRenderer = $this->createMock(ExerciseRenderer::class);
$exerciseRenderer->expects(self::once())
->method('__invoke')
->with(self::isInstanceOf(CliMenu::class));

$services = [
UserStateSerializer::class => $userStateSerializer,
ExerciseRepository::class => $exerciseRepository,
ExerciseRenderer::class => $exerciseRenderer,
HelpCommand::class => $this->createMock(HelpCommand::class),
CreditsCommand::class => $this->createMock(CreditsCommand::class),
ResetProgress::class => $this->createMock(ResetProgress::class),
'workshopLogo' => 'LOGO',
'bgColour' => 'black',
'fgColour' => 'green',
'workshopTitle' => 'TITLE',
WorkshopType::class => WorkshopType::STANDARD(),
EventDispatcher::class => $eventDispatcher,
Terminal::class => $terminal
];

$container
->method('get')
->willReturnCallback(function ($name) use ($services) {
return $services[$name];
});


$factory = new MenuFactory();

$menu = $factory($container);

$firstExercise = $menu->getItemByIndex(6);
$menu->executeAsSelected($firstExercise);
}
}
11 changes: 11 additions & 0 deletions test/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,15 @@ public function camelCaseToKebabCaseProvider(): array
]
];
}

public function testAny(): void
{
self::assertEquals(true, any([1, 2, 3, 10, 11], function (int $num) {
return $num > 10;
}));

self::assertEquals(false, any([1, 2, 3, 10, 11], function (int $num) {
return $num > 11;
}));
}
}
37 changes: 37 additions & 0 deletions test/Logger/ConsoleLoggerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace PhpSchool\PhpWorkshopTest\Logger;

use PhpSchool\CliMenu\Util\StringUtil;
use PhpSchool\PhpWorkshop\Logger\ConsoleLogger;
use PhpSchool\PhpWorkshop\Utils\StringUtils;
use PhpSchool\PhpWorkshopTest\ContainerAwareTest;
use Psr\Log\LoggerInterface;

class ConsoleLoggerTest extends ContainerAwareTest
{
public function setUp(): void
{
parent::setUp();

$this->container->set('phpschoolGlobalDir', $this->getTemporaryDirectory());
$this->container->set('appName', 'my-workshop');
$this->container->set('debugMode', true);
}

public function testConsoleLoggerIsCreatedIfDebugModeEnable(): void
{
$this->assertInstanceOf(ConsoleLogger::class, $this->container->get(LoggerInterface::class));
}

public function testLoggerWithContext(): void
{
$logger = $this->container->get(LoggerInterface::class);
$logger->critical('Failed to copy file', ['exercise' => 'my-exercise']);

$out = StringUtil::stripAnsiEscapeSequence($this->getActualOutputForAssertion());

$match = '/\d{2}\:\d{2}\:\d{2} - CRITICAL - Failed to copy file\n{\n "exercise": "my-exercise"\n}/';
$this->assertMatchesRegularExpression($match, $out);
}
}
1 change: 1 addition & 0 deletions test/Logger/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function setUp(): void

$this->container->set('phpschoolGlobalDir', $this->getTemporaryDirectory());
$this->container->set('appName', 'my-workshop');
$this->container->set('debugMode', false);
}

public function testLoggerDoesNotCreateFileIfNoMessageIsLogged(): void
Expand Down