Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Hash Laravel Package

dynamophp/hash

Generate a deterministic float hash for any string mapped to the range 0–360. Uses a primary hash (e.g., SHA-256), then converts selected leading/trailing characters into a numeric value within the interval.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require baptistecontreras/dynamo-php-hash
    

    Add the package to composer.json under require.

  2. Basic Usage:

    use BaptisteContreras\DynamoPHPHash\Hash;
    
    $angle = Hash::generate('example-string');
    // Returns a float between 0 and 360
    
  3. First Use Case: Generate a consistent angle for UI elements (e.g., circular progress bars, dynamic avatars):

    $userAngle = Hash::generate(auth()->user()->email);
    $style = "transform: rotate({$userAngle}deg);";
    

Implementation Patterns

Core Workflows

  1. Deterministic Angle Generation:

    $hash = Hash::generate($inputString);
    // Use $hash for circular layouts, color hues, or directional logic
    
  2. Custom Hash Algorithm:

    $hash = Hash::generate($input, 'sha1'); // Override default 'sha256'
    
  3. Laravel Service Binding: Register the service in AppServiceProvider:

    $this->app->singleton('hash', function () {
        return new Hash(algorithm: 'sha256', x: 5, y: 5);
    });
    

    Use via dependency injection:

    public function __construct(private Hash $hash) {}
    
  4. Model Events: Attach to created events for dynamic attribute generation:

    public function created(Model $model) {
        $model->angle = Hash::generate($model->id);
        $model->save();
    }
    
  5. Caching: Cache results for static inputs (e.g., product IDs):

    $angle = Cache::remember("hash_{$productId}", now()->addHours(1), function () use ($productId) {
        return Hash::generate($productId);
    });
    

Integration Tips

  • Blade Directives:

    @php
        $dynamicStyle = "background-color: hsl({{ Hash::generate($user->name) }}, 100%, 50%)";
    @endphp
    <div style="{{ $dynamicStyle }}">...</div>
    
  • API Responses:

    return response()->json([
        'data' => $items,
        'meta' => [
            'angles' => collect($items)->map(fn($item) => Hash::generate($item->id)),
        ],
    ]);
    
  • Testing:

    public function test_hash_reproducibility() {
        $this->assertEquals(123.45, Hash::generate('test')); // Replace with actual expected value
    }
    
  • Query Scopes: Filter records by hashed ranges (application-layer filtering):

    public function scopeInAngleRange($query, $min, $max) {
        return $query->where(function($q) use ($min, $max) {
            $q->where('id', '>=', $min)
              ->orWhere('id', '<=', $max);
        })->get()->filter(function($item) use ($min, $max) {
            return Hash::generate($item->id) >= $min && Hash::generate($item->id) <= $max;
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Floating-Point Precision:

    • Direct comparisons may fail due to tiny precision differences.
    • Fix: Round results for equality checks:
      $rounded = round(Hash::generate($input), 2);
      $this->assertEquals($rounded, 123.45);
      
  2. Non-Uniform Distribution:

    • SHA-256 may produce skewed results for certain inputs.
    • Fix: Test distribution with a large dataset (e.g., 10,000 inputs) and adjust X/Y parameters if needed.
  3. Empty/Null Inputs:

    • Hash::generate(null) or Hash::generate('') returns 0.0.
    • Fix: Validate inputs or handle edge cases:
      $input = $input ?? 'default-fallback';
      
  4. Performance Under Load:

    • Hashing overhead may impact high-throughput operations.
    • Fix: Cache results aggressively or use a lighter algorithm (e.g., sha1).
  5. Database Storage:

    • Storing floats in databases may cause precision loss.
    • Fix: Use DECIMAL(6,2) for angles or store as integers (e.g., intval($hash * 100)).
  6. Collisions:

    • Two different inputs may produce identical hashes.
    • Fix: Add a small random offset for critical use cases:
      $angle = Hash::generate($input) + (rand() / 1000);
      

Debugging Tips

  • Log Hash Values:
    \Log::debug("Hash for '{$input}': " . Hash::generate($input));
    
  • Visualize Distribution: Use a script to plot 1,000+ hashes to check for clustering:
    $hashes = collect(range(1, 1000))->map(fn($i) => Hash::generate("test-$i"));
    $hashes->sort()->unique()->count(); // Check for collisions
    

Configuration Quirks

  • Custom Parameters: The constructor accepts x (first characters) and y (last characters) to tune the hash:

    $hash = new Hash(algorithm: 'sha256', x: 8, y: 4);
    
    • Higher x/y values increase entropy but may reduce precision.
    • Lower values may cause collisions or skewed distributions.
  • Algorithm Limitations:

    • Not all PHP hash algorithms are supported (e.g., ripemd128 may not work).
    • Fix: Stick to widely supported algorithms like sha256, sha1, or md5.

Extension Points

  1. Custom Transformations: Extend the class to add methods like toHex() or toColor():

    class ExtendedHash extends Hash {
        public function toHex(): string {
            return sprintf('#%06x', (int)round($this->generate() / 360 * 0xFFFFFF));
        }
    }
    
  2. Alternative Ranges: Override the transformation logic to support other ranges (e.g., [0;100]):

    class CustomRangeHash extends Hash {
        protected function transform(string $hash): float {
            return (float) $hash * 100 / pow(2, 256);
        }
    }
    
  3. Input Normalization: Preprocess inputs for consistency (e.g., lowercase, trim):

    class NormalizedHash extends Hash {
        public function generate(string $input): float {
            return parent::generate(mb_strtolower(trim($input), 'UTF-8'));
        }
    }
    

Laravel-Specific Tips

  • Service Container Binding: Bind the service with custom parameters:

    $this->app->singleton(Hash::class, function () {
        return new Hash(algorithm: config('app.hash_algorithm'), x: config('app.hash_x'), y: config('app.hash_y'));
    });
    
  • Environment Configuration: Add to config/app.php:

    'hash' => [
        'algorithm' => env('HASH_ALGORITHM', 'sha256'),
        'x' => env('HASH_X', 5),
        'y' => env('HASH_Y', 5),
    ],
    
  • Facade for Convenience: Create a facade to simplify usage:

    // app/Facades/Hash.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class Hash extends Facade {
        protected static function getFacadeAccessor() {
            return 'hash';
        }
    }
    

    Usage:

    use App\Facades\Hash;
    $angle = Hash::generate($input);
    

Performance Optimization

  • Memoization: Cache results in memory for repeated calls:

    $cache = [];
    $hash = function ($input) use ($cache) {
        return $cache[$input] ?? $cache[$input] = Hash::generate($input);
    };
    
  • Batch Processing: For bulk operations, precompute hashes:

    $inputs = ['user1', 'user2', 'user3'];
    $hashes = collect($inputs)->map(fn($input) => Hash::generate($input));
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky