Skip to content

Commit

Permalink
Config and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
bencroker committed Jan 4, 2025
1 parent cda06ec commit 3413da6
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 60 deletions.
2 changes: 1 addition & 1 deletion config/datastar.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* The event options to override the Datastar defaults. Null values will be ignored.
*/
'defaultEventOptions' => [
'retryDuration' => null,
'retryDuration' => 123,
],

/**
Expand Down
1 change: 1 addition & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ parameters:
level: 5
paths:
- src
- config
44 changes: 29 additions & 15 deletions src/DatastarServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,63 +9,77 @@
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Putyourlightson\Datastar\Globals\DatastarGlobal;
use Putyourlightson\Datastar\Http\Controllers\DatastarController;
use Putyourlightson\Datastar\Services\SseService;
use Putyourlightson\Datastar\Variables\DatastarVariable;

class DatastarServiceProvider extends ServiceProvider
{
/**
* @inheritdoc
*/
public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/../config/datastar.php', 'datastar');

$this->app->singleton(SseService::class, function() {
return new SseService();
});
}

/**
* Bootstrap services.
*/
public function boot(): void
{
$this->registerRoutes();
$this->registerVariables();
$this->registerDirectives();
}

protected function registerRoutes(): void
{
Route::match(
['get', 'post', 'put', 'patch', 'delete'],
'/datastar-controller',
[DatastarController::class, 'index'],
);
}

protected function registerVariables(): void
{
View::composer('*', function(\Illuminate\View\View $view) {
$view->with('datastar', new DatastarGlobal(app(SseService::class)));
$view->with('datastar', new DatastarVariable(app(SseService::class)));
});
}

protected function registerDirectives(): void
{
Blade::directive('mergefragments', function(string $expression) {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->setSseInProcess('mergeFragments', $expression); ob_start(); ?>";
return $this->getDirective("setSseInProcess('mergeFragments', $expression); ob_start()");
});

Blade::directive('endmergefragments', function() {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->mergeFragments(ob_get_clean()); ?>";
return $this->getDirective("mergeFragments(ob_get_clean())");
});

Blade::directive('removefragments', function(string $expression) {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->removeFragments($expression); ?>";
return $this->getDirective("removeFragments($expression)");
});

Blade::directive('mergesignals', function(string $expression) {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->mergeSignals($expression); ?>";
return $this->getDirective("mergeSignals($expression)");
});

Blade::directive('removesignals', function(string $expression) {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->removeSignals($expression); ?>";
return $this->getDirective("removeSignals($expression)");
});

Blade::directive('executescript', function(string $expression) {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->setSseInProcess('executeScript', $expression); ob_start(); ?>";
return $this->getDirective("setSseInProcess('executeScript', $expression); ob_start()");
});

Blade::directive('endexecutescript', function() {
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->executeScript(ob_get_clean()); ?>";
return $this->getDirective("executeScript(ob_get_clean())");
});
}

protected function getDirective(string $expression): string
{
return "<?php app(\Putyourlightson\Datastar\Services\SseService::class)->$expression ?>";
}
}
12 changes: 5 additions & 7 deletions src/Http/Controllers/DatastarController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@

class DatastarController extends Controller
{
protected SseService $sse;

public function __construct(SseService $sse)
{
$this->sse = $sse;
public function __construct(
protected SseService $sse,
) {
}

public function index(Request $request): StreamedResponse
Expand All @@ -27,8 +25,8 @@ public function index(Request $request): StreamedResponse

if (strtolower($request->header('Content-Type')) === 'application/json') {
// Clear out params to prevent them from being processed by controller actions.
// $request->setQueryParams([]);
// $request->setBodyParams([]);
$request->query->replace();
$request->request->replace();
}

// Set the response headers for the event stream.
Expand Down
9 changes: 4 additions & 5 deletions src/Models/ConfigModel.php → src/Models/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class ConfigModel
class Config
{
protected const HASH_LENGTH = 64;
protected const HASH_ALGORITHM = 'sha256';
protected const HASH_LENGTH = 64;

public string $view = '';
public array $variables = [];
public bool $includeCsrfToken = false;
public ?string $csrfToken = null;

/**
* Creates a new instance from an encrypted config string.
* Creates a new instance from a hashed config string.
*/
public static function fromHashed(string $config): ?self
{
Expand Down Expand Up @@ -102,8 +102,7 @@ public function validate(): void
*/
protected function validateVariables(string $attribute, mixed $variables, Closure $fail): void
{
// $signalsVariableName = Datastar::getInstance()->settings->signalsVariableName;
$signalsVariableName = 'signals';
$signalsVariableName = config('datastar.signalsVariableName');

foreach ($variables as $key => $value) {
if ($key === $signalsVariableName) {
Expand Down
17 changes: 8 additions & 9 deletions src/Models/SignalsModel.php → src/Models/Signals.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@

use Putyourlightson\Datastar\Services\SseService;

class SignalsModel
class Signals
{
private array $values;

public function __construct(array $values)
{
$this->values = $values;
public function __construct(
protected array $values,
protected SseService $sse,
) {
}

public function __get(string $name)
Expand Down Expand Up @@ -56,7 +55,7 @@ public function set(string $name, mixed $value): static
{
$this->setNestedValue($name, $value);

app(SseService::class)->mergeSignals($this->getNestedArrayValue($name, $value));
$this->sse->mergeSignals($this->getNestedArrayValue($name, $value));

return $this;
}
Expand All @@ -70,7 +69,7 @@ public function setValues(array $values): static
$this->values[$name] = $value;
}

app(SseService::class)->mergeSignals($values);
$this->sse->mergeSignals($values);

return $this;
}
Expand All @@ -82,7 +81,7 @@ public function remove(string $name): static
{
$this->removeNestedValue($name);

app(SseService::class)->removeSignals([$name]);
$this->sse->removeSignals([$name]);

return $this;
}
Expand Down
28 changes: 12 additions & 16 deletions src/Services/SseService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

use Illuminate\Validation\ValidationException;
use Putyourlightson\Datastar\Http\Controllers\DatastarController;
use Putyourlightson\Datastar\Models\ConfigModel;
use Putyourlightson\Datastar\Models\SignalsModel;
use Putyourlightson\Datastar\Models\Config;
use Putyourlightson\Datastar\Models\Signals;
use starfederation\datastar\ServerSentEventGenerator;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Throwable;
Expand Down Expand Up @@ -52,7 +52,7 @@ public function getAction(string $method, string $view, array $variables, array

public function getUrl(string $method, string $view, array $variables = []): string
{
$config = new ConfigModel([
$config = new Config([
'view' => $view,
'variables' => $variables,
'includeCsrfToken' => $method !== 'get',
Expand All @@ -72,13 +72,11 @@ public function getUrl(string $method, string $view, array $variables = []): str

/**
* Merges HTML fragments into the DOM.
*
* @used-by FragmentNode
*/
public function mergeFragments(string $data, array $options = []): void
{
$options = $this->mergeEventOptions(
config('datastar.defaultFragmentOptions') ?? [],
config('datastar.defaultFragmentOptions', []),
$options,
);

Expand All @@ -91,7 +89,7 @@ public function mergeFragments(string $data, array $options = []): void
public function removeFragments(string $selector, array $options = []): void
{
$options = $this->mergeEventOptions(
config('datastar.defaultFragmentOptions') ?? [],
config('datastar.defaultFragmentOptions', []),
$options,
);

Expand All @@ -104,7 +102,7 @@ public function removeFragments(string $selector, array $options = []): void
public function mergeSignals(array $signals, array $options = []): void
{
$options = $this->mergeEventOptions(
config('datastar.defaultSignalOptions') ?? [],
config('datastar.defaultSignalOptions', []),
$options,
);

Expand All @@ -121,13 +119,11 @@ public function removeSignals(array $paths, array $options = []): void

/**
* Executes JavaScript in the browser.
*
* @used-by ExecuteScriptNode
*/
public function executeScript(string $script, array $options = []): void
{
$options = $this->mergeEventOptions(
config('datastar.defaultExecuteScriptOptions') ?? [],
config('datastar.defaultExecuteScriptOptions', []),
$options,
);

Expand All @@ -148,15 +144,14 @@ public function setSseInProcess(string $method, array $options = []): void
*/
public function stream(string $config, array $signals): void
{
$config = ConfigModel::fromHashed($config);
$config = Config::fromHashed($config);
if ($config === null) {
$this->throwException('Submitted data was tampered.');
}

$signals = new SignalsModel($signals);
$signals = new Signals($signals, $this);
$variables = array_merge(
//[Datastar::getInstance()->settings->signalsVariableName => $signals],
['signals' => $signals],
[config('datastar.signalsVariableName', 'signals') => $signals],
$config->variables,
);

Expand All @@ -168,7 +163,8 @@ public function stream(string $config, array $signals): void
*/
private function mergeEventOptions(array ...$optionSets): array
{
$options = array_merge([], //Datastar::getInstance()->settings->defaultEventOptions;
$options = array_merge(
config('datastar.defaultEventOptions', []),
$this->sseOptionsInProcess,
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,52 @@
* @copyright Copyright (c) PutYourLightsOn
*/

namespace Putyourlightson\Datastar\Globals;
namespace Putyourlightson\Datastar\Variables;

use Putyourlightson\Datastar\Services\SseService;

class DatastarGlobal
class DatastarVariable
{
private SseService $sse;

public function __construct(SseService $sse)
{
$this->sse = $sse;
public function __construct(
protected SseService $sse,
) {
}

/**
* Returns a Datastar `@get` action.
*/
public function get(string $view, array $variables = [], array $options = []): string
{
return $this->sse->getAction('get', $view, $variables, $options);
}

/**
* Returns a Datastar `@post` action.
*/
public function post(string $view, array $variables = [], array $options = []): string
{
return $this->sse->getAction('post', $view, $variables, $options);
}

/**
* Returns a Datastar `@put` action.
*/
public function put(string $view, array $variables = [], array $options = []): string
{
return $this->sse->getAction('put', $view, $variables, $options);
}

/**
* Returns a Datastar `@patch` action.
*/
public function patch(string $view, array $variables = [], array $options = []): string
{
return $this->sse->getAction('patch', $view, $variables, $options);
}

/**
* Returns a Datastar `@delete` action.
*/
public function delete(string $view, array $variables = [], array $options = []): string
{
return $this->sse->getAction('delete', $view, $variables, $options);
Expand Down

0 comments on commit 3413da6

Please sign in to comment.