Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
JhumanJ committed Apr 29, 2022
2 parents 96961ac + 14b64e7 commit 666d259
Show file tree
Hide file tree
Showing 24 changed files with 199 additions and 174 deletions.
21 changes: 16 additions & 5 deletions config/model-stats.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
|
*/

'enabled' => env('MODEL_STATS_ENABLED', true),
'allow_custom_code' => env('MODEL_STATS_CUSTOM_CODE', true),
'enabled' => env('MODEL_STATS_ENABLED', true),
'allow_custom_code' => env('MODEL_STATS_CUSTOM_CODE', true),

/*
|--------------------------------------------------------------------------
Expand All @@ -29,20 +29,31 @@
| the existing middleware. Or, you can simply stick with this list.
|
*/
'middleware' => [
'middleware' => [
'web',
\Jhumanj\LaravelModelStats\Http\Middleware\Authorize::class,
],

/*
|--------------------------------------------------------------------------
| ModelStats table name
|--------------------------------------------------------------------------
|
| As PostgreSQL table names seems to use dashes instead of underscore
| this configures the table name based on your connection.
|
*/
'table_name' => 'model_stats_dashboards',

/*
|--------------------------------------------------------------------------
| Route Prefixes
|--------------------------------------------------------------------------
|
| You can change the route where your dashboards are. By default routes will
| You can change the route where your dashboards are. By default, routes will
| be starting the '/stats' prefix, and names will start with 'stats.'.
|
*/
'routes_prefix' => 'stats',
'routes_prefix' => 'stats',
'route_names_prefix' => 'stats.',
];
20 changes: 20 additions & 0 deletions database/factories/DashboardFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Jhumanj\LaravelModelStats\Database\Factories;

use Jhumanj\LaravelModelStats\Models\Dashboard;
use Illuminate\Database\Eloquent\Factories\Factory;

class DashboardFactory extends Factory
{
protected $model = Dashboard::class;

public function definition(): array
{
return [
'name' => $this->faker->name,
'description' => $this->faker->sentence,
'body' => '{"widgets":[]}',
];
}
}
19 changes: 0 additions & 19 deletions database/factories/ModelFactory.php

This file was deleted.

19 changes: 12 additions & 7 deletions database/migrations/create_model-stats_table.php
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
<?php

use Illuminate\Support\Facades\Config;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up()
return new class extends Migration {

public function up(): void
{
Schema::create('model-stats-dashboards', function (Blueprint $table) {
Schema::create(Config::get('model-stats.table_name'), function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->jsonb('body')->default('{"widgets":[]}');
if (Config::get('database.defaults') === 'pgsql') {
$table->jsonb('body')->default('{"widgets":[]}');
} else {
$table->json('body');
}
$table->timestamps();
});
}

public function down()
public function down(): void
{
Schema::dropIfExists('model-stats-dashboards');
Schema::dropIfExists(Config::get('model-stats.table_name'));
}
};
20 changes: 11 additions & 9 deletions src/AuthorizesRequests.php
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
<?php


namespace Jhumanj\LaravelModelStats;

use Closure;
use Illuminate\Http\Request;

trait AuthorizesRequests
{
/**
* The callback that should be used to authenticate ModelStats users.
*
* @var \Closure
*/
public static $authUsing;
public static Closure $authUsing;

/**
* Register the ModelStats authentication callback.
*
* @param \Closure $callback
* @param \Closure $callback
*
* @return static
*/
public static function auth($callback)
public static function auth(Closure $callback): static
{
static::$authUsing = $callback;

Expand All @@ -28,13 +31,12 @@ public static function auth($callback)
/**
* Determine if the given request can access the ModelStats dashboard.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Request $request
*
* @return bool
*/
public static function check($request)
public static function check(Request $request): bool
{
return (static::$authUsing ?: function () {
return app()->environment('local');
})($request);
return (static::$authUsing ?: fn () => app()->environment('local'))($request);
}
}
4 changes: 2 additions & 2 deletions src/Console/InstallModelStatsPackage.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class InstallModelStatsPackage extends Command

protected $description = 'Install the ModelStatsPackage';

public function handle()
public function handle(): void
{
$this->info('Installing ModelStats package...');

Expand All @@ -35,7 +35,7 @@ public function handle()
*
* @return void
*/
private function registerModelStatsServiceProvider()
private function registerModelStatsServiceProvider(): void
{
$namespace = Str::replaceLast('\\', '', $this->laravel->getNamespace());

Expand Down
3 changes: 1 addition & 2 deletions src/Console/PublishCommand.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php


namespace Jhumanj\LaravelModelStats\Console;

use Illuminate\Console\Command;
Expand All @@ -11,7 +10,7 @@ class PublishCommand extends Command

protected $description = 'Publish all of the ModelStats resources';

public function handle()
public function handle(): void
{
$this->call('vendor:publish', [
'--tag' => 'model-stats-config',
Expand Down
6 changes: 3 additions & 3 deletions src/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
<?php


namespace Jhumanj\LaravelModelStats\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
use ValidatesRequests;
use AuthorizesRequests;

public function success($data = [])
public function success($data = []): JsonResponse
{
return response()->json(array_merge([
'type' => 'success',
], $data));
}

public function error($data = [], $statusCode = 400)
public function error($data = [], $statusCode = 400): JsonResponse
{
return response()->json(array_merge([
'type' => 'error',
Expand Down
52 changes: 23 additions & 29 deletions src/Http/Controllers/CustomCodeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
namespace Jhumanj\LaravelModelStats\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Jhumanj\LaravelModelStats\Http\Middleware\CustomCodeEnabled;
use Jhumanj\LaravelModelStats\Services\Tinker;

class CustomCodeController extends Controller
{
const CHART_TYPES = ['line_chart', 'bar_chart'];
public const CHART_TYPES = ['line_chart', 'bar_chart'];

public function __construct()
{
Expand All @@ -20,7 +21,7 @@ public function __construct()
/**
* Endpoint used to test customCode when creating widgets.
*/
public function executeCustomCode(Request $request, Tinker $tinker)
public function executeCustomCode(Request $request, Tinker $tinker): JsonResponse
{
$validated = $request->validate([
'code' => 'required',
Expand All @@ -35,10 +36,8 @@ public function executeCustomCode(Request $request, Tinker $tinker)
return $this->success([
'output' => $result,
'code_executed' => $codeExecuted,
'valid_output' => $codeExecuted ? $this->isValidOutput(
$request->chart_type,
$tinker->getCustomCodeResult()
) : false,
'valid_output' => $codeExecuted
&& $this->isValidOutput($request->get('chart_type'), $tinker->getCustomCodeResult()),
]);
}

Expand All @@ -51,8 +50,8 @@ public function widgetData(Request $request, Tinker $tinker)
'date_to' => 'required|date_format:Y-m-d|after:date_from',
]);

$dateFrom = Carbon::createFromFormat('Y-m-d', $request->date_from);
$dateTo = Carbon::createFromFormat('Y-m-d', $request->date_to);
$dateFrom = Carbon::createFromFormat('Y-m-d', $request->get('date_from'));
$dateTo = Carbon::createFromFormat('Y-m-d', $request->get('date_to'));

$result = $tinker->injectDates($dateFrom, $dateTo)
->readonly()
Expand All @@ -61,33 +60,28 @@ public function widgetData(Request $request, Tinker $tinker)
$codeExecuted = $tinker->lastExecSuccess();
$dataResult = $tinker->getCustomCodeResult();

if ($codeExecuted && $this->isValidOutput($request->chart_type, $dataResult)) {
if ($codeExecuted && $this->isValidOutput($request->get('chart_type'), $dataResult)) {
return $tinker->getCustomCodeResult();
} else {
return $this->error([
'output' => $result,
'code_executed' => $codeExecuted,
'valid_output' => $codeExecuted ? $this->isValidOutput(
$request->chart_type,
$tinker->getCustomCodeResult()
) : false,
]);
}

return $this->error([
'output' => $result,
'code_executed' => $codeExecuted,
'valid_output' => $codeExecuted
&& $this->isValidOutput($request->get('chart_type'), $tinker->getCustomCodeResult()),
]);
}

private function isValidOutput(string $chartType, $data)
private function isValidOutput(string $chartType, $data): bool
{
switch ($chartType) {
case 'bar_chart':
return $this->validateBarChartData($data);
case 'line_chart':
return $this->validateLineChartData($data);
}

return false;
return match ($chartType) {
'bar_chart' => $this->validateBarChartData($data),
'line_chart' => $this->validateLineChartData($data),
default => false,
};
}

private function validateBarChartData($data)
private function validateBarChartData($data): bool
{
if (! is_array($data)) {
return false;
Expand All @@ -101,7 +95,7 @@ private function validateBarChartData($data)
return true;
}

private function validateLineChartData($data)
private function validateLineChartData($data): bool
{
if (! is_array($data)) {
return false;
Expand Down
16 changes: 10 additions & 6 deletions src/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,39 @@

namespace Jhumanj\LaravelModelStats\Http\Controllers;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Jhumanj\LaravelModelStats\Http\Requests\Dashboard\StoreRequest;
use Jhumanj\LaravelModelStats\Http\Requests\Dashboard\UpdateRequest;
use Jhumanj\LaravelModelStats\Models\Dashboard;

class DashboardController extends Controller
{
public function index()
public function index(): Collection|array
{
return Dashboard::all();
}

public function show(Dashboard $dashboard)
public function show(Dashboard $dashboard): Dashboard
{
return $dashboard;
}

public function store(StoreRequest $request)
public function store(StoreRequest $request): Model|Builder
{
return Dashboard::create($request->validated());
return Dashboard::query()->create($request->validated());
}

public function update(Dashboard $dashboard, UpdateRequest $request)
public function update(Dashboard $dashboard, UpdateRequest $request): Dashboard
{
$dashboard->update($request->validated());

return $dashboard;
}

public function destroy(Dashboard $dashboard)
public function destroy(Dashboard $dashboard): JsonResponse
{
$dashboard->delete();

Expand Down
Loading

0 comments on commit 666d259

Please sign in to comment.