Skip to content

Commit

Permalink
refactor: further improve instance and installation robustness
Browse files Browse the repository at this point in the history
  • Loading branch information
EdieLemoine committed Oct 23, 2023
1 parent 2d36193 commit b396e48
Showing 1 changed file with 33 additions and 21 deletions.
54 changes: 33 additions & 21 deletions myparcelnl.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,13 @@ public function __construct()

parent::__construct();

try {
$this->setup();
} catch (Throwable $e) {
$this->_errors[] = sprintf(
"Failed to instantiate %s: %s\nStack: %s",
$this->displayName,
$e->getMessage(),
$e->getTraceAsString()
);
$this->hasPdk = false;
}
$this->withErrorHandling(
[$this, 'setup'],
sprintf('Failed to instantiate %s', $this->displayName),
function () {
$this->hasPdk = false;
}
);
}

/**
Expand All @@ -83,6 +79,10 @@ public function __construct()
*/
public function disable($forceAll = false): bool
{
if (! $this->hasPdk) {
return parent::disable($forceAll);
}

return $this->withErrorHandling(function () { Installer::uninstall($this); }) && parent::disable($forceAll);
}

Expand Down Expand Up @@ -185,24 +185,36 @@ private function setup(): void
}

/**
* @param callable $callback
* @param null|string $message
* @param callable $callback
* @param null|string $message
* @param null|callable $failureCallback
*
* @return bool
*/
private function withErrorHandling(callable $callback, ?string $message = null): bool
{
if (! $this->hasPdk) {
return false;
}

private function withErrorHandling(
callable $callback,
?string $message = null,
?callable $failureCallback = null
): bool {
try {
$callback();

return true;
} catch (Throwable $e) {
Logger::error("An error occurred: {$e->getMessage()}", ['exception' => $e->getTraceAsString()]);
$this->_errors[] = $message ?? $e->getMessage();
if ($this->hasPdk) {
Logger::error("An error occurred: {$e->getMessage()}", ['exception' => $e->getTraceAsString()]);
}

$this->_errors[] = sprintf(
'<hr>%s: %s<br><br><b>Stack trace:</b><br><code>%s</code>',
$message ?? 'Error',
$e->getMessage(),
$e->getTraceAsString()
);

if ($failureCallback) {
$failureCallback();
}

return false;
}
Expand Down

0 comments on commit b396e48

Please sign in to comment.