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

Scalars Laravel Package

windwalker/scalars

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require windwalker/scalars ^4.0
    

    Add to config/app.php under providers:

    Windwalker\Scalars\ScalarsServiceProvider::class,
    
  2. First Use Case Convert a string to a scalar value (e.g., 123123 as integer):

    use Windwalker\Scalars\Facades\Scalar;
    
    $value = Scalar::toInt('123'); // Returns 123 (int)
    
  3. Key Classes

    • Scalar facade (primary entry point).
    • Scalar::toInt(), Scalar::toFloat(), Scalar::toBool(), etc.
    • Scalar::cast() for dynamic casting.

Implementation Patterns

Core Workflows

  1. Type Casting

    // Convert to specific types
    $int = Scalar::toInt('123abc', 0); // Returns 123 (ignores 'abc')
    $float = Scalar::toFloat('3.14');
    $bool = Scalar::toBool('true'); // Returns true (case-insensitive)
    
  2. Dynamic Casting

    $value = Scalar::cast('123', 'int'); // Equivalent to toInt()
    $value = Scalar::cast(['foo' => 'bar'], 'array'); // Returns array
    
  3. Validation + Casting

    // Validate and cast in one step
    $validInt = Scalar::toInt('123', null, ['min' => 0, 'max' => 100]);
    // Returns 123 if valid, null otherwise
    
  4. Laravel Integration

    • Form Requests: Cast user input in prepareForValidation():
      public function prepareForValidation()
      {
          $this->merge([
              'age' => Scalar::toInt($this->age, null, ['min' => 0]),
          ]);
      }
      
    • Model Attributes:
      protected $casts = [
          'price' => [Scalar::class, 'toFloat'],
      ];
      
  5. Batch Processing

    $data = ['1', '2.5', 'false'];
    $casted = array_map([Scalar::class, 'cast'], $data, array_fill(0, 3, 'float'));
    // Returns [1.0, 2.5, 0.0]
    

Gotchas and Tips

Pitfalls

  1. Strict Validation

    • toInt('abc') returns null by default. Use a fallback:
      Scalar::toInt('abc', 0); // Returns 0
      
    • Validation rules (e.g., ['min' => 0]) throw exceptions on failure. Suppress with:
      Scalar::toInt('abc', null, ['min' => 0], false); // Returns null
      
  2. Boolean Quirks

    • Scalar::toBool('1') returns true (treats non-zero as true).
    • Empty strings ('') return false, but '0' returns false (unlike PHP’s (bool)'0').
  3. Floating-Point Precision

    • toFloat('1.23456789') may lose precision. Use round() if needed:
      Scalar::toFloat('1.234', null, null, 2); // Returns 1.23 (2 decimal places)
      
  4. Array Handling

    • Scalar::cast($array, 'array') returns the same array. Use toArray() for deep casting:
      Scalar::toArray(['foo' => '123'], ['foo' => 'int']); // ['foo' => 123]
      

Debugging Tips

  1. Check Defaults

    • Run Scalar::getConfig() to inspect current settings (e.g., strict mode).
    • Override defaults in config/scalars.php:
      'strict' => false, // Allow loose casting
      'fallback' => 0,   // Global fallback value
      
  2. Custom Validators

    • Extend validation rules via Scalar::extend():
      Scalar::extend('even', function ($value) {
          return $value % 2 === 0;
      });
      Scalar::toInt('123', null, ['even' => true]); // Returns null (fails)
      
  3. Performance

    • Cache repeated casts (e.g., in a loop) to avoid redundant parsing:
      $cache = [];
      $casted = $cache[$key] ?? ($cache[$key] = Scalar::toInt($value));
      

Extension Points

  1. Custom Types

    • Register a new scalar type:
      Scalar::extend('uuid', function ($value) {
          return Str::of($value)->startsWith('uuid:') ? Str::after($value, 'uuid:') : null;
      });
      
  2. Service Provider

    • Bind custom resolvers in register():
      $this->app->bind('scalar.resolver.custom', function () {
          return new CustomScalarResolver();
      });
      
  3. Facade Overrides

    • Publish and modify the facade:
      php artisan vendor:publish --provider="Windwalker\Scalars\ScalarsServiceProvider"
      
    • Override Scalar::cast() logic in app/Providers/AppServiceProvider.php:
      Scalar::macro('customCast', function ($value) { ... });
      
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