Helpers
The Ecommerce\Supports namespace provides several helper classes to assist with common tasks involving arrays, strings, URLs, and flexible data structures.
Arr
The Arr class provides a fluent object-oriented interface for working with arrays. It allows you to chain methods to manipulate array data efficiently.
make
Create a new Arr instance.
Description:
The make() method is a static factory method used to create a new instance of the Arr class. This is the preferred way to instantiate the class.
Method Signature:
public static function make(array $items = []): self
Parameters:
$items- (Optional) The initial array data. Defaults to an empty array[].
Examples:
// Create an empty Arr instance
$arr = Arr::make();
// Create with initial data
$products = Arr::make([
'p1' => ['name' => 'T-Shirt'],
'p2' => ['name' => 'Jeans']
]);
// Create with numeric array
$numbers = Arr::make([1, 2, 3, 4, 5]);
// Using with Model data
$orders = Arr::make([
Order::find(1),
Order::find(2)
]);
from
Create an array from various types of inputs.
Description:
The from() method converts a given input into a native PHP array. It supports arrays, Arrayable objects, Jsonable objects, Collection instances, and standard objects.
Method Signature:
public static function from(mixed $items): array
Parameters:
$items- The items to convert to an array.
Examples:
// Convert a Collection to array
$collection = Product::all(); // Returns Collection
$array = Arr::from($collection);
// Convert a standard object
$obj = new stdClass();
$obj->name = 'Product A';
$array = Arr::from($obj);
// ['name' => 'Product A']
// Convert an Arrayable object
$order = Order::find(1); // Assumes Order implements Arrayable
$orderArray = Arr::from($order);
// Convert existing array (returns as is)
$simple = ['a', 'b'];
$result = Arr::from($simple);
has
Check if a key exists in the array.
Description:
The has() method checks if a specific key exists within the array items.
Method Signature:
public function has(string $key): bool
Parameters:
$key- The key to check for.
Examples:
$data = Arr::make(['status' => 'active', 'count' => 10]);
// Check for existing key
if ($data->has('status')) {
echo "Status exists";
}
// Check with model attributes
$productData = Arr::make(['sku' => 'ABC-123', 'price' => 100]);
$hasSku = $productData->has('sku'); // true
$hasStock = $productData->has('stock'); // false
// Useful in validation logic
if (!$data->has('required_field')) {
throw new Exception("Missing field");
}
get
Retrieve a value from the array by key.
Description:
The get() method retrieves the value associated with a specific key. If the key does not exist, a default value can be returned.
Method Signature:
public function get(string $key, mixed $default = null): mixed
Parameters:
$key- The key to retrieve.$default- (Optional) The default value to return if the key is missing. Defaults tonull.
Examples:
$config = Arr::make([
'debug' => true,
'cache_ttl' => 3600
]);
// Get existing value
$debug = $config->get('debug'); // true
// Get missing value with default
$apiKey = $config->get('api_key', 'default_key'); // 'default_key'
// Working with Product attributes
$attributes = Arr::make(['color' => 'red', 'size' => 'L']);
$color = $attributes->get('color'); // 'red'
$material = $attributes->get('material', 'Cotton'); // 'Cotton'
set
Set a value in the array.
Description:
The set() method allows you to add or update a value in the array for a specific key.
Method Signature:
public function set(string $key, mixed $value): void
Parameters:
$key- The key to set.$value- The value to assign.
Examples:
$cart = Arr::make([]);
// set a value
$cart->set('item_count', 5);
// Update a value
$cart->set('item_count', 6);
// Store complex data
$cart->set('last_added', ['id' => 1, 'name' => 'Product X']);
// Validating data state
echo $cart->get('item_count'); // 6
count
Get the total number of items.
Description:
The count() method returns the total number of items currently in the array.
Method Signature:
public function count(): int
Examples:
$items = Arr::make([1, 2, 3]);
echo $items->count(); // 3
$empty = Arr::make();
echo $empty->count(); // 0
// Count orders
$orders = Arr::make([
['id' => 1, 'total' => 100],
['id' => 2, 'total' => 200]
]);
if ($orders->count() > 0) {
// Process orders
}
push
Add a new item to the end of the array.
Description:
The push() method appends a new value to the end of the array and returns the new total count of items.
Method Signature:
public function push(mixed $value): int
Parameters:
$value- The value to add.
Examples:
$ids = Arr::make([1, 2]);
// Push a single value
$newCount = $ids->push(3); // Returns 3
// Items: [1, 2, 3]
// Push a model instance
$recentViewed = Arr::make();
$recentViewed->push(Product::find(1));
$recentViewed->push(Product::find(2));
// Push array data
$logs = Arr::make();
$logs->push(['action' => 'login', 'time' => time()]);
prepend
Add a new item to the beginning of the array.
Description:
The prepend() method inserts a new value at the start of the array and returns the new total count of items. All existing numerical keys will be modified to reflect the new position, while literal keys remain untouched.
Method Signature:
public function prepend(mixed $value): int
Parameters:
$value- The value to add.
Examples:
$queue = Arr::make(['second', 'third']);
// Prepend item
$queue->prepend('first');
// Items: ['first', 'second', 'third']
// Prepend high priority order
$orders = Arr::make([$regularOrder]);
$orders->prepend($priorityOrder);
// Prepend configuration defaults
$middleware = Arr::make(['AuthMiddleware']);
$middleware->prepend('LogMiddleware');
pop
Remove and get the last item from the array.
Description:
The pop() method removes the last element from the array and returns it. If the array is empty, it returns null.
Method Signature:
public function pop(): mixed
Examples:
$stack = Arr::make([1, 2, 3]);
// Remove last item
$item = $stack->pop(); // 3
// Items: [1, 2]
// Process tasks LIFO (Last In, First Out)
$tasks = Arr::make(['task1', 'task2']);
while($task = $tasks->pop()) {
process($task);
}
// Handling empty array
$empty = Arr::make();
$val = $empty->pop(); // null
shift
Remove and get the first item from the array.
Description:
The shift() method removes the first element from the array and returns it. All numerical keys will be reindexed.
Method Signature:
public function shift(): mixed
Examples:
$queue = Arr::make(['first', 'second']);
// Remove first item
$item = $queue->shift(); // 'first'
// Items: ['second']
// Process tasks FIFO (First In, First Out)
$jobs = Arr::make([$job1, $job2, $job3]);
$currentJob = $jobs->shift();
// With empty array
$empty = Arr::make();
$val = $empty->shift(); // null
map
Apply a callback to each item in the array.
Description:
The map() method iterates through the array and passes each value and key to the given callback. It returns a new instance of Arr containing the transformed items. The original array remains unchanged.
Method Signature:
public function map(callable $callable): static
Parameters:
$callable- Function to apply to each item. Signature:function($value, $index)
Examples:
$prices = Arr::make([100, 200, 300]);
// Apply tax
$withTax = $prices->map(function($price) {
return $price * 1.2;
});
// $withTax items: [120, 240, 360]
// Extract IDs from Models
$products = Arr::make([Product::find(1), Product::find(2)]);
$ids = $products->map(function($product) {
return $product->id;
});
// Using keys
$data = Arr::make(['a' => 1, 'b' => 2]);
$formatted = $data->map(function($value, $key) {
return "$key:$value";
});
// Items: ['a:1', 'b:2']
filter
Filter the array using a callback.
Description:
The filter() method filters the array by passing each value and key to the callback. If the callback returns true, the item is included in the new array. Returns a new Arr instance.
Method Signature:
public function filter(callable $callable): static
Parameters:
$callable- Function to test each item. Signature:function($value, $index): bool
Examples:
$scores = Arr::make([85, 40, 90, 30]);
// Filter passing scores
$passed = $scores->filter(function($score) {
return $score >= 50;
});
// Items: [85, 90]
// Filter active products
$products = Arr::make(Product::all()->all());
$active = $products->filter(function($product) {
return $product->status === 'active';
});
// Filter by key
$data = Arr::make(['pk_1' => 1, 'sk_2' => 2]);
$pks = $data->filter(function($v, $k) {
return str_starts_with($k, 'pk_');
});
foreach
Iterate over each item in the array.
Description:
The foreach() method iterates over the items in the array and executes the provided callback for each item. This method does not return a new array.
Method Signature:
public function foreach(callable $callable): void
Parameters:
$callable- Function to execute. Signature:function($value, $index)
Examples:
$users = Arr::make(['Alice', 'Bob']);
// Print names
$users->foreach(function($name) {
echo "User: $name\n";
});
// Update database models
$orders = Arr::make(Order::where('status', 'pending')->get()->all());
$orders->foreach(function($order) {
$order->status = 'processing';
$order->save();
});
// Using key and value
$settings = Arr::make(['theme' => 'dark', 'notifications' => 'on']);
$settings->foreach(function($value, $key) {
Option::set($key, $value);
});
find
Find the first item matching a condition.
Description:
The find() method iterates through the array and returns the first value for which the callback returns true. If no item is found, it returns null.
Method Signature:
public function find(callable $callable): mixed
Parameters:
$callable- Function to test each item. Signature:function($value, $index): bool
Examples:
$numbers = Arr::make([1, 5, 10, 15]);
// Find first number > 8
$result = $numbers->find(function($n) {
return $n > 8;
});
// 10
// Find specific product in memory
$cartItems = Arr::make($cart->items);
$tshirt = $cartItems->find(function($item) {
return $item->sku === 'TSHIRT-001';
});
// Not found returns null
$notFound = $numbers->find(fn($n) => $n > 100); // null
reduce
Reduce the array to a single value.
Description:
The reduce() method applies a callback function cumulatively to the items of the array, so as to reduce the array to a single value.
Method Signature:
public function reduce(callable $callable, mixed $initial_value): mixed
Parameters:
$callable- Function to apply. Signature:function($carry, $item)$initial_value- The initial value for the carry.
Examples:
$values = Arr::make([10, 20, 30]);
// Sum values
$sum = $values->reduce(function($carry, $item) {
return $carry + $item;
}, 0);
// 60
// Concatenate strings
$words = Arr::make(['Hello', 'World']);
$sentence = $words->reduce(function($carry, $item) {
return $carry . ' ' . $item;
}, '');
// " Hello World"
// Calculate total order value
$items = Arr::make([
['price' => 10, 'qty' => 2],
['price' => 5, 'qty' => 4]
]);
$total = $items->reduce(function($carry, $item) {
return $carry + ($item['price'] * $item['qty']);
}, 0);
// 40
pluck
Extract values for a specific key.
Description:
The pluck() method retrieves all the values for a given key from an array of arrays or objects.
Method Signature:
public function pluck(string $key): self
Parameters:
$key- The key to extract values for.
Examples:
$users = Arr::make([
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob']
]);
// Pluck names
$names = $users->pluck('name');
// Items: ['Alice', 'Bob']
// Pluck from Models
$products = Arr::make([
new Product(['id' => 101, 'sku' => 'A']),
new Product(['id' => 102, 'sku' => 'B'])
]);
$skus = $products->pluck('sku');
// Items: ['A', 'B']
// Flatten result automatically
$flattened = $names->toArray(); // ['Alice', 'Bob']
Flex
The Flex class is a hybrid structure that behaves like an array, an object, and is basically a versatile data container. It implements ArrayAccess and magic methods for property access.
fill
Fill the container with attributes.
Description:
The fill() method populates the internal attributes array with the provided data.
Method Signature:
protected function fill(array $attributes): void
Note: This method is protected but used via the constructor or internally.
Examples:
// Via Constructor
$flex = new Flex(['key' => 'value']);
// Accessing data
echo $flex->get('key');
get
Get an attribute value.
Description:
The get() method retrieves an attribute. If the attribute doesn't exist, a default value can be returned.
Method Signature:
public function get(string $key, mixed $default = null): mixed
Parameters:
$key- The attribute key.$default- (Optional) Default value.
Examples:
$settings = new Flex(['theme' => 'dark']);
// Using method
echo $settings->get('theme'); // 'dark'
// Using magic property
echo $settings->theme; // 'dark'
// Using array access
echo $settings['theme']; // 'dark'
// With default
echo $settings->get('font', 'Arial'); // 'Arial'
set
Set an attribute value.
Description:
The set() method assigns a value to a specific attribute key.
Method Signature:
public function set(string $key, mixed $value): self
Parameters:
$key- The attribute key.$value- The value to store.
Examples:
$data = new Flex();
// Using method (fluent)
$data->set('name', 'Product')->set('price', 100);
// Using magic property
$data->description = 'Sample';
// Using array access
$data['active'] = true;
// Verify
echo $data->get('name'); // 'Product'
exists
Check if an attribute exists.
Description:
The exists() method checks if a specific key is present in the attributes.
Method Signature:
public function exists(string $key): bool
Examples:
$file = new Flex(['path' => '/tmp/file.txt']);
if ($file->exists('path')) {
unlink($file->path);
}
// Magic isset check
if (isset($file->size)) {
// ...
}
to_array
Convert the container to a PHP array.
Description:
The to_array() method returns all the stored attributes as a standard associative array.
Method Signature:
public function to_array(): array
Examples:
$user = new Flex(['name' => 'John', 'email' => 'john@example.com']);
$array = $user->to_array();
// ['name' => 'John', 'email' => 'john@example.com']
// JSON encoding uses this automatically
echo json_encode($user);
// {"name":"John","email":"john@example.com"}
Str
The Str class provides a collection of static methods for string manipulation, generation, and formatting.
slug
Generate a URL-friendly slug.
Description:
The slug() method sanitizes a string to be safe for use in URLs, replacing spaces with dashes and removing special characters.
Method Signature:
public static function slug(string $value): string
Parameters:
$value- The string to convert.
Examples:
echo Str::slug('Hello World!');
// "hello-world"
echo Str::slug('Product #123 (Red)');
// "product-123-red"
// Creating product handle
$product->handle = Str::slug($product->title);
trim
Trim characters from the beginning and end of a string.
Description:
The trim() method strips whitespace (or other characters) from the beginning and end of a string. It handles unicode whitespace characters as well.
Method Signature:
public static function trim(string $value, string $charlist = null): string
Parameters:
$value- The string to trim.$charlist- (Optional) Characters to remove. Defaults to whitespace.
Examples:
echo Str::trim(' Hello ');
// "Hello"
echo Str::trim('/path/to/file/', '/');
// "path/to/file"
// Cleanup user input
$email = Str::trim($request->input('email'));
substr
Get a substring from a string.
Description:
The substr() method returns the portion of string specified by the start and length parameters, using multi-byte safe operations.
Method Signature:
public static function substr(string $value, int $start, int $length = null, string $encoding = 'UTF-8'): string
Parameters:
$value- The input string.$start- Start position.$length- (Optional) Length of substring.$encoding- (Optional) Character encoding.
Examples:
echo Str::substr('Hello World', 0, 5);
// "Hello"
echo Str::substr('Hello World', 6);
// "World"
// Safe with unicode
echo Str::substr('こんにちは', 0, 2);
// "こん"
lower
Convert a string to lowercase.
Description:
The lower() method converts the given string to lowercase using multi-byte safe functions.
Method Signature:
public static function lower(string $value): string
Examples:
echo Str::lower('HELLO'); // "hello"
echo Str::lower('Mixed Case'); // "mixed case"
upper
Convert a string to uppercase.
Description:
The upper() method converts the given string to uppercase using multi-byte safe functions.
Method Signature:
public static function upper(string $value): string
Examples:
echo Str::upper('hello'); // "HELLO"
camel
Convert a string to camel case.
Description:
The camel() method converts the given string to camelCase. It separates words by spaces, hyphens, or underscores.
Method Signature:
public static function camel(string $value): string
Examples:
echo Str::camel('hello_world'); // "helloWorld"
echo Str::camel('param-name'); // "paramName"
echo Str::camel('User Profile'); // "userProfile"
snake
Convert a string to snake case.
Description:
The snake() method converts the given string to snake_case.
Method Signature:
public static function snake(string $value): string
Examples:
echo Str::snake('HelloWorld'); // "hello_world"
echo Str::snake('userProfile'); // "user_profile"
pascal
Convert a string to Pascal case.
Description:
The pascal() method converts the given string to PascalCase (also known as StudlyCase).
Method Signature:
public static function pascal(string $value): string
Examples:
echo Str::pascal('hello_world'); // "HelloWorld"
echo Str::pascal('user_profile'); // "UserProfile"
uuid
Generate a version 4 UUID.
Description:
The uuid() method generates a universally unique identifier (UUID) v4.
Method Signature:
public static function uuid(): string
Examples:
$id = Str::uuid();
// "550e8400-e29b-41d4-a716-446655440000" (random)
// Assign to model
$order->uuid = Str::uuid();
Url
The Url class provides helper methods for URL generation and redirection.
make
Create a URL with query parameters.
Description:
The make() method appends query parameters to a base URL.
Method Signature:
public static function make(string $url, array $data = []): string
Parameters:
$url- The base URL.$data- Array of query parameters.
Examples:
$url = Url::make('https://example.com/products', ['sort' => 'price', 'page' => 2]);
// "https://example.com/products?sort=price&page=2"
$link = Url::make('/checkout', ['step' => 'shipping']);
// "/checkout?step=shipping"
redirect
Redirect to a specific URL.
Description:
The redirect() method creates a URL with optional query parameters and performs a redirect. It handles both standard headers and JavaScript fallback if headers are already sent.
Method Signature:
public static function redirect(string $url, array $data = []): void
Parameters:
$url- The target URL.$data- Query parameters to append.
Examples:
// Redirect to dashboard
Url::redirect('/dashboard');
// Redirect with params
Url::redirect('/search', ['q' => 'shoes']);
// Redirect to custom success page
Url::redirect('/thank-you', ['order_id' => 123]);
redirect_back
Redirect back to the referrer.
Description:
The redirect_back() method redirects the user back to the previous page (Referrer). It also supports appending query data.
Method Signature:
public static function redirect_back(array $data = []): void
Parameters:
$data- Query parameters to append to the referrer URL.
Examples:
// Simple back
Url::redirect_back();
// Back with error
Url::redirect_back(['error' => 'invalid_input']);
// Back with success message
Url::redirect_back(['success' => true]);