dragon-code/support
Dragon Code Support is a lightweight helper toolkit for PHP/Laravel projects, providing a growing collection of utilities and facades to speed up development. Easy to extend—add new methods or classes with tests following the package structure.
Installation:
composer require dragon-code/support
No additional configuration is required—facades are auto-discoverable in Laravel.
First Use Case: Replace a common utility function with the package’s helpers. For example:
use DragonCode\Support\Facades\Arr;
use DragonCode\Support\Facades\Str;
// Flatten an array
$flattened = Arr::flatten(['a' => ['b', 'c']]);
// Generate a slug
$slug = Str::slug('Hello World');
Key Facades to Explore:
Arr (array manipulation)Str (string operations)File/Directory (filesystem utilities)Digit (number formatting)Instance (object/type checks)Where to Look First:
$result = Arr::of(['a', 'b', 'c'])
->filter(fn($item) => $item !== 'b')
->map(fn($item) => strtoupper($item))
->toArray();
$flattened = Arr::flattenKeys(['user.data' => ['name' => 'John']]);
// Returns: ['user' => ['data' => ['name' => 'John']]]
$trimmed = Str::trim(' hello ');
$slug = Str::slug('Hello World', '-');
$matches = Str::matchAll('/\d+/', 'Order 123');
$string = Str::of('hello')->reverse()->toString();
$paths = Directory::allPaths(storage_path('app'));
Directory::copy(storage_path('old'), storage_path('new'));
$content = File::load(public_path('file.txt'), true); // Validates readability
if (Instance::of($obj)->is(Model::class)) {
// Handle Eloquent models
}
$short = Digit::toShort(1000, 'k'); // '1k'
Service Providers: Bind facades explicitly if auto-discovery fails (unlikely, but possible in older Laravel versions):
public function register()
{
$this->app->bind('DragonCode\Support\Facades\Arr', function ($app) {
return new \DragonCode\Support\Facades\Arr;
});
}
Blade Directives: Create custom Blade helpers for frontend templates:
Blade::directive('slug', function ($expression) {
return "<?php echo DragonCode\Support\Facades\Str::slug({$expression}); ?>";
});
Usage:
<h1>{{ slug('Hello World') }}</h1>>
Form Request Validation:
Use Arr and Str facades in FormRequest classes for dynamic validation:
public function rules()
{
$slug = Str::slug($this->input('title'));
return [
'title' => ['required', Rule::unique('posts')->ignore($this->post)->where('slug', $slug)],
];
}
Mock Facades:
Use DragonCode\Support\Facades\Arr::shouldReceive() in PHPUnit:
Arr::shouldReceive('flatten')
->once()
->andReturn(['a', 'b', 'c']);
Data Factories:
Generate test data with Arr::of():
$user = Arr::of([
'name' => 'John',
'email' => 'john@example.com',
])->toInstance(User::class);
Avoid Overhead:
For simple operations (e.g., array_merge), prefer native PHP functions if benchmarking shows negligible gains.
Example:
// Benchmark first:
// Native PHP: ~0.1ms
// Arr::merge(): ~0.3ms
$merged = array_merge($array1, $array2); // Use native if critical path
Lazy Loading:
Use Arr::of()->method() for deferred execution in loops:
foreach ($items as $item) {
$processed = Arr::of($item)->map(...)->toArray();
}
Facade Caching:
// ❌ Avoid: Facade state may reset between requests
Arr::of([])->add('key', 'value'); // State lost on next request
PHP Version Mismatches:
// ❌ Fails in PHP 8.0
Str::matchAll('/\d+/', '123'); // Throws error in older PHP
Recursive Method Behavior:
Arr::map or Arr::flatten may behave unexpectedly with mixed-type arrays. Always validate input:
// ❌ Potential bug: mixed arrays may break flattenKeys
$data = ['a' => ['b' => 1, 2], 'c' => null];
Arr::flattenKeys($data); // May throw in some versions
Filesystem Permissions:
File::load() and Directory::copy() will throw exceptions if permissions are insufficient. Handle gracefully:
try {
File::load($path);
} catch (\DragonCode\Support\Exceptions\FileNotReadable $e) {
// Fallback logic
}
Facade Method Naming:
doesntEmpty → isNotEmpty). Check the changelog for deprecated aliases.Enable Facade Logging:
Add this to AppServiceProvider to log facade calls (useful for debugging):
public function boot()
{
\DragonCode\Support\Facades\Arr::setLogger(function ($method, $args) {
\Log::debug("Arr::{$method} called with: " . json_encode($args));
});
}
Test Edge Cases:
Arr::of([])->count(); // Should return 0
Arr::of([null, null])->filter()->toArray(); // Should return []
Arr::flattenKeys(['a.b.c' => 1, 'a.b.d' => 2]);
// Returns: ['a' => ['b' => ['c' => 1, 'd' => 2]]]
Common Errors and Fixes:
| Error | Solution |
|---|---|
Class 'DragonCode\Support\Facades\Arr' not found |
Run composer dump-autoload or check config/app.php for aliases. |
Method doesNotExist does not exist |
Update the package (composer update dragon-code/support). |
String offset cannot be accessed in Arr::flattenKeys |
Ensure all array values are arrays or strings. |
Directory copy failed |
Verify write permissions on the target directory. |
src/Arr.php).How can I help you explore Laravel packages today?