Skip to content

Commit

Permalink
add pint.json
Browse files Browse the repository at this point in the history
  • Loading branch information
gael-connan-cybex committed Mar 15, 2024
1 parent ce5ce7b commit b83d9f1
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 68 deletions.
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ services:
- '.:/var/www/html'
networks:
- internal
- shared
depends_on:
- mysql_testing
mysql_testing:
Expand All @@ -40,3 +41,5 @@ services:
networks:
internal:
internal: true
shared:
external: true
37 changes: 37 additions & 0 deletions pint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"preset": "laravel",
"rules": {
"blank_line_before_statement": {
"statements": [
"break",
"continue",
"do",
"exit",
"for",
"foreach",
"if",
"phpdoc",
"return",
"switch",
"throw",
"try",
"while",
"yield",
"yield_from"
]
},
"class_attributes_separation": {
"elements": {
"const": "none",
"property": "none"
}
},
"concat_space": {
"spacing": "one"
},
"no_superfluous_phpdoc_tags": true,
"not_operator_with_successor_space": false,
"phpdoc_separation": true,
"phpdoc_trim_consecutive_blank_line_separation": true
}
}
16 changes: 8 additions & 8 deletions src/Classes/MySqlSchemaStateProxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ public function load($path)
*/
protected function getCommandString(): string
{
$command = 'mysqldump '.$this->schemaState->connectionString().' ';
$command = 'mysqldump ' . $this->schemaState->connectionString() . ' ';

$conditionalParameters = [
'--set-gtid-purged=OFF' => ! $this->schemaState->connection->isMaria(),
'--no-create-db' => ! $this->protector->shouldCreateDb(),
'--skip-comments' => ! $this->protector->shouldDumpComments(),
'--skip-set-charset' => ! $this->protector->shouldDumpCharsets(),
'--no-data' => ! $this->protector->shouldDumpData(),
'--set-gtid-purged=OFF' => !$this->schemaState->connection->isMaria(),
'--no-create-db' => !$this->protector->shouldCreateDb(),
'--skip-comments' => !$this->protector->shouldDumpComments(),
'--skip-set-charset' => !$this->protector->shouldDumpCharsets(),
'--no-data' => !$this->protector->shouldDumpData(),
];

$parameters = [
Expand All @@ -61,11 +61,11 @@ protected function getCommandString(): string
'--tz-utc',
'--column-statistics=0',
'--result-file="${:LARAVEL_LOAD_PATH}"',
'--max-allowed-packet='.$this->protector->getMaxPacketLength(),
'--max-allowed-packet=' . $this->protector->getMaxPacketLength(),
...array_keys(array_filter($conditionalParameters)),
'"${:LARAVEL_LOAD_DATABASE}"',
];

return $command.implode(' ', $parameters);
return $command . implode(' ', $parameters);
}
}
2 changes: 1 addition & 1 deletion src/Commands/CreateToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function handle()
$user->tokens()->whereAbilities('["protector:import"]')->delete();
$userInformation = sprintf('%s: %s (%s)', $user->id, $user->name, $user->email);

if (! $user->protector_public_key && ! $publicKey) {
if (!$user->protector_public_key && !$publicKey) {
$this->error(
'The user doesn\'t have a protector public key and none was specified. Please provide a public key for the user.'
);
Expand Down
17 changes: 8 additions & 9 deletions src/Commands/ImportDump.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ class ImportDump extends Command
protected $description = 'Imports a local or remote database dump.';

protected const DOWNLOAD_REMOTE_DUMP = 'Download remote dump';

protected const IMPORT_EXISTING_LOCAL_DUMP = 'Import existing local dump';

protected ?Protector $protector = null;
Expand All @@ -67,13 +66,13 @@ public function handle(): int
$optionLatest = $this->option('latest');
$optionConnection = $this->option('connection');

if (App::environment('production') && ! $this->option('allow-production')) {
if (App::environment('production') && !$this->option('allow-production')) {
throw new InvalidEnvironmentException(
'Import is not allowed on production systems! Use --allow-production'
);
}

if ($optionForce && ! ($optionRemote || $optionFile || $optionDump || $optionLatest)) {
if ($optionForce && !($optionRemote || $optionFile || $optionDump || $optionLatest)) {
$this->error('Nothing to import.');

return self::FAILURE;
Expand All @@ -82,7 +81,7 @@ public function handle(): int
$this->protector->withConnectionName($optionConnection);

$shouldImportLocalDump = $optionFile || $optionDump || $optionLatest;
$shouldDownloadDump = $optionRemote || (! $shouldImportLocalDump && $this->userWantsRemoteDump());
$shouldDownloadDump = $optionRemote || (!$shouldImportLocalDump && $this->userWantsRemoteDump());

if ($shouldDownloadDump) {
$importFilePath = $this->getRemoteDump();
Expand All @@ -98,7 +97,7 @@ public function handle(): int
}

if (empty($localFilePath)) {
if (! $importFilePath) {
if (!$importFilePath) {
$this->error('Found no file to import.');

return self::FAILURE;
Expand All @@ -109,7 +108,7 @@ public function handle(): int

$this->importDump($localFilePath, $optionForce);

if (! $optionFile) {
if (!$optionFile) {
unlink($localFilePath);
}

Expand Down Expand Up @@ -200,7 +199,7 @@ public function getMetaDataForFiles(array $directoryFiles): Collection
foreach ($directoryFiles as $directoryFile) {
$metaData = $this->protector->getDumpMetaData($directoryFile);

if ($this->option('ignore-connection-filter') || (! is_array($metaData) || empty($metaData))) {
if ($this->option('ignore-connection-filter') || (!is_array($metaData) || empty($metaData))) {
$matchingFiles->push([
'path' => $directoryFile,
'file' => basename($directoryFile),
Expand Down Expand Up @@ -306,11 +305,11 @@ public function getConnectionFiles(?string $connectionName = null): Collection

$filesByConnection = $sortedFiles->groupBy('connection');

if ($connectionName && ! $filesByConnection->has($connectionName)) {
if ($connectionName && !$filesByConnection->has($connectionName)) {
throw new InvalidConnectionException();
}

if (! $connectionName) {
if (!$connectionName) {
$connectionName = $this->chooseConnectionName($filesByConnection->keys());
}

Expand Down
42 changes: 21 additions & 21 deletions src/Protector.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ public function importDump(string $sourceFilePath, array $options = []): void
$this->guardExecEnabled();

// Production environment is not allowed unless set in options.
if (App::environment('production') && ! Arr::get($options, 'allow-production')) {
if (App::environment('production') && !Arr::get($options, 'allow-production')) {
throw new InvalidEnvironmentException('Production environment is not allowed and option was not set.');
}

if (! $this->connectionConfig) {
if (!$this->connectionConfig) {
throw new InvalidConnectionException('Connection is not configured properly');
}

if (! file_exists($sourceFilePath)) {
if (!file_exists($sourceFilePath)) {
throw new FileNotFoundException($sourceFilePath);
}

Expand Down Expand Up @@ -145,7 +145,7 @@ public function createDestinationFilePath(string $fileName, ?string $subFolder =
*/
public function createDump(array $options = []): string
{
if (! $this->connectionConfig) {
if (!$this->connectionConfig) {
throw new InvalidConnectionException('Connection is not configured properly.');
}

Expand Down Expand Up @@ -183,7 +183,7 @@ public function getDumpMetaData(string $dumpFile): bool|array
$decodedData = json_decode($matches['data'], true);

// We store json-encoded arrays, if we do not get an array back, that means something went wrong.
if (! is_array($decodedData)) {
if (!is_array($decodedData)) {
return false;
}

Expand Down Expand Up @@ -216,13 +216,13 @@ public function getRemoteDump(): string
{
$disk = $this->getDisk();

if ($this->shouldEncrypt() && ! $this->getPrivateKey()) {
if ($this->shouldEncrypt() && !$this->getPrivateKey()) {
throw new InvalidConfigurationException(
'For using Laravel Sanctum a crypto keypair is required. There was none found in your .env file.'
);
}

if (! $serverUrl = $this->getServerUrl()) {
if (!$serverUrl = $this->getServerUrl()) {
throw new InvalidConfigurationException('Server url is not set or invalid.');
}

Expand All @@ -248,14 +248,14 @@ public function getRemoteDump(): string
}
}

if (! $response->ok()) {
if (!$response->ok()) {
$httpCode = $response->status();

throw match ($httpCode) {
401, 403 => new UnauthorizedHttpException('', $httpCode.' Unauthorized access'),
404 => new NotFoundHttpException('404 Not found: '.$serverUrl),
401, 403 => new UnauthorizedHttpException('', $httpCode . ' Unauthorized access'),
404 => new NotFoundHttpException('404 Not found: ' . $serverUrl),
500 => new FailedRemoteDatabaseFetchingException($response->header('message')),
default => new HttpException($httpCode, 'Status code '.$httpCode),
default => new HttpException($httpCode, 'Status code ' . $httpCode),
};
}

Expand Down Expand Up @@ -330,7 +330,7 @@ protected function generateDump(array $options = []): ?string

$schemaStateProxy->dump($connection, $tempFile);

if (! filesize($tempFile)) {
if (!filesize($tempFile)) {
unlink($tempFile);

$tempFile = null;
Expand Down Expand Up @@ -386,7 +386,7 @@ public function createFilename(): string
*/
public function getMetaData(bool $refresh = false): array
{
if (! $refresh && $this->metaDataCache) {
if (!$refresh && $this->metaDataCache) {
return $this->metaDataCache;
}

Expand Down Expand Up @@ -422,7 +422,7 @@ protected function tail(string $file, int $lines, int $buffer = 1024): array
// Open file-handle.
$fileHandle = $this->getDisk()->readStream($file);

if (! is_resource($fileHandle)) {
if (!is_resource($fileHandle)) {
throw new FileNotFoundException($file);
}

Expand All @@ -441,7 +441,7 @@ protected function tail(string $file, int $lines, int $buffer = 1024): array
fseek($fileHandle, -$seekLength, SEEK_CUR);

// Get the next content-chunk by using the according length.
$contents = ($chunk = fread($fileHandle, $seekLength)).$contents;
$contents = ($chunk = fread($fileHandle, $seekLength)) . $contents;

// Reset pointer to the position before reading the current chunk.
fseek($fileHandle, -mb_strlen($chunk, 'UTF-8'), SEEK_CUR);
Expand Down Expand Up @@ -491,7 +491,7 @@ public function generateFileDownloadResponse(
$shouldEncrypt = $this->shouldEncrypt();

// Only proceed when either Laravel Sanctum is turned off or the user's token is valid.
if (! $shouldEncrypt || $request->user()?->tokenCan('protector:import')) {
if (!$shouldEncrypt || $request->user()?->tokenCan('protector:import')) {
if ($this->withConnectionName($connectionName)) {
try {
$serverFilePath = $this->createDump();
Expand All @@ -506,7 +506,7 @@ public function generateFileDownloadResponse(
function () use ($publicKey, $serverFilePath, $chunkSize, $shouldEncrypt) {
$inputHandle = fopen($serverFilePath, 'rb');

while (! feof($inputHandle)) {
while (!feof($inputHandle)) {
$chunk = fread($inputHandle, $chunkSize);

// Encrypt the data when Laravel Sanctum is active.
Expand Down Expand Up @@ -672,7 +672,7 @@ public function createTempFilePath(string $diskFilePath): string

$stream = $this->getDisk()->readStream($diskFilePath);

if (! is_resource($stream)) {
if (!is_resource($stream)) {
fclose($handle);

throw new FileNotFoundException($diskFilePath);
Expand Down Expand Up @@ -711,7 +711,7 @@ protected function shouldEncrypt(): bool
*/
public function guardExecEnabled(): void
{
if (! function_exists('exec')) {
if (!function_exists('exec')) {
throw new ShellAccessDeniedException();
}
}
Expand Down Expand Up @@ -749,7 +749,7 @@ protected function writeDumpFile(
$outputHandle = fopen($this->getDisk()->path($destinationFilePath), 'wb');

// Stop when EOF is reached or an empty chunk was read.
while (! feof($resource) && $chunk = stream_get_contents($resource, $chunkSize)) {
while (!feof($resource) && $chunk = stream_get_contents($resource, $chunkSize)) {
if ($sanctumEnabled) {
$chunk = $this->decryptString($chunk);
}
Expand Down Expand Up @@ -777,7 +777,7 @@ protected function getProxyForSchemaState($schemaState): SchemaState
MySqlSchemaState::class => app(MySqlSchemaStateProxy::class, [$schemaState, $this]),
// PostgresSchemaState::class => app('PostgresSchemaStateProxy', [$schemaState, $this]),
// SqliteSchemaState::class => app('SqliteSchemaStateProxy', [$schemaState, $this]),
default => throw new UnsupportedDatabaseException('Unsupported database schema state: '.class_basename($schemaState)),
default => throw new UnsupportedDatabaseException('Unsupported database schema state: ' . class_basename($schemaState)),
};
}
}
4 changes: 2 additions & 2 deletions src/ProtectorServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function boot(): void

// Publish package config to app config space.
$this->publishes([
__DIR__.'/../config/protector.php' => config_path('protector.php'),
__DIR__ . '/../config/protector.php' => config_path('protector.php'),
], 'protector.config');

$this->publishMigrations();
Expand All @@ -39,7 +39,7 @@ public function boot(): void
public function register(): void
{
// Automatically apply the package configuration.
$this->mergeConfigFrom(__DIR__.'/../config/protector.php', 'protector');
$this->mergeConfigFrom(__DIR__ . '/../config/protector.php', 'protector');

// Register the main class to use with the facade.
$this->app->singleton('protector', function () {
Expand Down
2 changes: 1 addition & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ protected function getFakeDumpDisk(): Filesystem
$disk = $this->getDumpDisk();
$baseDirectory = $this->protector->getBaseDirectory();

foreach (glob(getcwd().'/tests/dumps/*.sql') as $filename) {
foreach (glob(getcwd() . '/tests/dumps/*.sql') as $filename) {
Storage::disk('local')->putFileAs($baseDirectory, $filename, basename($filename));
}

Expand Down
3 changes: 0 additions & 3 deletions tests/feature/ExportDumpTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@
class ExportDumpTest extends TestCase
{
protected Filesystem $disk;

protected string $baseDirectory;

protected string $filePath;

protected string $emptyDumpPath;

protected function setUp(): void
Expand Down
Loading

0 comments on commit b83d9f1

Please sign in to comment.