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

Feature: Basic gains view #60

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion .github/workflows/github-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ name: Deploy static content to Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ['main', 'feature/**']
branches: ['main']

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ yarn-error.log

# Apache Jmeter
jmeter.log

# K6
k6
9 changes: 9 additions & 0 deletions app/Http/Controllers/Api/ApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

class ApiController extends Controller
{
}
42 changes: 42 additions & 0 deletions app/Http/Controllers/Api/GainsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Http\Controllers\Api;

use App\Services\GainsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class GainsController extends ApiController
{
protected ?string $challenge = null;

protected ?string $method = null;

// TODO: Move to custom Request
public function __construct(
protected Request $request,
protected GainsService $gainsService
) {
$parts = collect(explode('/', $this->request->path()))
->skip(2);

if ($parts->isNotEmpty()) {
$this->challenge = $parts->shift();
}

if ($parts->isNotEmpty()) {
$this->method = $parts->shift();
}
}

public function index(): JsonResponse
{
return response()->json([
'success' => true,
'data' => $this->gainsService->getGains(
$this->challenge,
$this->method
),
]);
}
}
64 changes: 64 additions & 0 deletions app/Http/Controllers/Api/KataController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace App\Http\Controllers\Api;

use App\Services\KataService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class KataController extends ApiController
{
protected ?string $challenge = null;

protected ?string $method = null;

// TODO: Move to custom Request
public function __construct(
protected Request $request,
protected KataService $kataService
) {
$parts = collect(explode('/', $this->request->path()))
->skip(2);

if ($parts->isNotEmpty()) {
$this->challenge = $parts->shift();
}

if ($parts->isNotEmpty()) {
$this->method = $parts->shift();
}
}

public function index(): JsonResponse
{
// Run the method
if (! is_null($this->method) && ! is_null($this->challenge)) {
return response()->json([
'success' => true,
'data' => $this->kataService->runChallengeMethod(
$this->request,
$this->challenge,
$this->method
),
]);
}

$challenges = $this->kataService->getChallenges();

if (! is_null($this->challenge)) {
$challenges = $challenges->filter(fn (string $challenge) => $challenge === $this->challenge);
}

$challenges = $challenges->map(fn (string $challenge) => [
'challenge' => $challenge,
'methods' => $this->kataService->getChallengeMethods($challenge)
->filter(fn (string $method) => is_null($this->method) || $method === $this->method)
->values(),
])->values();

return response()->json([
'success' => true,
'data' => $challenges,
]);
}
}
14 changes: 8 additions & 6 deletions app/Kata/KataRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,18 +273,20 @@ protected function getReportData(

if (config('laravel-kata.save-outputs')) {
$filePath = sprintf(
'laravel-kata/%s/result-%s.json',
$this->createdAt->format('Ymd-His'),
Str::slug(implode(' ', [$className, $methodName])),
'public/gains/%s-%s.json',
$className,
$methodName
);

Storage::disk('local')->put($filePath, json_encode($result));
$this->command?->warn(sprintf('Saved output to %s', $filePath));
$this->command?->info(sprintf('Saved output to %s', $filePath));
}

if (config('laravel-kata.debug-mode')) {
$this->addExitHintsFromViolations($statsBaseline['violations']);
$this->addExitHintsFromViolations($statsBefore['violations']);
$this->addExitHintsFromViolations(array_merge(
$statsBaseline['violations'],
$statsBefore['violations']
));
}

$this->addExitHintsFromViolations($statsRecord['violations']);
Expand Down
82 changes: 82 additions & 0 deletions app/Services/GainsService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace App\Services;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use JsonException;

class GainsService
{
public function __construct(
protected KataService $kataService
) {
}

public function getGains(
?string $challenge,
?string $method
): Collection {
$gains = collect();

/** @var string $challengeName */
foreach ($this->kataService->getChallenges() as $challengeName) {
if (! is_null($challenge) && $challengeName !== $challenge) {
continue;
}

/** @var string $methodName */
foreach ($this->kataService->getChallengeMethods($challengeName) as $methodName) {
if (! is_null($method) && $methodName !== $method) {
continue;
}

$gains->push($this->getChallengeMethodGains($challengeName, $methodName));
}
}

return $gains;
}

public function getChallengeMethodGains(
string $challenge,
string $method
): array {
$errors = [];
$suggestions = [];
$path = sprintf(
'gains/%s-%s.json',
$challenge,
$method
);
$gains = Storage::disk('public')->get($path);

if (is_null($gains)) {
$errors[] = sprintf(
'Gains file not found (%s)',
asset(sprintf('storage/%s', $path)),
);
$suggestions[] = 'Run the following command `npm run benchmark:kata`';
}

if (! is_null($gains)) {
try {
$gains = json_decode($gains, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
$errors[] = sprintf(
'Unable to decode file. %s (%s)',
$exception->getMessage(),
asset(sprintf('storage/%s', $path)),
);
$suggestions[] = 'Run the following command `npm run benchmark:kata`';
}
}

return [
'success' => empty($errors),
'gains' => $gains,
'errors' => $errors,
'suggestions' => $suggestions,
];
}
}
74 changes: 74 additions & 0 deletions app/Services/KataService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace App\Services;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;

class KataService
{
public function getChallenges(): Collection
{
return collect(config('laravel-kata.challenges', []))
->map(function ($className) {
$classNameParts = explode('\\', $className);

return array_pop($classNameParts);
});
}

public function getChallengeMethods(string $challenge): Collection
{
$class = sprintf(
'App\\Kata\\Challenges\\%s',
$challenge
);

try {
$reflectionClass = new ReflectionClass($class);
} catch (ReflectionException $exception) {
throw new Exception(sprintf(
'Something bad happened: %s',
$exception->getMessage()
));
}

return collect($reflectionClass->getMethods())
->filter(fn (ReflectionMethod $method) => $method->class === $class)
->filter(fn (ReflectionMethod $method) => $method->isPublic())
->filter(fn (ReflectionMethod $method) => $method->name !== 'baseline')
->map(fn ($method) => $method->name)
->values();
}

public function runChallengeMethod(Request $request, string $challenge, string $method): array
{
$className = sprintf(
'App\\Kata\\Challenges\\%s',
$challenge
);

$instance = app($className, [
'request' => $request,
]);

$outputs = collect();
$iterations = $request->get('iterations', 1);
foreach (range(1, $iterations) as $iteration) {
$output = $instance->{$method}($iteration);
$outputs->push(json_encode($output));
}

$json = $outputs->toJson();

return [
'outputs_md5' => md5($json),
'outputs_last_10' => $outputs->take(-10),
'outputs' => $json,
];
}
}
4 changes: 3 additions & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ let site = null;

// https://astro.build/config
let config = {
output: 'server',
base: '/laravel-kata',
srcDir: './client/src',
publicDir: './client/public',
outDir: './client/dist',
routes: './src/pages',
integrations: [
vue(),
svelte()
]
],
};

if (process.env.CI_MODE === 'local') {
Expand Down
Loading