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

Piper Laravel Package

spatie/piper

Pipe-operator-first PHP utility library for array and string manipulation. Piper ports many Laravel Collection and Str helpers to standalone functions that work with primitives, so you can compose readable pipelines for filtering, mapping, joining, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require spatie/piper
    
  2. First Use Case: Import functions and pipe them directly:
    use function Spatie\Piper\Arr\{filter, map};
    use function Spatie\Piper\Str\{lower, replace};
    
    $result = [1, 2, 3, 4, 5]
        |> filter(fn ($n) => $n % 2 === 0)
        |> map(fn ($n) => "Item $n")
        |> join(', ');
    // "Item 2, Item 4"
    

Where to Look First

  • Documentation: Spatie Piper Docs (alphabetical function reference).
  • Examples: The README’s mixed array/string pipeline example ([1, 2, 3] |> ... |> suffix('.')).
  • Namespace: Spatie\Piper\Arr (arrays) and Spatie\Piper\Str (strings).

Implementation Patterns

Core Workflows

  1. Data Transformation Pipelines:

    $users = User::all()
        |> map(fn ($user) => $user->name)
        |> filter(fn ($name) => strlen($name) > 5)
        |> sort();
    
  2. String Manipulation:

    $path = 'app/Models/User'
        |> afterLast('/')
        |> studly();
    // "User" (class name extraction)
    
  3. Validation Helpers:

    $email = 'test@example.com'
        |> is('*@*.com')
        |> tap(fn ($isValid) => $isValid || abort(422, 'Invalid email'));
    

Integration Tips

  • Laravel Synergy: Replace collect()->pipe() with Piper’s primitives for lightweight operations.
  • Type Safety: Use typed closures (e.g., fn (Post $post) => ...) for IDE autocompletion.
  • Mixed Pipelines: Chain Arr and Str functions seamlessly (e.g., ['a', 'b'] |> join(', ') |> upper()).

Common Patterns

Use Case Pattern
Filtering `$array
Mapping `$array
String Formatting `$str
Conditional Logic `$value
Data Extraction `$path

Gotchas and Tips

Pitfalls

  1. Mutable Operations:

    • Piper functions return new values; avoid side effects (e.g., $arr = $arr |> push() is safe, but $arr[] = ... breaks pipelines).
    • Fix: Use tap() for side effects:
      $arr |> tap(fn ($a) => $a[] = 'new');
      
  2. Empty Inputs:

    • Functions like explode() or map() may return null or empty arrays/strings.
    • Fix: Chain with default() or isNotEmpty():
      $str |> explode(',') |> default([]) |> count();
      
  3. Regex Caveats:

    • isMatch() and matchAll() use PCRE; escape special chars:
      $str |> is('/\d+/'); // Fails if $str contains literal '/'
      // Fix: Use `preg_quote()` or raw strings.
      
  4. Performance:

    • Avoid deep pipelines on large arrays (e.g., map() + filter() + sort()). Use intermediate variables if needed.

Debugging Tips

  • Inspect Mid-Pipeline:
    $result = $data
        |> tap(fn ($d) => logger()->debug('Debug:', ['data' => $d]))
        |> map(...);
    
  • Test Edge Cases:
    $empty = [] |> filter(fn ($x) => false); // Returns []
    $null = null |> default('fallback');    // Returns 'fallback'
    

Extension Points

  1. Custom Functions: Add to composer.json autoload:

    // app/Helpers/Piper.php
    use function Spatie\Piper\Arr\{*};
    function customFn($arr) { ... }
    

    Then import globally in composer.json:

    "autoload": {
      "files": ["app/Helpers/Piper.php"]
    }
    
  2. Alias Existing Functions:

    use function Spatie\Piper\Str\{upper as toUpper};
    
  3. Laravel Service Provider: Register global functions in AppServiceProvider:

    use function Spatie\Piper\Arr\{*};
    use function Spatie\Piper\Str\{*};
    

Config Quirks

  • No Config File: Piper is zero-config. All functions are stateless.
  • Locale Awareness: String functions (e.g., lower()) respect PHP’s locale settings. Set via setlocale() if needed.

Pro Tips

  • Combine with Laravel:
    $query = User::query()
        |> where('active', true)
        |> orderBy('name')
        |> get()
        |> map(fn ($user) => $user->email);
    
  • DSL-Style Chaining:
    $result = $data
        |> filter(fn ($x) => $x > 0)
        |> map(fn ($x) => $x * 2)
        |> sum();
    
  • Function Composition:
    $transform = fn ($str) => $str
        |> trim()
        |> lower()
        |> kebab();
    
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