From b01afa2fe49bbd2f8da953bc9e598934fdf146a9 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Thu, 6 Jun 2024 18:35:13 -0300 Subject: [PATCH 01/10] Changes --- .github/workflows/code_analysis.yml | 40 ---- .github/workflows/run_tests.yml | 4 + .php-cs-fixer.php | 165 ----------------- pint.json | 175 ++++++++++++++++++ src/Commands/BatchProcess.php | 21 ++- src/GraphQL/Mutations/AddTokensMutation.php | 6 +- src/GraphQL/Mutations/ClaimBeamMutation.php | 2 +- src/GraphQL/Mutations/CreateBeamMutation.php | 8 +- src/GraphQL/Mutations/UpdateBeamMutation.php | 6 +- src/GraphQL/Types/BeamClaimType.php | 2 +- src/GraphQL/Types/BeamType.php | 4 +- .../Types/Input/IntegerRangeStringType.php | 8 +- src/Jobs/ClaimBeam.php | 4 +- src/Jobs/DispatchCreateBeamClaimsJobs.php | 4 +- src/Listeners/UpdateClaimStatus.php | 2 +- src/Models/Laravel/Beam.php | 6 +- src/Models/Laravel/BeamClaim.php | 2 +- src/Models/Laravel/BeamScan.php | 8 +- .../Laravel/Traits/EagerLoadSelectFields.php | 9 +- src/Rules/CanClaim.php | 10 +- src/Rules/HasBeamFlag.php | 8 +- src/Rules/IsEndDateValid.php | 6 +- src/Rules/IsStartDateValid.php | 6 +- src/Rules/MaxBigIntIntegerRange.php | 2 +- src/Rules/MaxTokenCount.php | 12 +- src/Rules/MaxTokenSupply.php | 19 +- src/Rules/MinBigIntIntegerRange.php | 2 +- src/Rules/NotExpired.php | 8 +- src/Rules/NotOwner.php | 6 +- src/Rules/NotPaused.php | 6 +- src/Rules/PassesClaimCondition.php | 8 +- src/Rules/PassesClaimConditions.php | 8 +- src/Rules/ScanLimit.php | 8 +- src/Rules/SingleUseCodeExist.php | 6 +- src/Rules/SingleUseCodesExist.php | 6 +- src/Rules/TokenUploadExistInCollection.php | 13 +- src/Rules/TokenUploadNotExistInBeam.php | 14 +- src/Rules/TokenUploadNotExistInCollection.php | 12 +- src/Rules/TokensDoNotExistInBeam.php | 12 +- src/Rules/TokensDoNotExistInCollection.php | 10 +- src/Rules/TokensExistInBeam.php | 12 +- src/Rules/TokensExistInCollection.php | 10 +- src/Rules/Traits/IntegerRange.php | 6 +- src/Rules/UniqueTokenIds.php | 8 +- src/Rules/VerifySignedMessage.php | 12 +- src/Services/BatchService.php | 4 +- src/Services/BeamService.php | 22 +-- src/Support/ClaimProbabilities.php | 2 +- tests/Feature/Commands/BatchProcessTest.php | 13 +- tests/Feature/Commands/PruneTest.php | 18 +- .../GraphQL/Mutations/AddTokensTest.php | 2 +- .../GraphQL/Mutations/ClaimBeamTest.php | 14 +- .../GraphQL/Mutations/CreateBeamTest.php | 6 +- .../Mutations/ExpireSingleUseCodesTest.php | 2 +- .../GraphQL/Mutations/UpdateBeamTest.php | 4 +- tests/Feature/GraphQL/Queries/GetBeamTest.php | 4 +- tests/Feature/GraphQL/TestCaseGraphQL.php | 14 +- tests/Feature/Traits/CreateBeamData.php | 2 +- tests/Feature/Traits/CreateCollectionData.php | 4 - tests/Feature/Traits/SeedBeamData.php | 4 +- tests/TestCase.php | 3 +- tests/Unit/EventTest.php | 53 +++++- 62 files changed, 395 insertions(+), 482 deletions(-) delete mode 100644 .github/workflows/code_analysis.yml delete mode 100644 .php-cs-fixer.php create mode 100644 pint.json diff --git a/.github/workflows/code_analysis.yml b/.github/workflows/code_analysis.yml deleted file mode 100644 index 7ac80a0..0000000 --- a/.github/workflows/code_analysis.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Code Analysis and Linting - -on: - pull_request: - paths-ignore: - - "**.md" - push: - paths-ignore: - - "**.md" - -jobs: - tests: - runs-on: ubuntu-latest - name: Code Analysis - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 8.1 - tools: composer:v2 - coverage: none - - - name: Checkout friendsofphp php-cs-fixer code - uses: actions/checkout@v4 - with: - repository: "friendsofphp/php-cs-fixer" - ref: "v3.13.1" - path: ".php-cs-fixer" - - - name: Install dependencies - run: | - cd .php-cs-fixer/ - composer install - cd .. - - name: Run - run: ./.php-cs-fixer/php-cs-fixer fix --dry-run --diff --show-progress=none --verbose diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index 7993a34..45ec05d 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -64,6 +64,10 @@ jobs: composer build-sr25519 composer dumpautoload + - name: Run Laravel Pint + run: | + ./vendor/bin/pint --test + - name: Execute tests run: | php -d pcov.enabled=1 ./vendor/bin/phpunit --colors=always --coverage-clover coverage.xml diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php deleted file mode 100644 index b9cd09f..0000000 --- a/.php-cs-fixer.php +++ /dev/null @@ -1,165 +0,0 @@ -notPath('vendor') - ->notPath('build') - ->in(__DIR__) - ->name('*.php') - ->ignoreDotFiles(true) - ->ignoreVCS(true); - -return (new PhpCsFixer\Config()) - ->setFinder($finder) - ->setRiskyAllowed(true) - ->setLineEnding("\n") - ->setRules([ - '@PSR1' => true, - '@PSR2' => true, - '@PSR12' => true, - 'align_multiline_comment' => true, - 'array_indentation' => true, - 'backtick_to_shell_exec' => true, - 'blank_line_after_opening_tag' => true, - 'blank_line_before_statement' => true, - 'cast_spaces' => true, - 'combine_consecutive_issets' => true, - 'combine_consecutive_unsets' => true, - 'combine_nested_dirname' => true, - 'comment_to_phpdoc' => true, - 'compact_nullable_typehint' => true, - 'declare_equal_normalize' => true, - 'dir_constant' => true, - 'explicit_indirect_variable' => true, - 'explicit_string_variable' => true, - 'fully_qualified_strict_types' => true, - 'function_to_constant' => true, - 'function_typehint_space' => true, - 'single_line_comment_style' => [ - 'comment_types' => ['hash'], - ], - 'heredoc_to_nowdoc' => true, - 'implode_call' => true, - 'include' => true, - 'linebreak_after_opening_tag' => true, - 'list_syntax' => ['syntax' => 'short'], - 'logical_operators' => true, - 'lowercase_cast' => true, - 'constant_case' => ['case' => 'lower'], - 'lowercase_static_reference' => true, - 'magic_constant_casing' => true, - 'magic_method_casing' => true, - 'method_chaining_indentation' => true, - 'modernize_types_casting' => true, - 'multiline_comment_opening_closing' => true, - 'multiline_whitespace_before_semicolons' => true, - 'native_function_casing' => true, - 'no_alias_functions' => true, - 'no_alternative_syntax' => true, - 'no_binary_string' => true, - 'no_blank_lines_after_phpdoc' => true, - 'no_empty_phpdoc' => true, - 'no_empty_statement' => true, - 'no_leading_import_slash' => true, - 'no_leading_namespace_whitespace' => true, - 'no_mixed_echo_print' => true, - 'no_multiline_whitespace_around_double_arrow' => true, - 'no_null_property_initialization' => true, - 'no_php4_constructor' => true, - 'no_short_bool_cast' => true, - 'echo_tag_syntax' => ['format' => 'long'], - 'no_singleline_whitespace_before_semicolons' => true, - 'no_spaces_around_offset' => true, - 'no_trailing_comma_in_list_call' => true, - 'no_trailing_comma_in_singleline_array' => true, - 'no_unneeded_control_parentheses' => true, - 'no_unneeded_curly_braces' => true, - 'no_unneeded_final_method' => true, - 'no_unreachable_default_argument_value' => true, - 'no_unused_imports' => true, - 'no_useless_else' => true, - 'no_useless_return' => true, - 'no_whitespace_before_comma_in_array' => true, - 'no_whitespace_in_blank_line' => true, - 'non_printable_character' => true, - 'normalize_index_brace' => true, - 'object_operator_without_whitespace' => true, - 'ordered_class_elements' => true, - 'ordered_imports' => true, - 'ordered_interfaces' => true, - 'php_unit_construct' => true, - 'php_unit_dedicate_assert' => true, - 'php_unit_dedicate_assert_internal_type' => true, - 'php_unit_expectation' => true, - 'php_unit_method_casing' => ['case' => 'snake_case'], - 'phpdoc_indent' => true, - 'phpdoc_no_access' => true, - 'phpdoc_no_alias_tag' => true, - 'phpdoc_no_package' => true, - 'phpdoc_order' => true, - 'phpdoc_scalar' => true, - 'phpdoc_trim' => true, - 'phpdoc_types' => true, - 'phpdoc_var_without_name' => true, - 'phpdoc_summary' => true, - 'phpdoc_trim_consecutive_blank_line_separation' => true, - 'pow_to_exponentiation' => true, - 'psr_autoloading' => true, - 'random_api_migration' => true, - 'return_type_declaration' => [ - 'space_before' => 'none', - ], - 'self_accessor' => true, - 'semicolon_after_instruction' => true, - 'short_scalar_cast' => true, - 'simple_to_complex_string_variable' => true, - 'simplified_null_return' => true, - 'single_quote' => true, - 'space_after_semicolon' => true, - 'standardize_increment' => true, - 'standardize_not_equals' => true, - 'string_line_ending' => true, - 'ternary_operator_spaces' => true, - 'ternary_to_null_coalescing' => true, - 'trailing_comma_in_multiline' => [ - 'elements' => ['arrays'], - ], - 'trim_array_spaces' => true, - 'unary_operator_spaces' => true, - 'whitespace_after_comma_in_array' => true, - 'native_function_type_declaration_casing' => true, - 'no_closing_tag' => true, - 'no_spaces_inside_parenthesis' => true, - 'no_spaces_after_function_name' => true, - 'nullable_type_declaration_for_default_null_value' => [ - 'use_nullable_type_declaration' => true, - ], - 'single_line_after_imports' => true, - 'single_import_per_statement' => true, - 'switch_case_semicolon_to_colon' => true, - 'switch_case_space' => true, - 'binary_operator_spaces' => [ - 'default' => 'single_space', - 'operators' => ['=>' => null], - ], - 'array_syntax' => ['syntax' => 'short'], - 'class_attributes_separation' => [ - 'elements' => ['method' => 'one'], - ], - 'concat_space' => [ - 'spacing' => 'one', - ], - 'general_phpdoc_annotation_remove' => [ - 'annotations' => ['author'], - ], - 'increment_style' => [ - 'style' => 'post', - ], - 'no_extra_blank_lines' => [ - 'tokens' => [ - 'break', - 'continue', - 'throw', - 'use', - ], - ], - ]); diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..e465863 --- /dev/null +++ b/pint.json @@ -0,0 +1,175 @@ +{ + "preset": "laravel", + "rules": { + "@PSR1": true, + "@PSR2": true, + "@PSR12": true, + "align_multiline_comment": true, + "array_indentation": true, + "backtick_to_shell_exec": true, + "blank_line_after_opening_tag": true, + "blank_line_before_statement": true, + "cast_spaces": true, + "combine_consecutive_issets": true, + "combine_consecutive_unsets": true, + "combine_nested_dirname": true, + "comment_to_phpdoc": true, + "compact_nullable_typehint": true, + "declare_equal_normalize": true, + "dir_constant": true, + "explicit_indirect_variable": true, + "explicit_string_variable": true, + "fully_qualified_strict_types": true, + "function_to_constant": true, + "function_typehint_space": true, + "single_line_comment_style": { + "comment_types": [ + "hash" + ] + }, + "heredoc_to_nowdoc": true, + "implode_call": true, + "include": true, + "linebreak_after_opening_tag": true, + "list_syntax": { + "syntax": "short" + }, + "logical_operators": true, + "lowercase_cast": true, + "constant_case": { + "case": "lower" + }, + "lowercase_static_reference": true, + "magic_constant_casing": true, + "magic_method_casing": true, + "method_chaining_indentation": true, + "modernize_types_casting": true, + "multiline_comment_opening_closing": true, + "multiline_whitespace_before_semicolons": true, + "native_function_casing": true, + "no_alias_functions": true, + "no_alternative_syntax": true, + "no_binary_string": true, + "no_blank_lines_after_phpdoc": true, + "no_empty_phpdoc": true, + "no_empty_statement": true, + "no_leading_import_slash": true, + "no_leading_namespace_whitespace": true, + "no_mixed_echo_print": true, + "no_multiline_whitespace_around_double_arrow": true, + "no_null_property_initialization": true, + "no_php4_constructor": true, + "no_short_bool_cast": true, + "echo_tag_syntax": { + "format": "long" + }, + "no_singleline_whitespace_before_semicolons": true, + "no_spaces_around_offset": true, + "no_trailing_comma_in_singleline": true, + "no_unneeded_control_parentheses": true, + "no_unneeded_curly_braces": true, + "no_unneeded_final_method": true, + "no_unreachable_default_argument_value": true, + "no_unused_imports": true, + "no_useless_else": true, + "no_useless_return": true, + "no_whitespace_before_comma_in_array": true, + "no_whitespace_in_blank_line": true, + "not_operator_with_space": false, + "not_operator_with_successor_space": false, + "non_printable_character": true, + "normalize_index_brace": true, + "object_operator_without_whitespace": true, + "ordered_class_elements": true, + "ordered_imports": true, + "ordered_interfaces": true, + "php_unit_construct": true, + "php_unit_dedicate_assert": true, + "php_unit_dedicate_assert_internal_type": true, + "php_unit_expectation": true, + "php_unit_method_casing": { + "case": "snake_case" + }, + "phpdoc_indent": true, + "phpdoc_no_access": true, + "phpdoc_no_alias_tag": true, + "phpdoc_no_package": true, + "phpdoc_order": true, + "phpdoc_scalar": true, + "phpdoc_trim": true, + "phpdoc_types": true, + "phpdoc_var_without_name": true, + "phpdoc_summary": true, + "phpdoc_trim_consecutive_blank_line_separation": true, + "pow_to_exponentiation": true, + "psr_autoloading": true, + "random_api_migration": true, + "return_type_declaration": { + "space_before": "none" + }, + "self_accessor": true, + "semicolon_after_instruction": true, + "short_scalar_cast": true, + "simple_to_complex_string_variable": true, + "simplified_null_return": true, + "single_quote": true, + "space_after_semicolon": true, + "standardize_increment": true, + "standardize_not_equals": true, + "string_line_ending": true, + "ternary_operator_spaces": true, + "ternary_to_null_coalescing": true, + "trailing_comma_in_multiline": { + "elements": [ + "arrays" + ] + }, + "trim_array_spaces": true, + "unary_operator_spaces": true, + "whitespace_after_comma_in_array": true, + "native_function_type_declaration_casing": true, + "no_closing_tag": true, + "no_spaces_inside_parenthesis": true, + "no_spaces_after_function_name": true, + "nullable_type_declaration_for_default_null_value": { + "use_nullable_type_declaration": true + }, + "single_line_after_imports": true, + "single_import_per_statement": true, + "switch_case_semicolon_to_colon": true, + "switch_case_space": true, + "binary_operator_spaces": { + "default": "single_space", + "operators": { + "=>": null + } + }, + "array_syntax": { + "syntax": "short" + }, + "class_attributes_separation": { + "elements": { + "method": "one" + } + }, + "concat_space": { + "spacing": "one" + }, + "general_phpdoc_annotation_remove": { + "annotations": [ + "author" + ] + }, + "increment_style": { + "style": "post" + }, + "no_extra_blank_lines": { + "tokens": [ + "break", + "continue", + "throw", + "use" + ] + } + } +} \ No newline at end of file diff --git a/src/Commands/BatchProcess.php b/src/Commands/BatchProcess.php index 4f8b178..2559d27 100644 --- a/src/Commands/BatchProcess.php +++ b/src/Commands/BatchProcess.php @@ -27,6 +27,7 @@ class BatchProcess extends Command * The signing account resolver. */ public static $signingAccountResolver; + /** * The name and signature of the console command. * @@ -134,14 +135,14 @@ protected function process(): void protected function processBatch(BeamType $type): int { $batches = $this->batch->getBatchesForProcessing($type)->groupBy('beam_batch_id'); - if (!$batches->isEmpty()) { + if (! $batches->isEmpty()) { $batches->each(function ($claims, $batchId) use ($type) { $params = []; $createdTokens = []; $reassignedClaims = []; $claims->each(function ($claim) use (&$params, $type, &$createdTokens, &$reassignedClaims) { $collectionId = Arr::get($claim, 'beam.collection_chain_id'); - if (!isset($params[$collectionId])) { + if (! isset($params[$collectionId])) { $params[$collectionId] = [ 'collectionId' => $collectionId, 'recipients' => [], @@ -150,7 +151,7 @@ protected function processBatch(BeamType $type): int $params[$collectionId]['beamId'] = $claim->beam_id; - if (BeamType::TRANSFER_TOKEN == $type) { + if ($type == BeamType::TRANSFER_TOKEN) { $params[$collectionId]['recipients'][] = [ 'accountId' => $claim->wallet_public_key, 'params' => $this->substrate->getTransferParams([ @@ -173,7 +174,7 @@ protected function processBatch(BeamType $type): int return; } - if (!isset($this->tokenCreatedCache[$key])) { + if (! isset($this->tokenCreatedCache[$key])) { $this->tokenCreatedCache[$key] = Token::where(['token_chain_id' => $claim->token_chain_id, 'collection_id' => $claim->collection_id])->exists(); } @@ -194,14 +195,14 @@ protected function processBatch(BeamType $type): int ])->toEncodable(), ]; - if (!$this->tokenCreatedCache[$key]) { + if (! $this->tokenCreatedCache[$key]) { $this->tokenCreatedCache[$key] = true; $createdTokens[$key] = true; } } }); - $method = BeamType::MINT_ON_DEMAND == $type ? 'BatchMint' : 'BatchTransfer'; + $method = $type == BeamType::MINT_ON_DEMAND ? 'BatchMint' : 'BatchTransfer'; foreach ($params as $param) { $transaction = $this->transaction->store([ 'method' => $method, @@ -212,7 +213,13 @@ protected function processBatch(BeamType $type): int 'idempotency_key' => Str::uuid()->toString(), ]); BeamBatch::where('id', $batchId)->update(['transaction_id' => $transaction->id]); - BeamBatchTransactionCreated::safeBroadcast($param['beamId'], $param['collectionId'], $transaction->id); + BeamBatchTransactionCreated::safeBroadcast( + event: [ + 'beam_id' => $param['beamId'], + 'collection_id' => $param['collectionId'], + ], + transaction: $transaction + ); } $this->updateStatus($claims, $reassignedClaims); diff --git a/src/GraphQL/Mutations/AddTokensMutation.php b/src/GraphQL/Mutations/AddTokensMutation.php index 2da62e5..3b5e3cc 100644 --- a/src/GraphQL/Mutations/AddTokensMutation.php +++ b/src/GraphQL/Mutations/AddTokensMutation.php @@ -105,7 +105,7 @@ protected function rules(array $args = []): array 'min:1', 'max:10', new DistinctAttributes(), - Rule::prohibitedIf(BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute)))), + Rule::prohibitedIf(BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute))) == BeamType::TRANSFER_TOKEN), ]; }), 'tokens.*.attributes.*.key' => 'max:255', @@ -116,7 +116,7 @@ protected function rules(array $args = []): array 'required_without:tokens.*.tokenIdDataUpload', 'prohibits:tokens.*.tokenIdDataUpload', 'distinct', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokensExistInCollection($beam?->collection_chain_id) : new TokensDoNotExistInCollection($beam?->collection_chain_id), new TokensDoNotExistInBeam($beam), @@ -127,7 +127,7 @@ protected function rules(array $args = []): array 'bail', 'required_without:tokens.*.tokenIds', 'prohibits:tokens.*.tokenIds', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokenUploadExistInCollection($beam?->collection_chain_id) : new TokenUploadNotExistInCollection($beam?->collection_chain_id), new TokenUploadNotExistInBeam($beam), diff --git a/src/GraphQL/Mutations/ClaimBeamMutation.php b/src/GraphQL/Mutations/ClaimBeamMutation.php index 5d9de14..57116c9 100644 --- a/src/GraphQL/Mutations/ClaimBeamMutation.php +++ b/src/GraphQL/Mutations/ClaimBeamMutation.php @@ -25,8 +25,8 @@ class ClaimBeamMutation extends Mutation implements PlatformPublicGraphQlOperation { - use HasBeamCommonFields; use HasBeamClaimConditions; + use HasBeamCommonFields; use HasIdempotencyField; /** diff --git a/src/GraphQL/Mutations/CreateBeamMutation.php b/src/GraphQL/Mutations/CreateBeamMutation.php index e905d9f..ff5a6a6 100644 --- a/src/GraphQL/Mutations/CreateBeamMutation.php +++ b/src/GraphQL/Mutations/CreateBeamMutation.php @@ -100,7 +100,7 @@ protected function rules(array $args = []): array 'bail', 'filled', function (string $attribute, mixed $value, Closure $fail) { - if (!Collection::where('collection_chain_id', $value)->exists()) { + if (! Collection::where('collection_chain_id', $value)->exists()) { $fail('validation.exists')->translate(); } }, @@ -119,7 +119,7 @@ function (string $attribute, mixed $value, Closure $fail) { 'min:1', 'max:10', new DistinctAttributes(), - Rule::prohibitedIf(BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute)))), + Rule::prohibitedIf(BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute))) == BeamType::TRANSFER_TOKEN), ]; }), 'tokens.*.attributes.*.key' => 'max:255', @@ -130,7 +130,7 @@ function (string $attribute, mixed $value, Closure $fail) { 'required_without:tokens.*.tokenIdDataUpload', 'prohibits:tokens.*.tokenIdDataUpload', 'distinct', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokensExistInCollection($args['collectionId']) : new TokensDoNotExistInCollection($args['collectionId']), new TokensDoNotExistInBeam(), @@ -141,7 +141,7 @@ function (string $attribute, mixed $value, Closure $fail) { 'bail', 'required_without:tokens.*.tokenIds', 'prohibits:tokens.*.tokenIds', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokenUploadExistInCollection($args['collectionId']) : new TokenUploadNotExistInCollection($args['collectionId']), new TokenUploadNotExistInBeam(), diff --git a/src/GraphQL/Mutations/UpdateBeamMutation.php b/src/GraphQL/Mutations/UpdateBeamMutation.php index d082b4b..a0994d5 100644 --- a/src/GraphQL/Mutations/UpdateBeamMutation.php +++ b/src/GraphQL/Mutations/UpdateBeamMutation.php @@ -124,7 +124,7 @@ protected function rules(array $args = []): array 'min:1', 'max:10', new DistinctAttributes(), - Rule::prohibitedIf(BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute)))), + Rule::prohibitedIf(BeamType::getEnumCase(Arr::get($args, str_replace('attributes', 'type', $attribute))) == BeamType::TRANSFER_TOKEN), ]; }), 'tokens.*.attributes.*.key' => 'max:255', @@ -135,7 +135,7 @@ protected function rules(array $args = []): array 'required_without:tokens.*.tokenIdDataUpload', 'prohibits:tokens.*.tokenIdDataUpload', 'distinct', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokensExistInCollection($beam?->collection_chain_id) : new TokensDoNotExistInCollection($beam?->collection_chain_id), new TokensDoNotExistInBeam($beam), @@ -146,7 +146,7 @@ protected function rules(array $args = []): array 'bail', 'required_without:tokens.*.tokenIds', 'prohibits:tokens.*.tokenIds', - BeamType::TRANSFER_TOKEN == BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) + BeamType::getEnumCase(Arr::get($args, str_replace('tokenIdDataUpload', 'type', $attribute))) == BeamType::TRANSFER_TOKEN ? new TokenUploadExistInCollection($beam?->collection_chain_id) : new TokenUploadNotExistInCollection($beam?->collection_chain_id), new TokenUploadNotExistInBeam($beam), diff --git a/src/GraphQL/Types/BeamClaimType.php b/src/GraphQL/Types/BeamClaimType.php index bd98938..14ae7fa 100644 --- a/src/GraphQL/Types/BeamClaimType.php +++ b/src/GraphQL/Types/BeamClaimType.php @@ -9,8 +9,8 @@ class BeamClaimType extends Type { - use HasSelectFields; use HasAuthorizableFields; + use HasSelectFields; /** * Get the type's attributes. diff --git a/src/GraphQL/Types/BeamType.php b/src/GraphQL/Types/BeamType.php index 679b90a..222dd5d 100644 --- a/src/GraphQL/Types/BeamType.php +++ b/src/GraphQL/Types/BeamType.php @@ -67,7 +67,7 @@ public function fields(): array 'resolve' => fn ($beam) => Carbon::now()->between( Carbon::parse($beam->start), Carbon::parse($beam->end) - ) && !$beam->hasFlag(BeamFlag::PAUSED) + ) && ! $beam->hasFlag(BeamFlag::PAUSED) && ((int) Cache::get(BeamService::key($beam->code), BeamService::claimsCountResolver($beam->code))) > 0, 'selectable' => false, 'is_relation' => false, @@ -113,7 +113,7 @@ public function fields(): array $beam?->claims, $args['first'], Arr::get($args, 'after') ? Cursor::fromEncoded($args['after']) : null, - ['parameters'=>['id']] + ['parameters' => ['id']] ), 'total' => (int) $beam?->claims_count, ]; diff --git a/src/GraphQL/Types/Input/IntegerRangeStringType.php b/src/GraphQL/Types/Input/IntegerRangeStringType.php index 22080a0..dc2b970 100644 --- a/src/GraphQL/Types/Input/IntegerRangeStringType.php +++ b/src/GraphQL/Types/Input/IntegerRangeStringType.php @@ -13,8 +13,8 @@ class IntegerRangeStringType extends ScalarType implements PlatformGraphQlType, TypeConvertible { - use InGlobalSchema; use HasIntegerRanges; + use InGlobalSchema; public function __construct(array $config = []) { @@ -40,7 +40,7 @@ public function serialize($value): string */ public function parseValue($value): string { - if (!is_string($value) || !$this->isValid($value)) { + if (! is_string($value) || ! $this->isValid($value)) { throw new Error(__('enjin-platform::error.cannot_represent_integer_range', ['value' => Utils::printSafeJson($value)])); } @@ -52,7 +52,7 @@ public function parseValue($value): string */ public function parseLiteral($valueNode, ?array $variables = null): string { - if (!in_array($valueNode->kind, ['StringValue']) || !$this->isValid($valueNode->value)) { + if (! in_array($valueNode->kind, ['StringValue']) || ! $this->isValid($valueNode->value)) { throw new Error(__('enjin-platform::error.not_valid_integer_range'), [$valueNode]); } @@ -64,7 +64,7 @@ public function parseLiteral($valueNode, ?array $variables = null): string */ public function isValid($value): bool { - return !$this->validateValue($value); + return ! $this->validateValue($value); } /** diff --git a/src/Jobs/ClaimBeam.php b/src/Jobs/ClaimBeam.php index 3d1e970..2262004 100644 --- a/src/Jobs/ClaimBeam.php +++ b/src/Jobs/ClaimBeam.php @@ -62,7 +62,7 @@ public function handle(BatchService $batch, WalletService $wallet): void Cache::put(BeamService::key(Arr::get($data, 'beam.code')), 0); Log::info('ClaimBeamJob: No claim available, setting remaining count to 0', $data); } - } catch(LockTimeoutException) { + } catch (LockTimeoutException) { Log::info('ClaimBeamJob: Cannot obtain lock, retrying', $data); $this->release(1); } catch (Throwable $e) { @@ -86,7 +86,7 @@ public function failed(Throwable $exception): void if ($this->claimQuery($data)->count() > 0) { // Idempotency key prevents incrementing cache on same claim request even with manual retry on horizon $key = Arr::get($data, 'idempotency_key'); - if (!Cache::get(PlatformBeamCache::IDEMPOTENCY_KEY->key($key))) { + if (! Cache::get(PlatformBeamCache::IDEMPOTENCY_KEY->key($key))) { Cache::forever($key, true); Cache::increment(BeamService::key(Arr::get($data, 'beam.code'))); Log::info('ClaimBeamJob: Job failed, incrementing remaining count to 1', $data); diff --git a/src/Jobs/DispatchCreateBeamClaimsJobs.php b/src/Jobs/DispatchCreateBeamClaimsJobs.php index 91f8de4..8246c45 100644 --- a/src/Jobs/DispatchCreateBeamClaimsJobs.php +++ b/src/Jobs/DispatchCreateBeamClaimsJobs.php @@ -15,10 +15,10 @@ class DispatchCreateBeamClaimsJobs implements ShouldQueue { use Dispatchable; + use IntegerRange; use InteractsWithQueue; use Queueable; use SerializesModels; - use IntegerRange; /** * Create a new job instance. @@ -43,7 +43,7 @@ public function handle(): void $chunks->each(function ($token) use ($beam, $claims) { collect($token['tokenIds'])->each(function ($tokenId) use ($beam, $claims, $token) { $range = $this->integerRange($tokenId); - if (false === $range) { + if ($range === false) { for ($i = 0; $i < $token['claimQuantity']; $i++) { $claims->push([ 'beam_id' => $beam->id, diff --git a/src/Listeners/UpdateClaimStatus.php b/src/Listeners/UpdateClaimStatus.php index 74fe570..f7fb01d 100644 --- a/src/Listeners/UpdateClaimStatus.php +++ b/src/Listeners/UpdateClaimStatus.php @@ -34,7 +34,7 @@ public function handle(PlatformBroadcastEvent $event): void ->with('beam') ->get(); - if (!$claims->isEmpty()) { + if (! $claims->isEmpty()) { $state = TransactionState::FINALIZED->name == $event->broadcastData['state'] && $event->broadcastData['result'] == SystemEventType::EXTRINSIC_SUCCESS->name ? ClaimStatus::COMPLETED->name diff --git a/src/Models/Laravel/Beam.php b/src/Models/Laravel/Beam.php index e8313cd..ada5a84 100644 --- a/src/Models/Laravel/Beam.php +++ b/src/Models/Laravel/Beam.php @@ -20,11 +20,11 @@ class Beam extends BaseModel { - use Traits\HasBeamQr; - use Traits\EagerLoadSelectFields; + use HasEagerLimit; use HasFactory; use SoftDeletes; - use HasEagerLimit; + use Traits\EagerLoadSelectFields; + use Traits\HasBeamQr; /** * The attributes that aren't mass assignable. diff --git a/src/Models/Laravel/BeamClaim.php b/src/Models/Laravel/BeamClaim.php index 9d3e3b9..1aee55b 100644 --- a/src/Models/Laravel/BeamClaim.php +++ b/src/Models/Laravel/BeamClaim.php @@ -176,7 +176,7 @@ public function claimableCode(): Attribute */ public function prunable() { - if (!is_null($days = config('enjin-platform-beam.prune_expired_claims'))) { + if (! is_null($days = config('enjin-platform-beam.prune_expired_claims'))) { $query = static::whereHas( 'beam', fn ($query) => $query->where('end', '<', now()->addDays($days)) diff --git a/src/Models/Laravel/BeamScan.php b/src/Models/Laravel/BeamScan.php index 974c1ea..1ab69d8 100644 --- a/src/Models/Laravel/BeamScan.php +++ b/src/Models/Laravel/BeamScan.php @@ -11,12 +11,12 @@ class BeamScan extends BaseModel { + use HasEagerLimit; use HasFactory; use SoftDeletes; - use Traits\HasCodeScope; - use Traits\HasClaimable; use Traits\EagerLoadSelectFields; - use HasEagerLimit; + use Traits\HasClaimable; + use Traits\HasCodeScope; /** * The attributes that aren't mass assignable. @@ -51,8 +51,6 @@ class BeamScan extends BaseModel /** * The beam's relationship. - * - * @return BelongsTo */ public function beam(): BelongsTo { diff --git a/src/Models/Laravel/Traits/EagerLoadSelectFields.php b/src/Models/Laravel/Traits/EagerLoadSelectFields.php index 4bd71f8..766028a 100644 --- a/src/Models/Laravel/Traits/EagerLoadSelectFields.php +++ b/src/Models/Laravel/Traits/EagerLoadSelectFields.php @@ -27,7 +27,7 @@ public static function selectFields(ResolveInfo $resolveInfo, string $query): ar static::$query = $query; $queryPlan = $resolveInfo->lookAhead()->queryPlan(); - switch($query) { + switch ($query) { case 'GetBeams': case 'GetBeam': [$select, $with, $withCount] = static::loadBeams( @@ -53,7 +53,6 @@ public static function selectFields(ResolveInfo $resolveInfo, string $query): ar break; } - return [$select, $with, $withCount]; } @@ -79,7 +78,7 @@ public static function loadBeams( $with = []; $withCount = []; - if (!$isParent) { + if (! $isParent) { $with = [ $key => function ($query) use ($select, $args) { $query->select(array_unique($select)) @@ -138,7 +137,7 @@ public static function loadClaims( $with = []; $withCount = []; - if (!$isParent) { + if (! $isParent) { $with = [ $key => function ($query) use ($select, $args) { $query->select(array_unique($select)) @@ -184,7 +183,7 @@ public static function getRelationQuery( $key = $parent ? "{$parent}.{$attribute}" : $attribute; $alias = static::getAlias($attribute, $parentType); $args = Arr::get($selections, $attribute . '.args', []); - switch($alias) { + switch ($alias) { case 'claims': $relations = static::loadClaims( $selections, diff --git a/src/Rules/CanClaim.php b/src/Rules/CanClaim.php index 186c2e4..8615b4e 100644 --- a/src/Rules/CanClaim.php +++ b/src/Rules/CanClaim.php @@ -24,15 +24,11 @@ public function __construct(protected bool $singleUse = false) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { - if (!Arr::get($this->data, 'account')) { + if (! Arr::get($this->data, 'account')) { return; } @@ -46,7 +42,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $passes = ((int) Cache::get(BeamService::key($value), BeamService::claimsCountResolver($value))) > 0; - if (!$passes) { + if (! $passes) { $fail('enjin-platform-beam::validation.can_claim')->translate(); } } diff --git a/src/Rules/HasBeamFlag.php b/src/Rules/HasBeamFlag.php index c98d0a6..fd11e40 100644 --- a/src/Rules/HasBeamFlag.php +++ b/src/Rules/HasBeamFlag.php @@ -19,17 +19,13 @@ public function __construct(protected BeamFlag $flag) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { $beam = Beam::whereCode($value)->first(); - if (!$beam || !$beam->hasFlag($this->flag)) { + if (! $beam || ! $beam->hasFlag($this->flag)) { $fail('enjin-platform-beam::validation.has_beam_flag')->translate(); } } diff --git a/src/Rules/IsEndDateValid.php b/src/Rules/IsEndDateValid.php index 804ed49..5bd1da0 100644 --- a/src/Rules/IsEndDateValid.php +++ b/src/Rules/IsEndDateValid.php @@ -17,11 +17,7 @@ class IsEndDateValid implements DataAwareRule, ValidationRule /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/IsStartDateValid.php b/src/Rules/IsStartDateValid.php index 4f7267a..788e8bb 100644 --- a/src/Rules/IsStartDateValid.php +++ b/src/Rules/IsStartDateValid.php @@ -17,11 +17,7 @@ class IsStartDateValid implements DataAwareRule, ValidationRule /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/MaxBigIntIntegerRange.php b/src/Rules/MaxBigIntIntegerRange.php index 4992659..4da7445 100644 --- a/src/Rules/MaxBigIntIntegerRange.php +++ b/src/Rules/MaxBigIntIntegerRange.php @@ -14,7 +14,7 @@ class MaxBigIntIntegerRange extends MaxBigInt protected function isValidMaxBigInt($value): bool { $range = $this->integerRange($value); - $value = false === $range ? $value : $range[0]; + $value = $range === false ? $value : $range[0]; $this->message = __('enjin-platform::validation.max_big_int', ['max' => $this->max]); return bccomp($this->max, $value) >= 0; diff --git a/src/Rules/MaxTokenCount.php b/src/Rules/MaxTokenCount.php index 9d826e9..b3da231 100644 --- a/src/Rules/MaxTokenCount.php +++ b/src/Rules/MaxTokenCount.php @@ -31,16 +31,12 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { - if ($this->collectionId && ($collection = Collection::withCount('tokens')->firstWhere(['collection_chain_id'=> $this->collectionId]))) { - if (!is_null($this->limit = $collection->max_token_count)) { + if ($this->collectionId && ($collection = Collection::withCount('tokens')->firstWhere(['collection_chain_id' => $this->collectionId]))) { + if (! is_null($this->limit = $collection->max_token_count)) { $passes = $collection->max_token_count >= $collection->tokens_count + collect($this->data['tokens']) ->filter(fn ($token) => BeamType::getEnumCase($token['type']) == BeamType::MINT_ON_DEMAND) @@ -61,7 +57,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void )->where('type', BeamType::MINT_ON_DEMAND->name) ->count(); - if (!$passes) { + if (! $passes) { $fail('enjin-platform-beam::validation.max_token_count') ->translate([ 'limit' => $this->limit, diff --git a/src/Rules/MaxTokenSupply.php b/src/Rules/MaxTokenSupply.php index 3b05df2..1fea4b3 100644 --- a/src/Rules/MaxTokenSupply.php +++ b/src/Rules/MaxTokenSupply.php @@ -31,6 +31,7 @@ class MaxTokenSupply implements DataAwareRule, ValidationRule * The error messages. */ protected string $maxTokenSupplyMessage = 'enjin-platform-beam::validation.max_token_supply'; + protected string $maxTokenBalanceMessage = 'enjin-platform::validation.max_token_balance'; /** @@ -43,20 +44,16 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if ($this->collectionId && ($collection = Collection::firstWhere(['collection_chain_id' => $this->collectionId])) - && !is_null($this->limit = $collection->max_token_supply) + && ! is_null($this->limit = $collection->max_token_supply) ) { if (Arr::get($this->data, str_replace('tokenQuantityPerClaim', 'type', $attribute)) == BeamType::MINT_ON_DEMAND->name) { - if (!$collection->max_token_supply >= $value) { + if (! $collection->max_token_supply >= $value) { $fail($this->maxTokenSupplyMessage) ->translate([ 'limit' => $this->limit, @@ -67,11 +64,11 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } $tokenIds = Arr::get($this->data, str_replace('tokenQuantityPerClaim', 'tokenIds', $attribute)); - $integers = collect($tokenIds)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $wallet = Wallet::firstWhere(['public_key' => Account::daemonPublicKey()]); $collection = Collection::firstWhere(['collection_chain_id' => $this->collectionId]); - if (!$wallet || !$collection) { + if (! $wallet || ! $collection) { $fail($this->maxTokenSupplyMessage) ->translate([ 'limit' => $this->limit, @@ -105,11 +102,11 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } } - $ranges = collect($tokenIds)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); if ($ranges) { $wallet = Wallet::firstWhere(['public_key' => Account::daemonPublicKey()]); $collection = Collection::firstWhere(['collection_chain_id' => $this->collectionId]); - if (!$wallet || !$collection) { + if (! $wallet || ! $collection) { $fail($this->maxTokenSupplyMessage) ->translate([ 'limit' => $this->limit, diff --git a/src/Rules/MinBigIntIntegerRange.php b/src/Rules/MinBigIntIntegerRange.php index 2cb5d30..96c1bdb 100644 --- a/src/Rules/MinBigIntIntegerRange.php +++ b/src/Rules/MinBigIntIntegerRange.php @@ -14,7 +14,7 @@ class MinBigIntIntegerRange extends MinBigInt protected function isValidMinBigInt($value): bool { $range = $this->integerRange($value); - $value = false === $range ? $value : $range[0]; + $value = $range === false ? $value : $range[0]; $this->message = __('enjin-platform::validation.min_big_int', ['min' => $this->min]); return bccomp($this->min, $value) <= 0; diff --git a/src/Rules/NotExpired.php b/src/Rules/NotExpired.php index f7f4537..013f6f8 100644 --- a/src/Rules/NotExpired.php +++ b/src/Rules/NotExpired.php @@ -16,15 +16,11 @@ public function __construct(protected ?string $code = null) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { - if (!$beam = Beam::where('code', $this->code ?: $value)->first()) { + if (! $beam = Beam::where('code', $this->code ?: $value)->first()) { $fail('validation.exists')->translate(); return; diff --git a/src/Rules/NotOwner.php b/src/Rules/NotOwner.php index 974f745..05bd1ea 100644 --- a/src/Rules/NotOwner.php +++ b/src/Rules/NotOwner.php @@ -22,11 +22,7 @@ public function __construct(protected bool $isSingleUse = false) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/NotPaused.php b/src/Rules/NotPaused.php index 7570c34..40d843c 100644 --- a/src/Rules/NotPaused.php +++ b/src/Rules/NotPaused.php @@ -16,11 +16,7 @@ public function __construct(protected ?string $code = null) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/PassesClaimCondition.php b/src/Rules/PassesClaimCondition.php index a1c4a48..8f12119 100644 --- a/src/Rules/PassesClaimCondition.php +++ b/src/Rules/PassesClaimCondition.php @@ -23,17 +23,13 @@ public function __construct( /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { $result = ($this->function)($attribute, $value, $this->singleUse, $this->data); - if (true !== $result) { + if ($result !== true) { $fail(is_string($result) ? $result : __('enjin-platform-beam::validation.passes_condition')); } } diff --git a/src/Rules/PassesClaimConditions.php b/src/Rules/PassesClaimConditions.php index da32415..9ee9d96 100644 --- a/src/Rules/PassesClaimConditions.php +++ b/src/Rules/PassesClaimConditions.php @@ -71,17 +71,13 @@ public static function clearConditionalFunctions(): void /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { $conditions = collect(static::$functions); - if (!$conditions->every(fn ($function) => $function($attribute, $value, $this->singleUse, $this->data))) { + if (! $conditions->every(fn ($function) => $function($attribute, $value, $this->singleUse, $this->data))) { $fail('enjin-platform-beam::validation.passes_conditions')->translate(); } } diff --git a/src/Rules/ScanLimit.php b/src/Rules/ScanLimit.php index eb83b0c..2eda3df 100644 --- a/src/Rules/ScanLimit.php +++ b/src/Rules/ScanLimit.php @@ -15,18 +15,14 @@ class ScanLimit implements DataAwareRule, ValidationRule /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { $limit = config('enjin-platform-beam.scan_limit'); if ($limit && - !($limit > (int) BeamScan::whereWalletPublicKey($value) + ! ($limit > (int) BeamScan::whereWalletPublicKey($value) ->hasCode($this->data['code']) ->first()?->count) ) { diff --git a/src/Rules/SingleUseCodeExist.php b/src/Rules/SingleUseCodeExist.php index fbd3597..9011d42 100644 --- a/src/Rules/SingleUseCodeExist.php +++ b/src/Rules/SingleUseCodeExist.php @@ -16,11 +16,7 @@ public function __construct(protected bool $isClaiming = false) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/SingleUseCodesExist.php b/src/Rules/SingleUseCodesExist.php index e93cba6..0acd477 100644 --- a/src/Rules/SingleUseCodesExist.php +++ b/src/Rules/SingleUseCodesExist.php @@ -9,11 +9,7 @@ class SingleUseCodesExist extends SingleUseCodeExist /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Rules/TokenUploadExistInCollection.php b/src/Rules/TokenUploadExistInCollection.php index 79a32eb..9d1ffe6 100644 --- a/src/Rules/TokenUploadExistInCollection.php +++ b/src/Rules/TokenUploadExistInCollection.php @@ -12,7 +12,6 @@ class TokenUploadExistInCollection implements ValidationRule { use IntegerRange; - /** * The message that should be used when validation fails. */ @@ -25,11 +24,7 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -38,7 +33,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $tokens = LazyCollection::make(function () use ($value, $ids) { $handle = fopen($value->getPathname(), 'r'); while (($line = fgets($handle)) !== false) { - if (!$this->tokenIdExists($ids->all(), $tokenId = trim($line))) { + if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) { $ids->push($tokenId); yield $tokenId; } @@ -47,7 +42,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void }); foreach ($tokens->chunk(10000) as $tokenIds) { - $integers = $tokenIds->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = $tokenIds->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $count = Token::whereIn('token_chain_id', $integers) ->whereHas('collection', fn ($query) => $query->where('collection_chain_id', $this->collectionId)) @@ -59,7 +54,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } } - $ranges = collect($tokenIds)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); $count = Token::whereBetween('token_chain_id', [(int) $from, (int) $to]) diff --git a/src/Rules/TokenUploadNotExistInBeam.php b/src/Rules/TokenUploadNotExistInBeam.php index 3ff614d..6f775fb 100644 --- a/src/Rules/TokenUploadNotExistInBeam.php +++ b/src/Rules/TokenUploadNotExistInBeam.php @@ -13,8 +13,8 @@ class TokenUploadNotExistInBeam implements DataAwareRule, ValidationRule { - use IntegerRange; use HasDataAwareRule; + use IntegerRange; public function __construct(protected ?Model $beam = null) { @@ -23,11 +23,7 @@ public function __construct(protected ?Model $beam = null) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -35,7 +31,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $tokens = LazyCollection::make(function () use ($value, $ids) { $handle = fopen($value->getPathname(), 'r'); while (($line = fgets($handle)) !== false) { - if (!$this->tokenIdExists($ids->all(), $tokenId = trim($line))) { + if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) { $ids->push($tokenId); yield $tokenId; } @@ -45,7 +41,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $prepare = TokensDoNotExistInBeam::prepareStatement($this->beam, Arr::get($this->data, 'collectionId')); foreach ($tokens->chunk(1000) as $tokenIds) { - $integers = collect($tokenIds)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { if ($prepare->whereIn('beam_claims.token_chain_id', $integers)->exists()) { $fail($this->message())->translate(); @@ -53,7 +49,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } } - $ranges = collect($tokenIds)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); if ($prepare->whereBetween('beam_claims.token_chain_id', [(int) $from, (int) $to])->exists()) { diff --git a/src/Rules/TokenUploadNotExistInCollection.php b/src/Rules/TokenUploadNotExistInCollection.php index 9b3bf51..25e7b4f 100644 --- a/src/Rules/TokenUploadNotExistInCollection.php +++ b/src/Rules/TokenUploadNotExistInCollection.php @@ -19,11 +19,7 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -32,7 +28,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $tokens = LazyCollection::make(function () use ($value, $ids) { $handle = fopen($value->getPathname(), 'r'); while (($line = fgets($handle)) !== false) { - if (!$this->tokenIdExists($ids->all(), $tokenId = trim($line))) { + if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) { $ids->push($tokenId); yield $tokenId; } @@ -41,7 +37,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void }); foreach ($tokens->chunk(10000) as $tokenIds) { - $integers = $tokenIds->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = $tokenIds->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $exists = Token::whereIn('token_chain_id', $integers) ->whereHas('collection', fn ($query) => $query->where('collection_chain_id', $this->collectionId)) @@ -53,7 +49,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } } - $ranges = collect($tokenIds)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($tokenIds)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); $exists = Token::whereBetween('token_chain_id', [(int) $from, (int) $to]) diff --git a/src/Rules/TokensDoNotExistInBeam.php b/src/Rules/TokensDoNotExistInBeam.php index b665b67..e5e51f8 100644 --- a/src/Rules/TokensDoNotExistInBeam.php +++ b/src/Rules/TokensDoNotExistInBeam.php @@ -15,8 +15,8 @@ class TokensDoNotExistInBeam implements DataAwareRule, ValidationRule { - use IntegerRange; use HasDataAwareRule; + use IntegerRange; public function __construct(protected ?Model $beam = null) { @@ -25,16 +25,12 @@ public function __construct(protected ?Model $beam = null) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { $prepare = static::prepareStatement($this->beam, Arr::get($this->data, 'collectionId')); - $integers = collect($value)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($value)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { if ($prepare->whereIn('beam_claims.token_chain_id', $integers)->exists()) { $fail($this->message())->translate(); @@ -42,7 +38,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } } - $ranges = collect($value)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($value)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); if ($prepare->whereBetween('beam_claims.token_chain_id', [(int) $from, (int) $to])->exists()) { diff --git a/src/Rules/TokensDoNotExistInCollection.php b/src/Rules/TokensDoNotExistInCollection.php index dd2feaa..d0136c5 100644 --- a/src/Rules/TokensDoNotExistInCollection.php +++ b/src/Rules/TokensDoNotExistInCollection.php @@ -18,16 +18,12 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if ($this->collectionId) { - $integers = collect($value)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($value)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $exists = Token::whereIn('token_chain_id', $integers) ->whereHas('collection', fn ($query) => $query->where('collection_chain_id', $this->collectionId)) @@ -38,7 +34,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } } - $ranges = collect($value)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($value)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); $exists = Token::whereBetween('token_chain_id', [(int) $from, (int) $to]) diff --git a/src/Rules/TokensExistInBeam.php b/src/Rules/TokensExistInBeam.php index 6e38930..1c8e4ed 100644 --- a/src/Rules/TokensExistInBeam.php +++ b/src/Rules/TokensExistInBeam.php @@ -11,22 +11,18 @@ class TokensExistInBeam implements DataAwareRule, ValidationRule { - use IntegerRange; use HasDataAwareRule; + use IntegerRange; /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if ($code = $this->data['code']) { - $integers = collect($value)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($value)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $count = BeamClaim::whereIn('token_chain_id', $integers) ->whereNull('claimed_at') @@ -39,7 +35,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } } - $ranges = collect($value)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($value)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); $count = BeamClaim::whereBetween('token_chain_id', [(int) $from, (int) $to]) diff --git a/src/Rules/TokensExistInCollection.php b/src/Rules/TokensExistInCollection.php index a0b6e03..391c961 100644 --- a/src/Rules/TokensExistInCollection.php +++ b/src/Rules/TokensExistInCollection.php @@ -18,16 +18,12 @@ public function __construct(protected ?string $collectionId) /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { if ($this->collectionId) { - $integers = collect($value)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($value)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { $count = Token::whereIn('token_chain_id', $integers) ->whereHas('collection', fn ($query) => $query->where('collection_chain_id', $this->collectionId)) @@ -38,7 +34,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } } - $ranges = collect($value)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($value)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); $count = Token::whereBetween('token_chain_id', [(int) $from, (int) $to]) diff --git a/src/Rules/Traits/IntegerRange.php b/src/Rules/Traits/IntegerRange.php index 1231118..4da1e1b 100644 --- a/src/Rules/Traits/IntegerRange.php +++ b/src/Rules/Traits/IntegerRange.php @@ -21,11 +21,11 @@ protected function integerRange(string $value): bool|array */ protected function tokenIdExists(array $tokenIds, string $value): bool { - $integers = array_filter($tokenIds, fn ($val) => false === $this->integerRange($val)); - $integerRanges = array_filter($tokenIds, fn ($val) => false !== $this->integerRange($val)); + $integers = array_filter($tokenIds, fn ($val) => $this->integerRange($val) === false); + $integerRanges = array_filter($tokenIds, fn ($val) => $this->integerRange($val) !== false); $valueRange = $this->integerRange($value); - if (false === $valueRange) { + if ($valueRange === false) { if (in_array($value, $integers)) { return true; } diff --git a/src/Rules/UniqueTokenIds.php b/src/Rules/UniqueTokenIds.php index 4c91eaa..e5d363d 100644 --- a/src/Rules/UniqueTokenIds.php +++ b/src/Rules/UniqueTokenIds.php @@ -13,11 +13,7 @@ class UniqueTokenIds implements ValidationRule /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -26,7 +22,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void ->pluck('tokenIds') ->filter() ->flatten() - ->sortBy(fn ($tokenId) => false !== $this->integerRange($tokenId)); + ->sortBy(fn ($tokenId) => $this->integerRange($tokenId) !== false); foreach ($tokens->all() as $tokenId) { if ($this->tokenIdExists($tokenIds, $tokenId)) { diff --git a/src/Rules/VerifySignedMessage.php b/src/Rules/VerifySignedMessage.php index e6a57c8..d24666f 100644 --- a/src/Rules/VerifySignedMessage.php +++ b/src/Rules/VerifySignedMessage.php @@ -20,15 +20,11 @@ class VerifySignedMessage implements DataAwareRule, ValidationRule /** * Determine if the validation rule passes. * - * @param string $attribute - * @param mixed $value - * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail - * - * @return void + * @param Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { - if (!$publicKey = SS58Address::getPublicKey($this->data['account'])) { + if (! $publicKey = SS58Address::getPublicKey($this->data['account'])) { $fail('enjin-platform::validation.valid_substrate_account') ->translate([ 'attribute' => 'account', @@ -41,7 +37,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $this->data['code'] = BeamService::getSingleUseCodeData($this->data['code'])?->beamCode; } - if (!$scan = BeamScan::hasCode($this->data['code'])->firstWhere(['wallet_public_key' => $publicKey])) { + if (! $scan = BeamScan::hasCode($this->data['code'])->firstWhere(['wallet_public_key' => $publicKey])) { $fail('enjin-platform-beam::validation.beam_scan_not_found')->translate(); return; @@ -60,7 +56,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void $type ); - if (!$passes) { + if (! $passes) { $fail('enjin-platform-beam::validation.verify_signed_message')->translate(); } } diff --git a/src/Services/BatchService.php b/src/Services/BatchService.php index 6bbcccd..2dd010d 100644 --- a/src/Services/BatchService.php +++ b/src/Services/BatchService.php @@ -26,7 +26,7 @@ class BatchService */ public function __construct() { - if (!$this->threshold = config('enjin-platform-beam.batch_process.threshold')) { + if (! $this->threshold = config('enjin-platform-beam.batch_process.threshold')) { throw new BeamException(__('enjin-platform-beam::error.threshold_not_set')); } } @@ -41,7 +41,7 @@ public function getNextBatchId(BeamType $type, string $collectionid): int 'beam_type' => $type->name, 'collection_chain_id' => $collectionid, ]); - if (!$batch->exists) { + if (! $batch->exists) { $batch->save(); } diff --git a/src/Services/BeamService.php b/src/Services/BeamService.php index 4d94ed1..e0ac889 100644 --- a/src/Services/BeamService.php +++ b/src/Services/BeamService.php @@ -60,7 +60,7 @@ public function __construct( /** * Get flags bitmask value. */ - public static function getFlagsValue(?array $flags, int $initial = 0): int|null + public static function getFlagsValue(?array $flags, int $initial = 0): ?int { if (is_null($flags)) { return 0; @@ -142,7 +142,7 @@ public function addTokens(string $code, array $tokens): bool /** * Find beam by code. */ - public function findByCode(string $code): Model|null + public function findByCode(string $code): ?Model { return Beam::whereCode($code)->first(); } @@ -150,7 +150,7 @@ public function findByCode(string $code): Model|null /** * Scan beam by code. */ - public function scanByCode(string $code, ?string $wallet = null): Model|null + public function scanByCode(string $code, ?string $wallet = null): ?Model { $isSingleUse = static::isSingleUse($code); @@ -197,7 +197,7 @@ public function claim(string $code, string $wallet, ?string $idempotencyKey = nu $beam = $this->findByCode($code); } - if (!$beam) { + if (! $beam) { throw new BeamException(__('enjin-platform-beam::error.beam_not_found', ['code' => $code])); } @@ -269,7 +269,7 @@ public function expireSingleUseCodes(array $codes): int $beams = []; collect($codes)->each(function ($code) use (&$beams) { if ($claim = BeamClaim::claimable()->withSingleUseCode($code)->first()) { - if (!isset($beams[$claim->beam_id])) { + if (! isset($beams[$claim->beam_id])) { $beams[$claim->beam_id] = 0; } $beams[$claim->beam_id] += $claim->increment('nonce'); @@ -289,7 +289,7 @@ public function expireSingleUseCodes(array $codes): int */ public static function hasSingleUse(?string $code): bool { - if (!$code) { + if (! $code) { return false; } @@ -301,7 +301,7 @@ public static function hasSingleUse(?string $code): bool */ public static function isSingleUse(?string $code): bool { - if (!$code) { + if (! $code) { return false; } @@ -343,7 +343,7 @@ public function deleteByCode(string $code): bool */ public function removeTokens(string $code, array $tokens): bool { - $integers = collect($tokens)->filter(fn ($val) => false === $this->integerRange($val))->all(); + $integers = collect($tokens)->filter(fn ($val) => $this->integerRange($val) === false)->all(); if ($integers) { Cache::decrement( self::key($code), @@ -354,7 +354,7 @@ public function removeTokens(string $code, array $tokens): bool ); } - $ranges = collect($tokens)->filter(fn ($val) => false !== $this->integerRange($val))->all(); + $ranges = collect($tokens)->filter(fn ($val) => $this->integerRange($val) !== false)->all(); foreach ($ranges as $range) { [$from, $to] = $this->integerRange($range); Cache::decrement( @@ -368,7 +368,7 @@ public function removeTokens(string $code, array $tokens): bool if ($tokens) { $this->probability->removeTokens($code, $tokens); - TokensRemoved::dispatch(['code'=>$code, 'tokenIds' => $tokens]); + TokensRemoved::dispatch(['code' => $code, 'tokenIds' => $tokens]); } return true; @@ -406,7 +406,7 @@ protected function createClaims(array $tokens, Model $beam): int LazyCollection::make(function () use ($token, $ids) { $handle = fopen($token['tokenIdDataUpload']->getPathname(), 'r'); while (($line = fgets($handle)) !== false) { - if (!$this->tokenIdExists($ids->all(), $tokenId = trim($line))) { + if (! $this->tokenIdExists($ids->all(), $tokenId = trim($line))) { $ids->push($tokenId); yield $tokenId; } diff --git a/src/Support/ClaimProbabilities.php b/src/Support/ClaimProbabilities.php index d289b40..1bd248c 100644 --- a/src/Support/ClaimProbabilities.php +++ b/src/Support/ClaimProbabilities.php @@ -121,7 +121,7 @@ public function removeTokens(string $code, array $tokenIds): void public function computeProbabilities(string $code, array $fts, array $nfts): void { $total = collect($fts)->sum() + ($totalNft = collect($nfts)->sum()); - if (!$total) { + if (! $total) { return; } diff --git a/tests/Feature/Commands/BatchProcessTest.php b/tests/Feature/Commands/BatchProcessTest.php index b64f322..597e80d 100644 --- a/tests/Feature/Commands/BatchProcessTest.php +++ b/tests/Feature/Commands/BatchProcessTest.php @@ -84,15 +84,18 @@ protected function genericBatchProcessTest(TransactionState $txnState, ClaimStat $this->batch->refresh()->load('transaction'); $this->assertEquals([ - 'method' => BeamType::MINT_ON_DEMAND == BeamType::getEnumCase($this->batch->beam_type) ? 'BatchMint' : 'BatchTransfer', + 'method' => BeamType::getEnumCase($this->batch->beam_type) == BeamType::MINT_ON_DEMAND ? 'BatchMint' : 'BatchTransfer', 'state' => TransactionState::PENDING->name, ], Arr::only($this->batch->transaction->toArray(), ['method', 'state'])); resolve(UpdateClaimStatus::class)->handle( - new TransactionUpdated($this->batch->transaction->fill([ - 'state' => $txnState->name, - 'result' => $txnState == TransactionState::FINALIZED ? SystemEventType::EXTRINSIC_SUCCESS->name : SystemEventType::EXTRINSIC_FAILED->name, - ])) + new TransactionUpdated( + event: [], + transaction: $this->batch->transaction->fill([ + 'state' => $txnState->name, + 'result' => $txnState == TransactionState::FINALIZED ? SystemEventType::EXTRINSIC_SUCCESS->name : SystemEventType::EXTRINSIC_FAILED->name, + ]) + ) ); $this->batch->refresh()->load('claims'); diff --git a/tests/Feature/Commands/PruneTest.php b/tests/Feature/Commands/PruneTest.php index 5d4b30f..29b8f5e 100644 --- a/tests/Feature/Commands/PruneTest.php +++ b/tests/Feature/Commands/PruneTest.php @@ -14,8 +14,6 @@ class PruneTest extends TestCaseGraphQL /** * Setup test case. - * - * @return void */ protected function setUp(): void { @@ -24,8 +22,6 @@ protected function setUp(): void /** * Test pruning expired claims. - * - * @return void */ public function test_it_can_prune_expired_claims(): void { @@ -36,7 +32,7 @@ public function test_it_can_prune_expired_claims(): void null, [ 'end' => now()->subDays(config('enjin-platform-beam.prune_expired_claims')), - 'flags_mask' => BeamService::getFlagsValue([['flag'=> 'PRUNABLE']]), + 'flags_mask' => BeamService::getFlagsValue([['flag' => 'PRUNABLE']]), ] ); $this->artisan('model:prune', ['--model' => BeamClaim::resolveClassFqn()]); @@ -45,8 +41,6 @@ public function test_it_can_prune_expired_claims(): void /** * Test pruning immediately. - * - * @return void */ public function test_it_can_prune_immediately(): void { @@ -58,7 +52,7 @@ public function test_it_can_prune_immediately(): void null, [ 'end' => now()->subMinute(1), - 'flags_mask' => BeamService::getFlagsValue([['flag'=> 'PRUNABLE']]), + 'flags_mask' => BeamService::getFlagsValue([['flag' => 'PRUNABLE']]), ] ); $this->artisan('model:prune', ['--model' => BeamClaim::resolveClassFqn()]); @@ -67,8 +61,6 @@ public function test_it_can_prune_immediately(): void /** * Test pruning unexpired claims. - * - * @return void */ public function test_it_cannot_prune_unexpired_claims(): void { @@ -79,7 +71,7 @@ public function test_it_cannot_prune_unexpired_claims(): void null, [ 'end' => now()->addDays(config('enjin-platform-beam.prune_expired_claims')), - 'flags_mask' => BeamService::getFlagsValue([['flag'=> 'PRUNABLE']]), + 'flags_mask' => BeamService::getFlagsValue([['flag' => 'PRUNABLE']]), ] ); $this->artisan('model:prune', ['--model' => BeamClaim::class]); @@ -88,8 +80,6 @@ public function test_it_cannot_prune_unexpired_claims(): void /** * Test pruning with no config. - * - * @return void */ public function test_it_cannot_prune_with_empty_config(): void { @@ -101,7 +91,7 @@ public function test_it_cannot_prune_with_empty_config(): void null, [ 'end' => now()->subDays(365), - 'flags_mask' => BeamService::getFlagsValue([['flag'=> 'PRUNABLE']]), + 'flags_mask' => BeamService::getFlagsValue([['flag' => 'PRUNABLE']]), ] ); $this->artisan('model:prune', ['--model' => BeamClaim::resolveClassFqn()]); diff --git a/tests/Feature/GraphQL/Mutations/AddTokensTest.php b/tests/Feature/GraphQL/Mutations/AddTokensTest.php index 6d60cec..b491cec 100644 --- a/tests/Feature/GraphQL/Mutations/AddTokensTest.php +++ b/tests/Feature/GraphQL/Mutations/AddTokensTest.php @@ -14,9 +14,9 @@ class AddTokensTest extends TestCaseGraphQL { - use SeedBeamData; use HasIntegerRanges; use IntegerRange; + use SeedBeamData; /** * The graphql method. diff --git a/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php b/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php index d8796e5..e23a1a0 100644 --- a/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php @@ -27,8 +27,8 @@ class ClaimBeamTest extends TestCaseGraphQL { - use SeedBeamData; use CreateBeamData; + use SeedBeamData; /** * The graphql method. @@ -138,14 +138,14 @@ function ($attribute, $code, $singleUse, $data) { return CryptoSignatureType::ED25519->name == $data['cryptoSignatureType']; }, function ($attribute, $code, $singleUse, $data) { - return 'code' == $attribute; + return $attribute == 'code'; }, ]); $this->assertCount(2, PassesClaimConditions::getConditionalFunctions()); PassesClaimConditions::removeConditionalFunctions( function ($attribute, $code, $singleUse, $data) { - return 'code' == $attribute; + return $attribute == 'code'; } ); $this->assertCount(1, PassesClaimConditions::getConditionalFunctions()); @@ -182,7 +182,7 @@ function ($attribute, $code, $singleUse, $data) { return CryptoSignatureType::ED25519->name == $data['cryptoSignatureType']; }, function ($attribute, $code, $singleUse, $data) { - return 'code' == $attribute; + return $attribute == 'code'; }, ]); $this->assertNotEmpty(PassesClaimConditions::getConditionalFunctions()); @@ -238,7 +238,7 @@ public function test_it_cannot_claim_beam_with_multiple_conditions_that_fail(): { $functions = collect([ function ($attribute, $code, $singleUse, $data) { - return 'code' == $data[$attribute]; + return $data[$attribute] == 'code'; }, function ($attribute, $code, $singleUse, $data) { return CryptoSignatureType::SR25519->name == $data['cryptoSignatureType'] ? true : 'Signature is not SR25519.'; @@ -447,7 +447,7 @@ public function test_it_will_fail_with_invalid_params_updated_single_use_codes() */ public function signMessage(CryptoSignatureType $type, mixed $keypair, string $message, string $privateKey): string { - if (CryptoSignatureType::SR25519 == $type) { + if ($type == CryptoSignatureType::SR25519) { $signature = (new sr25519())->Sign($keypair, $message); } else { $message = HexConverter::stringToHex($message); @@ -462,7 +462,7 @@ public function signMessage(CryptoSignatureType $type, mixed $keypair, string $m */ protected function getKeyPair(CryptoSignatureType $type = CryptoSignatureType::SR25519): array { - if (CryptoSignatureType::SR25519 == $type) { + if ($type == CryptoSignatureType::SR25519) { $sr = new sr25519(); $keypair = $sr->InitKeyPair(bin2hex(sodium_crypto_sign_publickey(sodium_crypto_sign_keypair()))); $public = HexConverter::prefix($keypair->publicKey); diff --git a/tests/Feature/GraphQL/Mutations/CreateBeamTest.php b/tests/Feature/GraphQL/Mutations/CreateBeamTest.php index 459b4d0..d26e27c 100644 --- a/tests/Feature/GraphQL/Mutations/CreateBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/CreateBeamTest.php @@ -19,8 +19,8 @@ class CreateBeamTest extends TestCaseGraphQL { use CreateBeamData; - use SeedBeamData; use HasIntegerRanges; + use SeedBeamData; /** * The graphql method. @@ -87,7 +87,7 @@ public function test_it_can_create_beam_with_attribute_mint_on_demand(): void $this->genericTestCreateBeam( BeamType::MINT_ON_DEMAND, random_int(1, 20), - [['key' => 'key1', 'value'=> 'value1'], ['key' => 'key2', 'value'=> 'value2']] + [['key' => 'key1', 'value' => 'value1'], ['key' => 'key2', 'value' => 'value2']] ); } @@ -200,7 +200,7 @@ public function test_it_will_fail_with_max_length_attribute_mint_on_demand(): vo $this->generateBeamData( BeamType::MINT_ON_DEMAND, random_int(1, 20), - [['key' => Str::random(256), 'value'=> Str::random(1001)]] + [['key' => Str::random(256), 'value' => Str::random(1001)]] ), true ); diff --git a/tests/Feature/GraphQL/Mutations/ExpireSingleUseCodesTest.php b/tests/Feature/GraphQL/Mutations/ExpireSingleUseCodesTest.php index aa4a528..613ce83 100644 --- a/tests/Feature/GraphQL/Mutations/ExpireSingleUseCodesTest.php +++ b/tests/Feature/GraphQL/Mutations/ExpireSingleUseCodesTest.php @@ -10,8 +10,8 @@ class ExpireSingleUseCodesTest extends TestCaseGraphQL { - use SeedBeamData; use CreateBeamData; + use SeedBeamData; /** * The graphql method. diff --git a/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php b/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php index 72f5090..9b8abb5 100644 --- a/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php @@ -23,9 +23,9 @@ class UpdateBeamTest extends TestCaseGraphQL { - use SeedBeamData; use HasIntegerRanges; use IntegerRange; + use SeedBeamData; /** * The graphql method. @@ -488,7 +488,7 @@ protected function generateBeamData(BeamType $type = BeamType::TRANSFER_TOKEN, i 'end' => Carbon::now()->addDays(20)->toDateTimeString(), 'tokens' => [[ 'type' => $type->name, - 'tokenIds' => BeamType::TRANSFER_TOKEN == $type + 'tokenIds' => $type == BeamType::TRANSFER_TOKEN ? [(string) $this->token->token_chain_id] : [(string) fake()->unique()->numberBetween(100, 10000), fake()->unique()->numberBetween(0, 10) . '..' . fake()->unique()->numberBetween(11, 20)], 'tokenQuantityPerClaim' => random_int(1, $count), diff --git a/tests/Feature/GraphQL/Queries/GetBeamTest.php b/tests/Feature/GraphQL/Queries/GetBeamTest.php index 31a045f..effbe9f 100644 --- a/tests/Feature/GraphQL/Queries/GetBeamTest.php +++ b/tests/Feature/GraphQL/Queries/GetBeamTest.php @@ -43,7 +43,7 @@ public function test_it_can_get_beam_with_single_use_codes(): void 1, false, BeamType::MINT_ON_DEMAND, - ['flags_mask' => BeamService::getFlagsValue([['flag'=> 'SINGLE_USE']])] + ['flags_mask' => BeamService::getFlagsValue([['flag' => 'SINGLE_USE']])] ); $claim = $this->claims->first(); $singleUseCode = encrypt(implode(':', [$claim->code, $this->beam->code, $claim->nonce])); @@ -54,7 +54,7 @@ public function test_it_can_get_beam_with_single_use_codes(): void 1, true, BeamType::MINT_ON_DEMAND, - ['flags_mask' => BeamService::getFlagsValue([['flag'=> 'SINGLE_USE']])] + ['flags_mask' => BeamService::getFlagsValue([['flag' => 'SINGLE_USE']])] ); $claim = $this->claims->first(); $singleUseCode = encrypt(implode(':', [$claim->code, $this->beam->code, $claim->nonce])); diff --git a/tests/Feature/GraphQL/TestCaseGraphQL.php b/tests/Feature/GraphQL/TestCaseGraphQL.php index 4be6d82..1b12e8d 100644 --- a/tests/Feature/GraphQL/TestCaseGraphQL.php +++ b/tests/Feature/GraphQL/TestCaseGraphQL.php @@ -15,8 +15,8 @@ class TestCaseGraphQL extends BaseTestCase { - use CreateCollectionData; use ArraySubsetAsserts; + use CreateCollectionData; /** * The graphql queries. @@ -68,7 +68,7 @@ public function graphql(string $query, array $arguments = [], ?bool $expectError } $validationMessages = collect($result->errors)->map(function ($error) { - if ('validation' == $error->getMessage()) { + if ($error->getMessage() == 'validation') { return $error->getPrevious()->getValidator()->getMessageBag()->getMessages(); } })->all(); @@ -84,9 +84,9 @@ public function graphql(string $query, array $arguments = [], ?bool $expectError throw new ExpectationFailedException($assertMessage); } - if ('validation' === Arr::get($data, 'errors.0.message')) { + if (Arr::get($data, 'errors.0.message') === 'validation') { $data['error'] = Arr::first($result->errors)?->getPrevious()->getValidatorMessages()->toArray(); - } elseif (null !== Arr::get($data, 'errors.0.message')) { + } elseif (Arr::get($data, 'errors.0.message') !== null) { $data['error'] = $data['errors'][0]['message']; } @@ -162,7 +162,7 @@ protected function loadQueries(): void /** * Get package providers. * - * @param mixed $app + * @param mixed $app */ protected function getPackageProviders($app): array { @@ -175,7 +175,7 @@ protected function getPackageProviders($app): array /** * Get package aliases. * - * @param mixed $app + * @param mixed $app */ protected function getPackageAliases($app): array { @@ -185,7 +185,7 @@ protected function getPackageAliases($app): array /** * Define environment. * - * @param mixed $app + * @param mixed $app */ protected function defineEnvironment($app): void { diff --git a/tests/Feature/Traits/CreateBeamData.php b/tests/Feature/Traits/CreateBeamData.php index d30a097..35e2b1f 100644 --- a/tests/Feature/Traits/CreateBeamData.php +++ b/tests/Feature/Traits/CreateBeamData.php @@ -22,7 +22,7 @@ protected function generateBeamData(BeamType $type = BeamType::TRANSFER_TOKEN, i 'flags' => $singleUse, 'tokens' => [[ 'type' => $type->name, - 'tokenIds' => BeamType::TRANSFER_TOKEN == $type + 'tokenIds' => $type == BeamType::TRANSFER_TOKEN ? [(string) $this->token->token_chain_id] : [(string) fake()->unique()->numberBetween(100, 10000), fake()->unique()->numberBetween(0, 10) . '..' . fake()->unique()->numberBetween(11, 20)], 'tokenQuantityPerClaim' => random_int(1, $count), diff --git a/tests/Feature/Traits/CreateCollectionData.php b/tests/Feature/Traits/CreateCollectionData.php index dfe0356..3a69f34 100644 --- a/tests/Feature/Traits/CreateCollectionData.php +++ b/tests/Feature/Traits/CreateCollectionData.php @@ -29,10 +29,6 @@ trait CreateCollectionData /** * Create collection data. - * - * @param string $publicKey - * - * @return void */ public function prepareCollectionData(?string $publicKey = null): void { diff --git a/tests/Feature/Traits/SeedBeamData.php b/tests/Feature/Traits/SeedBeamData.php index a03917a..7fa09d6 100644 --- a/tests/Feature/Traits/SeedBeamData.php +++ b/tests/Feature/Traits/SeedBeamData.php @@ -23,8 +23,6 @@ trait SeedBeamData /** * The beam claims. - * - * @var Collection */ protected Collection $claims; @@ -40,7 +38,7 @@ public function seedBeam(?int $claimsCount = null, bool $isClaimed = false, ?Bea { $states = [ 'collection_id' => $this->collection->id, - ...(!$isClaimed ? ['wallet_public_key' => null, 'claimed_at' => null, 'state' => null] : ['state' => ClaimStatus::PENDING->name]), + ...(! $isClaimed ? ['wallet_public_key' => null, 'claimed_at' => null, 'state' => null] : ['state' => ClaimStatus::PENDING->name]), ...($type ? ['type' => $type->name] : []), ]; diff --git a/tests/TestCase.php b/tests/TestCase.php index c98908e..766f71b 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -29,8 +29,7 @@ protected function getPackageProviders($app) /** * Define environment. * - * @param mixed $app - * + * @param mixed $app * @return void */ protected function defineEnvironment($app) diff --git a/tests/Unit/EventTest.php b/tests/Unit/EventTest.php index d7af7db..82c19f4 100644 --- a/tests/Unit/EventTest.php +++ b/tests/Unit/EventTest.php @@ -20,8 +20,13 @@ use Enjin\Platform\Events\Substrate\MultiTokens\CollectionFrozen; use Enjin\Platform\Events\Substrate\MultiTokens\CollectionThawed; use Enjin\Platform\Events\Substrate\MultiTokens\TokenDestroyed; +use Enjin\Platform\Models\Laravel\Transaction; use Enjin\Platform\Services\Database\WalletService; use Illuminate\Support\Facades\Event; +use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\CollectionDestroyed as CollectionDestroyedPolkadart; +use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\Frozen as CollectionFrozenPolkadart; +use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\Thawed as CollectionThawedPolkadart; +use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\TokenDestroyed as TokenDestroyedPolkadart; class EventTest extends TestCaseGraphQL { @@ -40,27 +45,49 @@ public function test_it_can_listens_to_events(): void { Event::fake(); - event($event = new CollectionDestroyed($this->collection)); + $collectionCreated = CollectionDestroyedPolkadart::fromChain($this->mockPolkadartEvent('MultiTokens', 'CollectionDestroyed', [ + 'collection_id' => $this->collection->id, + 'caller' => 'd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d', + ])); + + event($event = new CollectionDestroyed($collectionCreated)); Event::assertListening(CollectionDestroyed::class, ExpireBeam::class); resolve(ExpireBeam::class)->handle($event); - event($event = new CollectionFrozen($this->collection)); + $collectionFrozen = CollectionFrozenPolkadart::fromChain($this->mockPolkadartEvent('MultiTokens', 'Frozen', [ + 'collection_id' => $this->collection->collection_chain_id, + 'freeze_type' => 'Collection', + ])); + + event($event = new CollectionFrozen($collectionFrozen)); Event::assertListening(CollectionFrozen::class, PauseBeam::class); resolve(PauseBeam::class)->handle($event); - event($event = new CollectionThawed($this->collection)); + $collectionThawed = CollectionThawedPolkadart::fromChain($this->mockPolkadartEvent('MultiTokens', 'Thawed', [ + 'collection_id' => $this->collection->collection_chain_id, + 'freeze_type' => 'Collection', + ])); + + event($event = new CollectionThawed($collectionThawed)); Event::assertListening(CollectionThawed::class, UnpauseBeam::class); resolve(UnpauseBeam::class)->handle($event); - event($event = new PlatformSynced($this->collection)); + event($event = new PlatformSynced()); Event::assertListening(PlatformSynced::class, UpdateClaimCollectionIds::class); resolve(UpdateClaimCollectionIds::class)->handle($event); - event($event = new TransactionUpdated($this->collection)); + $transaction = Transaction::factory()->create(); + event($event = new TransactionUpdated(event: [], transaction: $transaction)); Event::assertListening(TransactionUpdated::class, UpdateClaimStatus::class); resolve(UpdateClaimStatus::class)->handle($event); - event($event = new TokenDestroyed($this->token, $this->wallet)); + $tokenDestroyed = TokenDestroyedPolkadart::fromChain($this->mockPolkadartEvent('MultiTokens', 'TokenDestroyed', [ + 'collection_id' => $this->collection->collection_chain_id, + 'token_id' => $this->token->token_chain_id, + 'caller' => $this->wallet->public_key, + ])); + + event($event = new TokenDestroyed($tokenDestroyed)); $this->collection->update([ 'max_token_supply' => 100, 'force_single_mint' => false, @@ -85,4 +112,18 @@ public function test_it_can_claim_job(): void $job->handle(resolve(BatchService::class), resolve(WalletService::class)); $this->assertLessThan($this->claims->count(), BeamClaim::where('beam_id', $this->beam->id)->claimable()->count()); } + + protected function mockPolkadartEvent(string $module, string $name, array $data): array + { + return [ + 'phase' => [ + 'ApplyExtrinsic' => 1, + ], + 'event' => [ + $module => [ + $name => $data, + ], + ], + ]; + } } From 0e6c78f0481a38f8b80e8970017179a604cd3c25 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Thu, 6 Jun 2024 18:43:58 -0300 Subject: [PATCH 02/10] Fixes composer fix --- composer.json | 2 +- tests/Feature/GraphQL/Mutations/AddTokensTest.php | 8 ++++---- tests/Feature/GraphQL/Mutations/ClaimBeamTest.php | 3 +-- tests/Feature/GraphQL/Mutations/CreateBeamTest.php | 1 - tests/Feature/GraphQL/Mutations/UpdateBeamTest.php | 7 +++---- tests/Feature/GraphQL/TestCaseGraphQL.php | 8 ++++---- tests/Unit/ClaimProbabilityTest.php | 1 + tests/Unit/EventTest.php | 2 +- 8 files changed, 15 insertions(+), 17 deletions(-) diff --git a/composer.json b/composer.json index 4aa596c..ed6f0cb 100644 --- a/composer.json +++ b/composer.json @@ -46,7 +46,7 @@ "scripts": { "build-sr25519": "cd vendor/gmajor/sr25519-bindings/go && go build -buildmode=c-shared -o sr25519.so . && mv sr25519.so ../src/Crypto/sr25519.so", "analyse": "vendor/bin/phpstan analyse", - "fix": "vendor/bin/php-cs-fixer fix", + "fix": "vendor/bin/pint", "test": "vendor/bin/phpunit", "test-coverage": "vendor/bin/phpunit --coverage-html ../../temp/coverage", "post-autoload-dump": [ diff --git a/tests/Feature/GraphQL/Mutations/AddTokensTest.php b/tests/Feature/GraphQL/Mutations/AddTokensTest.php index b491cec..13a6706 100644 --- a/tests/Feature/GraphQL/Mutations/AddTokensTest.php +++ b/tests/Feature/GraphQL/Mutations/AddTokensTest.php @@ -39,7 +39,7 @@ public function test_it_add_tokens(): void $this->method, [ 'code' => $this->beam->code, - 'tokens' => [['tokenIds' => ['1..5'], 'type' => BeamType::MINT_ON_DEMAND->name]], + 'tokens' => [['tokenIds' => ['1..5'], 'type' => BeamType::MINT_ON_DEMAND->name]], ] ); $this->assertTrue($response); @@ -53,7 +53,7 @@ public function test_it_can_add_token_with_attributes(): void $this->method, [ 'code' => $this->beam->code, - 'tokens' => [ + 'tokens' => [ [ 'tokenIds' => ['1..5'], 'type' => BeamType::MINT_ON_DEMAND->name, @@ -104,7 +104,7 @@ public function test_it_will_fail_with_token_exist_in_beam(): void $this->method, [ 'code' => $this->beam->code, - 'tokens' => [['tokenIds' => [$claim->token_chain_id], 'type' => BeamType::TRANSFER_TOKEN->name]], + 'tokens' => [['tokenIds' => [$claim->token_chain_id], 'type' => BeamType::TRANSFER_TOKEN->name]], ], true ); @@ -225,7 +225,7 @@ public function test_it_will_fail_with_invalid_parameters(): void $response = $this->graphql($this->method, [ 'code' => Str::random(1500), - 'tokens' => [['tokenIds' => ['1..5'], 'type' => BeamType::MINT_ON_DEMAND->name]], + 'tokens' => [['tokenIds' => ['1..5'], 'type' => BeamType::MINT_ON_DEMAND->name]], ], true); $this->assertArraySubset( ['code' => ['The code field must not be greater than 1024 characters.']], diff --git a/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php b/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php index e23a1a0..b49a2f5 100644 --- a/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/ClaimBeamTest.php @@ -69,7 +69,6 @@ public function test_it_can_claim_updated_single_use_codes(): void $response = $this->graphql('GetSingleUseCodes', ['code' => $code]); $this->assertNotEmpty($response['totalCount']); - Queue::fake(); $response = $this->graphql($this->method, [ 'code' => Arr::get($response, 'edges.0.node.code'), @@ -488,7 +487,7 @@ protected function genericClaimTest(CryptoSignatureType $type = CryptoSignatureT 'account' => $publicKey, ]); $this->assertNotEmpty($response['message']); - if (!$singleUseCode) { + if (! $singleUseCode) { $this->assertEquals(1, $this->beam->scans()->count()); } diff --git a/tests/Feature/GraphQL/Mutations/CreateBeamTest.php b/tests/Feature/GraphQL/Mutations/CreateBeamTest.php index d26e27c..2c102b5 100644 --- a/tests/Feature/GraphQL/Mutations/CreateBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/CreateBeamTest.php @@ -276,7 +276,6 @@ public function test_it_will_fail_with_invalid_parameters(): void ); $this->assertArraySubset(['image' => ['The image field must be a valid URL.']], $response['error']); - $now = Carbon::now(); $response = $this->graphql( $this->method, diff --git a/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php b/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php index 9b8abb5..071414a 100644 --- a/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php +++ b/tests/Feature/GraphQL/Mutations/UpdateBeamTest.php @@ -246,7 +246,6 @@ public function test_it_will_fail_existing_tokens(): void $response['error'] ); - $updates = array_merge( $updates, ['tokens' => [['tokenIds' => [$token->token_chain_id . '..' . $token->token_chain_id], 'type' => BeamType::MINT_ON_DEMAND->name]]] @@ -392,7 +391,7 @@ public function test_it_will_fail_with_invalid_dates(): void */ public function test_it_can_update_beam_flags(): void { - $this->assertTrue(!$this->beam->hasFlag(BeamFlag::PAUSED)); + $this->assertTrue(! $this->beam->hasFlag(BeamFlag::PAUSED)); $response = $this->graphql( $this->method, @@ -411,7 +410,7 @@ public function test_it_can_update_beam_flags(): void */ public function test_it_can_update_beam_with_empty_flags(): void { - $this->assertTrue(!$this->beam->hasFlag(BeamFlag::PAUSED)); + $this->assertTrue(! $this->beam->hasFlag(BeamFlag::PAUSED)); $response = $this->graphql( $this->method, @@ -429,7 +428,7 @@ public function test_it_can_update_beam_with_empty_flags(): void $this->assertTrue($response); $this->beam->refresh(); - $this->assertTrue(!$this->beam->hasFlag(BeamFlag::PAUSED)); + $this->assertTrue(! $this->beam->hasFlag(BeamFlag::PAUSED)); } /** diff --git a/tests/Feature/GraphQL/TestCaseGraphQL.php b/tests/Feature/GraphQL/TestCaseGraphQL.php index 1b12e8d..e5b7904 100644 --- a/tests/Feature/GraphQL/TestCaseGraphQL.php +++ b/tests/Feature/GraphQL/TestCaseGraphQL.php @@ -40,7 +40,7 @@ protected function setUp(): void { parent::setUp(); - if (!self::$initialized) { + if (! self::$initialized) { $this->artisan('migrate:fresh'); $this->loadQueries(); @@ -60,7 +60,7 @@ public function graphql(string $query, array $arguments = [], ?bool $expectError $assertMessage = null; - if (!$expectError && isset($data['errors'])) { + if (! $expectError && isset($data['errors'])) { $appendErrors = ''; if (isset($data['errors'][0]['trace'])) { @@ -90,7 +90,7 @@ public function graphql(string $query, array $arguments = [], ?bool $expectError $data['error'] = $data['errors'][0]['message']; } - if ($expectError && !isset($data['error'])) { + if ($expectError && ! isset($data['error'])) { throw new ExpectationFailedException('Test expected to yield an error, however returned successfully with the following: ' . json_encode($data)); } @@ -127,7 +127,7 @@ protected function httpGraphql(string $method, array $options = [], array $heade } $assertMessage = null; - if (!$expectErrors && isset($result['errors'])) { + if (! $expectErrors && isset($result['errors'])) { $appendErrors = ''; if (isset($result['errors'][0]['trace'])) { $appendErrors = "\n\n" . $this->formatSafeTrace($result['errors'][0]['trace']); diff --git a/tests/Unit/ClaimProbabilityTest.php b/tests/Unit/ClaimProbabilityTest.php index 2afcbef..fec974d 100644 --- a/tests/Unit/ClaimProbabilityTest.php +++ b/tests/Unit/ClaimProbabilityTest.php @@ -14,6 +14,7 @@ class ClaimProbabilityTest extends TestCaseGraphQL use CreateCollectionData; protected Model $beam; + protected ClaimProbabilities $probabilities; protected function setUp(): void diff --git a/tests/Unit/EventTest.php b/tests/Unit/EventTest.php index 82c19f4..c0e8679 100644 --- a/tests/Unit/EventTest.php +++ b/tests/Unit/EventTest.php @@ -22,11 +22,11 @@ use Enjin\Platform\Events\Substrate\MultiTokens\TokenDestroyed; use Enjin\Platform\Models\Laravel\Transaction; use Enjin\Platform\Services\Database\WalletService; -use Illuminate\Support\Facades\Event; use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\CollectionDestroyed as CollectionDestroyedPolkadart; use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\Frozen as CollectionFrozenPolkadart; use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\Thawed as CollectionThawedPolkadart; use Enjin\Platform\Services\Processor\Substrate\Codec\Polkadart\Events\MultiTokens\TokenDestroyed as TokenDestroyedPolkadart; +use Illuminate\Support\Facades\Event; class EventTest extends TestCaseGraphQL { From d45844bf714ab416f8b5563bcc8f0589df41d583 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Thu, 6 Jun 2024 18:44:44 -0300 Subject: [PATCH 03/10] Removes cs fixer --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ed6f0cb..1493aca 100644 --- a/composer.json +++ b/composer.json @@ -72,7 +72,7 @@ "prefer-stable": true, "require-dev": { "dms/phpunit-arraysubset-asserts": "dev-master", - "friendsofphp/php-cs-fixer": "^3.0", + "laravel/pint": "^1.16", "nunomaduro/collision": "^7.0", "nunomaduro/larastan": "^2.0", "orchestra/testbench": "^8.0", From f52221fcdd60227f87f901ea602cbf92efdd9d35 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Thu, 6 Jun 2024 18:48:59 -0300 Subject: [PATCH 04/10] Fix dependency --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 1493aca..60cb72f 100644 --- a/composer.json +++ b/composer.json @@ -69,7 +69,7 @@ } }, "minimum-stability": "dev", - "prefer-stable": true, + "prefer-stable": false, "require-dev": { "dms/phpunit-arraysubset-asserts": "dev-master", "laravel/pint": "^1.16", From 45a779e698cb055075e5b2b08f36571bab29bd6b Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Fri, 7 Jun 2024 10:40:22 -0300 Subject: [PATCH 05/10] Update events --- src/Events/BeamBatchTransactionCreated.php | 9 +++++---- src/Events/BeamClaimPending.php | 2 +- src/Events/CreateBeamClaimsCompleted.php | 8 ++++---- src/Events/TokensAdded.php | 9 ++++++--- src/Jobs/CreateBeamClaims.php | 2 +- src/Services/BeamService.php | 4 ++-- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/Events/BeamBatchTransactionCreated.php b/src/Events/BeamBatchTransactionCreated.php index 7b1e216..9a1206d 100644 --- a/src/Events/BeamBatchTransactionCreated.php +++ b/src/Events/BeamBatchTransactionCreated.php @@ -5,20 +5,21 @@ use Enjin\Platform\Beam\Channels\PlatformBeamChannel; use Enjin\Platform\Channels\PlatformAppChannel; use Enjin\Platform\Events\PlatformBroadcastEvent; +use Illuminate\Database\Eloquent\Model; class BeamBatchTransactionCreated extends PlatformBroadcastEvent { /** * Creates a new event instance. */ - public function __construct(string $beamId, string $collectionId, int $transactionId) + public function __construct(mixed $event, ?Model $transaction, ?array $extra) { parent::__construct(); $this->broadcastData = [ - 'beamId' => $beamId, - 'collectionId' => $collectionId, - 'transactionId' => $transactionId, + 'beamId' => $event['beam_id'], + 'collectionId' => $event['collection_id'], + 'transactionId' => $transaction?->id, ]; $this->broadcastChannels = [ diff --git a/src/Events/BeamClaimPending.php b/src/Events/BeamClaimPending.php index d8d0394..ddb6bf3 100644 --- a/src/Events/BeamClaimPending.php +++ b/src/Events/BeamClaimPending.php @@ -18,7 +18,7 @@ public function __construct(array $claim) parent::__construct(); $this->broadcastData = array_merge( - //idempotency_key needs to be present both since for some cases its not set in $claim['beam'] + //idempotency_key needs to be present both since for some cases it's not set in $claim['beam'] Arr::only($claim['beam'], ['code', 'collection_chain_id', 'idempotency_key']), Arr::only($claim, ['wallet_public_key', 'claimed_at', 'state', 'token_chain_id', 'idempotency_key']), [ diff --git a/src/Events/CreateBeamClaimsCompleted.php b/src/Events/CreateBeamClaimsCompleted.php index d039b9e..8bd22a3 100644 --- a/src/Events/CreateBeamClaimsCompleted.php +++ b/src/Events/CreateBeamClaimsCompleted.php @@ -6,21 +6,21 @@ use Enjin\Platform\Channels\PlatformAppChannel; use Enjin\Platform\Events\PlatformBroadcastEvent; use Illuminate\Broadcasting\Channel; -use Illuminate\Support\Arr; +use Illuminate\Database\Eloquent\Model; class CreateBeamClaimsCompleted extends PlatformBroadcastEvent { /** * Creates a new event instance. */ - public function __construct(array $data) + public function __construct(mixed $event, ?Model $transaction, ?array $extra) { parent::__construct(); - $this->broadcastData = $data; + $this->broadcastData = $event; $this->broadcastChannels = [ - new Channel('beam;' . Arr::get($data, 'code')), + new Channel("beam;{$event['code']}"), new PlatformAppChannel(), new PlatformBeamChannel(), ]; diff --git a/src/Events/TokensAdded.php b/src/Events/TokensAdded.php index 93c64bf..1b42955 100644 --- a/src/Events/TokensAdded.php +++ b/src/Events/TokensAdded.php @@ -6,18 +6,21 @@ use Enjin\Platform\Channels\PlatformAppChannel; use Enjin\Platform\Events\PlatformBroadcastEvent; use Illuminate\Broadcasting\Channel; +use Illuminate\Database\Eloquent\Model; class TokensAdded extends PlatformBroadcastEvent { /** * Create a new event instance. */ - public function __construct(array $data) + public function __construct(mixed $event, ?Model $transaction, ?array $extra, array $data) { parent::__construct(); - $this->broadcastData = $data; + + $this->broadcastData = $event; + $this->broadcastChannels = [ - new Channel("beam;{$this->broadcastData['code']}"), + new Channel("beam;{$event['code']}"), new PlatformAppChannel(), new PlatformBeamChannel(), ]; diff --git a/src/Jobs/CreateBeamClaims.php b/src/Jobs/CreateBeamClaims.php index e4cf4ab..26690b4 100644 --- a/src/Jobs/CreateBeamClaims.php +++ b/src/Jobs/CreateBeamClaims.php @@ -39,7 +39,7 @@ public function handle(): void ->pluck('beam_id', 'beam_id') ->each(function ($beamId) { if ($beam = Beam::select('id', 'code')->find($beamId)) { - event(new CreateBeamClaimsCompleted($beam->toArray())); + CreateBeamClaimsCompleted::safeBroadcast(event: $beam->toArray()); } }); diff --git a/src/Services/BeamService.php b/src/Services/BeamService.php index e0ac889..4797006 100644 --- a/src/Services/BeamService.php +++ b/src/Services/BeamService.php @@ -114,7 +114,7 @@ public function updateByCode(string $code, array $values): Model self::key($beam->code), $this->createClaims($tokens, $beam) ); - TokensAdded::dispatch(['beamCode' => $beam->code, 'code' => $code, 'tokenIds' => collect($tokens)->pluck('tokenIds')->all()]); + TokensAdded::safeBroadcast(event: ['beamCode' => $beam->code, 'code' => $code, 'tokenIds' => collect($tokens)->pluck('tokenIds')->all()]); } event(new BeamUpdated($beam)); @@ -134,7 +134,7 @@ public function addTokens(string $code, array $tokens): bool self::key($beam->code), $this->createClaims($tokens, $beam) ); - TokensAdded::dispatch(['beamCode' => $beam->code, 'code' => $code, 'tokenIds' => collect($tokens)->pluck('tokenIds')->all()]); + TokensAdded::safeBroadcast(event: ['beamCode' => $beam->code, 'code' => $code, 'tokenIds' => collect($tokens)->pluck('tokenIds')->all()]); return true; } From fe1692b5ba414a30119b9e981cb12e86ae375aed Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Fri, 7 Jun 2024 10:42:41 -0300 Subject: [PATCH 06/10] Fixes --- src/Events/TokensAdded.php | 2 +- tests/Feature/GraphQL/Mutations/AddTokensTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Events/TokensAdded.php b/src/Events/TokensAdded.php index 1b42955..3c63baf 100644 --- a/src/Events/TokensAdded.php +++ b/src/Events/TokensAdded.php @@ -13,7 +13,7 @@ class TokensAdded extends PlatformBroadcastEvent /** * Create a new event instance. */ - public function __construct(mixed $event, ?Model $transaction, ?array $extra, array $data) + public function __construct(mixed $event, ?Model $transaction, ?array $extra) { parent::__construct(); diff --git a/tests/Feature/GraphQL/Mutations/AddTokensTest.php b/tests/Feature/GraphQL/Mutations/AddTokensTest.php index 13a6706..9167dcb 100644 --- a/tests/Feature/GraphQL/Mutations/AddTokensTest.php +++ b/tests/Feature/GraphQL/Mutations/AddTokensTest.php @@ -48,7 +48,6 @@ public function test_it_add_tokens(): void public function test_it_can_add_token_with_attributes(): void { - Event::fake(); $response = $this->graphql( $this->method, [ @@ -65,6 +64,7 @@ public function test_it_can_add_token_with_attributes(): void ], ], ); + $this->assertTrue($response); Event::assertDispatched(TokensAdded::class); } From f8f3f04a77f51fce41f04da056529d3d3b68a509 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Fri, 7 Jun 2024 10:47:43 -0300 Subject: [PATCH 07/10] Changes --- src/Services/BeamService.php | 2 +- tests/Feature/GraphQL/Mutations/AddTokensTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Services/BeamService.php b/src/Services/BeamService.php index 4797006..022f35d 100644 --- a/src/Services/BeamService.php +++ b/src/Services/BeamService.php @@ -368,7 +368,7 @@ public function removeTokens(string $code, array $tokens): bool if ($tokens) { $this->probability->removeTokens($code, $tokens); - TokensRemoved::dispatch(['code' => $code, 'tokenIds' => $tokens]); + TokensRemoved::safeBroadcast(event: ['code' => $code, 'tokenIds' => $tokens]); } return true; diff --git a/tests/Feature/GraphQL/Mutations/AddTokensTest.php b/tests/Feature/GraphQL/Mutations/AddTokensTest.php index 9167dcb..13a6706 100644 --- a/tests/Feature/GraphQL/Mutations/AddTokensTest.php +++ b/tests/Feature/GraphQL/Mutations/AddTokensTest.php @@ -48,6 +48,7 @@ public function test_it_add_tokens(): void public function test_it_can_add_token_with_attributes(): void { + Event::fake(); $response = $this->graphql( $this->method, [ @@ -64,7 +65,6 @@ public function test_it_can_add_token_with_attributes(): void ], ], ); - $this->assertTrue($response); Event::assertDispatched(TokensAdded::class); } From b91563010fd3a93c1027f538e70dda2d1695da97 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Tue, 18 Jun 2024 17:51:08 +0400 Subject: [PATCH 08/10] Update BeamBatchTransactionCreated.php Signed-off-by: Leonardo Custodio --- src/Events/BeamBatchTransactionCreated.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Events/BeamBatchTransactionCreated.php b/src/Events/BeamBatchTransactionCreated.php index 9a1206d..70eed4f 100644 --- a/src/Events/BeamBatchTransactionCreated.php +++ b/src/Events/BeamBatchTransactionCreated.php @@ -12,7 +12,7 @@ class BeamBatchTransactionCreated extends PlatformBroadcastEvent /** * Creates a new event instance. */ - public function __construct(mixed $event, ?Model $transaction, ?array $extra) + public function __construct(mixed $event, ?Model $transaction = null, ?array $extra = null) { parent::__construct(); From d06a33378c1a12825749f03eeb4e814707988a86 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Tue, 18 Jun 2024 17:51:39 +0400 Subject: [PATCH 09/10] Update CreateBeamClaimsCompleted.php Signed-off-by: Leonardo Custodio --- src/Events/CreateBeamClaimsCompleted.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Events/CreateBeamClaimsCompleted.php b/src/Events/CreateBeamClaimsCompleted.php index 8bd22a3..dd3e9c3 100644 --- a/src/Events/CreateBeamClaimsCompleted.php +++ b/src/Events/CreateBeamClaimsCompleted.php @@ -13,7 +13,7 @@ class CreateBeamClaimsCompleted extends PlatformBroadcastEvent /** * Creates a new event instance. */ - public function __construct(mixed $event, ?Model $transaction, ?array $extra) + public function __construct(mixed $event, ?Model $transaction = null, ?array $extra = null) { parent::__construct(); From 76aed8f63704514cf3a9a11a32b71ca1ed7bdfe4 Mon Sep 17 00:00:00 2001 From: Leonardo Custodio Date: Tue, 18 Jun 2024 17:52:12 +0400 Subject: [PATCH 10/10] Update TokensAdded.php Signed-off-by: Leonardo Custodio --- src/Events/TokensAdded.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Events/TokensAdded.php b/src/Events/TokensAdded.php index 3c63baf..f4b0a2f 100644 --- a/src/Events/TokensAdded.php +++ b/src/Events/TokensAdded.php @@ -13,7 +13,7 @@ class TokensAdded extends PlatformBroadcastEvent /** * Create a new event instance. */ - public function __construct(mixed $event, ?Model $transaction, ?array $extra) + public function __construct(mixed $event, ?Model $transaction = null, ?array $extra = null) { parent::__construct();