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

Utility Laravel Package

cakephp/utility

Lightweight CakePHP Utility library providing handy helpers for arrays, text, numbers, hashing, security, and type conversion. A standalone set of utility classes you can use inside or outside CakePHP to simplify common PHP tasks with minimal dependencies.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer in your Laravel project:

    composer require cakephp/utility
    

    No additional configuration is required—it’s a standalone utility library.

  2. First Use Case: Text Manipulation Use the Text helper for common string operations like truncation, pluralization, or slug generation:

    use Cake\Utility\Text;
    
    $truncated = Text::truncate('This is a very long string', 10); // "This is a..."
    $slug = Text::slug('Hello World!'); // "hello-world"
    
  3. Where to Look First

    • Documentation: CakePHP Utility API Docs (adapt for Laravel).
    • Source Code: Browse the src directory for all available classes.
    • Laravel Integration: Treat it as a utility belt—import classes as needed without framework coupling.

Implementation Patterns

Common Workflows

  1. Text Utilities

    • Slugs & Inflection: Convert strings to URLs or human-readable formats.
      use Cake\Utility\Text;
      use Cake\Utility\Inflector;
      
      $slug = Text::slug('User Profile'); // "user-profile"
      $plural = Inflector::pluralize('user'); // "users"
      
    • Truncation: Limit text length with ellipsis.
      Text::truncate('Lorem ipsum...', 20); // "Lorem ipsum..."
      
  2. Hash Manipulation

    • Nested Access: Safely retrieve values from arrays/objects.
      use Cake\Utility\Hash;
      
      $data = ['user' => ['name' => 'John']];
      Hash::get($data, 'user.name'); // "John"
      Hash::extract($data, '{n}.name'); // ['John']
      
    • Merging: Combine arrays with precedence rules.
      $merged = Hash::merge(['a' => 1], ['a' => 2, 'b' => 3]); // ['a' => 2, 'b' => 3]
      
  3. Security

    • Input Sanitization: Escape HTML or strip tags.
      use Cake\Utility\Security;
      
      $clean = Security::escapeHtml('<script>alert(1)</script>'); // &lt;script&gt;...
      $stripped = Security::stripTags('<b>Hello</b>'); // "Hello"
      
  4. XML/JSON Handling

    • XML Parsing: Convert XML to arrays (useful for APIs).
      use Cake\Utility\Xml;
      
      $xml = '<root><item>test</item></root>';
      $array = Xml::toArray($xml); // ['root' => ['item' => 'test']]
      

Integration Tips

  • Service Providers: Register helpers as Laravel services (optional):
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton('text', function () {
            return new \Cake\Utility\Text();
        });
    }
    
    Use via dependency injection:
    public function __construct(private Text $text) {}
    
  • Facade Pattern: Create a facade for convenience (e.g., TextFacade).
  • Testing: Mock utilities in tests (e.g., Hash for complex data manipulation).

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • CakePHP uses Cake\Utility\* namespaces. Avoid collisions with Laravel’s Illuminate\Support\Str (e.g., don’t mix Str::slug() and Text::slug()).
    • Fix: Stick to one library per project for consistency.
  2. Array vs. Object Handling

    • Hash works with arrays by default. For objects, use Hash::extract($obj->toArray()).
    • Tip: Convert objects to arrays explicitly if behavior differs:
      Hash::get((array) $object, 'property');
      
  3. XML Parsing Quirks

    • Xml::toArray() may not handle malformed XML gracefully. Validate input first:
      if (!Xml::isWellFormed($xmlString)) {
          throw new \InvalidArgumentException('Invalid XML');
      }
      
  4. Security Overhead

    • Security::escapeHtml() is strict. For HTML emails or rich text, consider DOMPurifier instead.

Debugging Tips

  • Hash Paths: Use Hash::check() to validate paths before extraction:
    if (Hash::check($data, 'user.name')) {
        $value = Hash::get($data, 'user.name');
    }
    
  • Text Truncation: Ensure Text::truncate() respects UTF-8 characters (test with non-ASCII strings).
  • Performance: Hash operations on large arrays can be slow. Cache results if reused:
    $cached = Cache::remember("hash_{$key}", 60, fn() => Hash::get($data, $key));
    

Extension Points

  1. Custom Inflector Rules Override Inflector behavior by extending the class:

    class CustomInflector extends \Cake\Utility\Inflector {
        public static function pluralize($string) {
            return parent::pluralize($string) . '_custom';
        }
    }
    

    Use via CustomInflector::pluralize('user').

  2. Security Policies Extend Security for project-specific rules (e.g., custom allowed tags):

    Security::allowTags(['<b>', '<i>', '<custom-tag>']);
    
  3. XML Schema Validation Combine with Cake\Utility\Xml and DOMDocument for schema validation:

    $dom = new \DOMDocument();
    $dom->loadXML($xml);
    $schema = $dom->schemaValidate('schema.xsd');
    
  4. Laravel Blade Directives Create Blade helpers for utilities:

    // app/Providers/BladeServiceProvider.php
    Blade::directive('slug', function ($expression) {
        return "<?php echo \\Cake\\Utility\\Text::slug({$expression}); ?>";
    });
    

    Usage:

    @slug('Hello World') → "hello-world"
    
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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views