Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PLA-1939] Refactor max token count and supply rule #93

Merged
merged 6 commits into from
Aug 28, 2024

Conversation

enjinabner
Copy link
Contributor

@enjinabner enjinabner commented Aug 21, 2024

PR Type

Enhancement, Bug fix, Tests


Description

  • Refactored the MaxTokenCount rule to ensure unique token validation and efficient processing using LazyCollection.
  • Simplified the MaxTokenSupply rule by removing unnecessary dependencies and ensuring validation against the total circulating supply.
  • Updated validation messages to specify limits for unique tokens.
  • Enhanced test coverage for CreateBeam and UpdateBeam mutations to reflect new validation logic and messages.

Changes walkthrough 📝

Relevant files
Enhancement
validation.php
Update validation message for max token supply                     

lang/en/validation.php

  • Updated validation message for max_token_supply to specify unique
    tokens.
  • +1/-1     
    MaxTokenCount.php
    Refactor max token count validation logic                               

    src/Rules/MaxTokenCount.php

  • Refactored logic to ensure unique token validation.
  • Introduced checks for existing tokens and claims.
  • Utilized LazyCollection for efficient range processing.
  • +94/-25 
    MaxTokenSupply.php
    Simplify and enhance max token supply validation                 

    src/Rules/MaxTokenSupply.php

  • Simplified logic for checking token supply limits.
  • Removed unnecessary model dependencies.
  • Ensured validation against total circulating supply.
  • +62/-83 
    Tests
    CreateBeamTest.php
    Update tests for CreateBeam with new validation logic       

    tests/Feature/GraphQL/Mutations/CreateBeamTest.php

  • Updated test assertions to reflect new validation messages.
  • Ensured tests cover edge cases for token count and supply limits.
  • +7/-9     
    UpdateBeamTest.php
    Refactor UpdateBeam tests to match validation updates       

    tests/Feature/GraphQL/Mutations/UpdateBeamTest.php

  • Removed redundant test setup code.
  • Adjusted test cases to align with updated validation rules.
  • +0/-41   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    @enjinabner enjinabner added the bug Something isn't working label Aug 21, 2024
    @enjinabner enjinabner self-assigned this Aug 21, 2024
    @github-actions github-actions bot added enhancement New feature or request tests Bug fix labels Aug 21, 2024
    Copy link

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Complexity
    The validation logic in MaxTokenCount has significantly increased in complexity, making it harder to maintain and understand. Consider refactoring to simplify the logic or breaking it down into smaller, more manageable methods.

    Performance Concern
    The use of multiple nested loops and queries within the validation method could lead to performance issues, especially with large data sets. Review and optimize the data handling and querying strategy.

    Logic Redundancy
    There appears to be redundant checks and calculations related to token counts and ranges that could be streamlined or optimized.

    Copy link

    github-actions bot commented Aug 21, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Maintainability
    Simplify the method logic by using early returns to reduce nesting

    Refactor the nested if conditions to reduce complexity and improve readability by
    using early returns or guard clauses.

    src/Rules/MaxTokenCount.php [42-50]

    -if ($this->collectionId
    -    && ($collection = Collection::withCount('tokens')->firstWhere(['collection_chain_id' => $this->collectionId]))
    -    && ! is_null($this->limit = $collection->max_token_count)
    -) {
    -    if ($this->limit == 0) {
    -        $fail('enjin-platform-beam::validation.max_token_count')->translate(['limit' => $this->limit]);
    -        return;
    -    }
    -    ...
    +if (!$this->collectionId) {
    +    return;
     }
    +$collection = Collection::withCount('tokens')->firstWhere(['collection_chain_id' => $this->collectionId]);
    +if (!$collection || is_null($this->limit = $collection->max_token_count)) {
    +    return;
    +}
    +if ($this->limit == 0) {
    +    $fail('enjin-platform-beam::validation.max_token_count')->translate(['limit' => $this->limit]);
    +    return;
    +}
    +...
     
    Suggestion importance[1-10]: 9

    Why: The suggestion significantly improves code readability and maintainability by reducing nested conditions, making the logic clearer and easier to follow.

    9
    Enhancement
    Use higher-level file handling methods for better readability and reliability

    Replace the manual file handling with Laravel's higher-level file handling methods
    to simplify the code and improve error handling.

    src/Rules/MaxTokenCount.php [72-78]

    -$handle = fopen($data['tokenIdDataUpload']->getPathname(), 'r');
    -while (($line = fgets($handle)) !== false) {
    -    if (! $this->tokenIdExists($tokens->all(), $tokenId = trim($line))) {
    +$file = new SplFileObject($data['tokenIdDataUpload']->getPathname());
    +while (!$file->eof()) {
    +    $tokenId = trim($file->fgets());
    +    if (! $this->tokenIdExists($tokens->all(), $tokenId)) {
             $tokens->push($tokenId);
         }
     }
    -fclose($handle);
    +$file = null;  # Automatically closes the file
     
    Suggestion importance[1-10]: 8

    Why: The suggestion improves code readability and reliability by using Laravel's higher-level file handling methods, which also enhance error handling and resource management.

    8
    Performance
    Improve efficiency by reusing a collection variable instead of recreating it

    Replace the direct usage of collect($this->data['tokens']) with a variable
    assignment at the beginning of the method to avoid multiple collection creations,
    which can be inefficient.

    src/Rules/MaxTokenCount.php [64-69]

    -$tokens = collect($this->data['tokens'])
    +$tokensData = collect($this->data['tokens']);
    +$tokens = $tokensData
                 ->filter(fn ($data) => !empty(Arr::get($data, 'tokenIds')))
                 ->pluck('tokenIds')
                 ->flatten();
     ...
    -collect($this->data['tokens'])
    +$tokensData
                 ->filter(fn ($data) => !empty(Arr::get($data, 'tokenIdDataUpload')))
                 ->map(function ($data) use ($tokens) {
                     ...
                 });
     
    Suggestion importance[1-10]: 7

    Why: The suggestion improves performance by avoiding multiple collection creations, which can be inefficient. It enhances code readability and maintainability by reducing redundancy.

    7
    Optimize the use of collections to reduce unnecessary conditional checks

    Use Laravel's collection methods more effectively to simplify the code and improve
    performance.

    src/Rules/MaxTokenCount.php [89-97]

     $integers = $integers->diff($existingTokens);
    -if ($integers->count()) {
    -    $existingClaimsCount = BeamClaim::where('collection_id', $collection->id)
    -        ->whereIn('token_chain_id', $integers)
    -        ->claimable()
    -        ->pluck('token_chain_id');
    -    $createTokenTotal = $integers->diff($existingClaimsCount)->count();
    -}
    +$existingClaimsCount = BeamClaim::where('collection_id', $collection->id)
    +    ->whereIn('token_chain_id', $integers)
    +    ->claimable()
    +    ->pluck('token_chain_id');
    +$createTokenTotal = $integers->diff($existingClaimsCount)->count();
     
    Suggestion importance[1-10]: 6

    Why: The suggestion optimizes performance by removing unnecessary conditional checks, although the improvement is minor as it only slightly reduces complexity.

    6

    @enjinabner enjinabner merged commit d2425ac into master Aug 28, 2024
    5 checks passed
    @enjinabner enjinabner deleted the feature/pla-1939/max-token-count-validation branch August 28, 2024 00:39
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    Bug fix bug Something isn't working enhancement New feature or request Review effort [1-5]: 4 tests
    Development

    Successfully merging this pull request may close these issues.

    2 participants