Helper Classes Documentation

Helper Classes Documentation

This document provides documentation for the facades and helper classes available in the Textstem Laravel package.

Table of Contents

Facades

The package ships several Laravel facades. All are bound in TextstemServiceProvider and aliased in config/app.php (or via the package's alias registration).

Textstem Facade

Accessor: textstem -- wraps Medialight\Textstem\Textstem.

The primary package facade. Provides page context, global options, and HTML rendering shortcuts.

Alias: Textstem (registered automatically by the service provider)

Key methods:

Method Description
getPage() Returns the current WranglerPage instance set in context.
setPage($page) Sets the active page for the current request context.
globalVal(string $key) Gets the value of a GlobalOption by key.
globalVar(string $key) Alias for globalVal.
sectionMenu(string $section) Returns a navigation menu for the given section slug.
section(string $name) Returns the named section/region of the current page.
pageCategoryList() Returns a list of page categories.
asset(int $id) Loads and returns an Asset model by ID.
nicefy(string $str) Converts a slug or technical string into a human-readable label.
wrt(string $key) Returns a translated string from the package language files.
picture($asset, array $attrs) Renders a responsive <picture> element for an asset.
image($asset, array $attrs) Renders an <img> element for an asset.
thumbImg($asset, array $attrs) Renders a thumbnail <img> element for an asset.
assetTile($asset, array $attrs) Renders an asset tile component.
findHelperClass(string $name) Resolves a helper class by short name.
sendMsg(array $data) Sends an internal message/notification.

Preferences Facade

Accessor: preferences -- wraps Medialight\Textstem\Preferences.

Manages per-user or global preference key/value pairs stored as JSON in the local storage disk.

Alias: Preferences (registered automatically)

Method Description
get(string $key, mixed $default = null) Gets a preference value by key.
all(): array Returns all stored preferences.
set(string $key, mixed $value) Sets a single preference value.
update(array $values) Merges an array of key/value pairs into the stored preferences.
save() Persists the current in-memory preferences to disk.
reset() Clears all preferences and resets to defaults.
validateConfig(array $config): bool Validates a preferences configuration array.

Preferences are stored at storage/app/preferences.json on the local disk.

Notifier Facade

Accessor: messenger -- wraps the Messenger tool/service.

Alias: Notifier (registered automatically via NotifierFacade)

Used to send in-app notifications or messages. The binding resolves to the Messenger service registered in the container.

Accessibility Facade

Accessor: accessibility -- wraps Medialight\Textstem\Services\AccessibilityService.

Alias: Accessibility

Runs WCAG accessibility analysis against URLs or raw HTML.

Method Description
analyzeUrl(string $url): array Fetches the URL and analyses its HTML for accessibility issues.
analyzeHtml(string $html): array Analyses a raw HTML string for accessibility issues.
getWcagLevel(): string Returns the configured WCAG conformance level (A, AA, or AAA).
shouldCheckOnSave(): bool Returns true if analysis should run automatically on page save.
shouldStoreReports(): bool Returns true if analysis reports should be persisted.
getReportRetentionDays(): int Returns how many days reports are retained before being pruned.

Configuration is read from textstemapp.accessibility.*.

SEO Facade

Accessor: seo -- wraps Medialight\Textstem\Services\SEOService.

Alias: SEO

Runs SEO analysis against URLs or raw HTML.

Method Description
analyzeUrl(string $url): array Fetches the URL and analyses its HTML for SEO issues.
analyzeHtml(string $html): array Analyses a raw HTML string for SEO issues.
shouldCheckOnSave(): bool Returns true if analysis should run automatically on page save.
shouldStoreReports(): bool Returns true if SEO reports should be persisted.
getReportRetentionDays(): int Returns how many days SEO reports are retained.

Configuration is read from textstemapp.seo.*.

TableGenerator Facade

Accessor: tablegenerator -- wraps Medialight\Textstem\Services\TableGeneratorService.

Alias: TableGenerator (registered via TableGeneratorFacade)

Generates HTML tables from PHP arrays using Tailwind CSS classes.

Method Description
arrayToTable(array $array): string Converts a 2-D array to a full <table> HTML string including header row.
rowToHead(array $row): string Generates a <thead> row from the keys of the supplied array.
rowToHtml(array $row): string Generates a <tr> row from the values of the supplied array.

Example:

TableGenerator::arrayToTable([
    ['Name' => 'Alice', 'Role' => 'Admin'],
    ['Name' => 'Bob',   'Role' => 'Editor'],
]);

Text Helper

The Text class provides various helper methods for manipulating and formatting text.

Namespace: Medialight\Textstem\Helpers

toHtml

Return formatted HTML paragraph string with escaped special characters.

public static function toHtml($string): string

Parameters:

  • $string (string): The string to convert to HTML.

Returns:

  • (string): The formatted HTML paragraph string.

strip_bare

Strip out all formatting from some HTML.

public static function strip_bare($str, $treatasHTML = false): string

Parameters:

  • $str (string): The HTML string to strip formatting from.
  • $treatasHTML (bool): Whether to treat the input as HTML. Default is false.

Returns:

  • (string): The stripped string without formatting.

formatForSort

Format a string for sorting. (eg 'The Great Escape' => 'Great Escape, The')

public static function formatForSort(string $rawString): string

Parameters:

  • $rawString (string): The original string to be formatted.

Returns:

  • (string): The formatted string for sorting.

formatFromSort

Format a string from sorting. (eg 'Great Escape, The' => 'The Great Escape')

public static function formatFromSort(string $str): string

Parameters:

  • $str (string): The sorted string to be formatted.

Returns:

  • (string): The formatted string.

nicefy

Convert a string to a more readable format by handling hyphens, slashes, and camelCase.

public static function nicefy($str, $ucwrds = true, $keepHyphens = true): string

Parameters:

  • $str (string): The string to be formatted.
  • $ucwrds (bool): Whether to convert the result to title case. Default is true.
  • $keepHyphens (bool): Whether to keep hyphens in the string. Default is true.

Returns:

  • (string): The formatted string.

toArray

This function is the same as explode, but trims white space and skips empties.

public static function toArray(mixed $str = '', ?string $sep = ','): array

Parameters:

  • $str (mixed): The string to be exploded or an array to be returned as is.
  • $sep (string|null): The separator to use for exploding the string. Default is comma.

Returns:

  • (array): The resulting array after exploding and filtering.

truncate

Truncate a given text, preserving word boundaries and adding a signify chop with.

public static function truncate(mixed $text = '', ?int $length = 50, $signifyChopWith = '...'): string

Parameters:

  • $text (mixed): The text to be truncated. Default is an empty string.
  • $length (int|null): The maximum length of the truncated text. Default is 50.
  • $signifyChopWith (string): The signify chop with to be added at the end of the truncated text. Default is '...'.

Returns:

  • (string): The truncated text with signify chop with added.

truncateMiddle

Truncates a given text in the middle if it exceeds the specified length.

public static function truncateMiddle(mixed $text = '', ?int $length = 50, $signifyChopWith = '...'): string

Parameters:

  • $text (mixed): The text to truncate. Default is an empty string.
  • $length (int|null): The maximum length of the truncated text. Default is 50.
  • $signifyChopWith (string): The string to insert at the truncation point. Default is '...'.

Returns:

  • (string): The truncated text, if necessary.

Lists Helper

The Lists class provides various helper methods for manipulating and working with arrays.

Namespace: Medialight\Textstem\Helpers

ensureArray

Ensures the input is converted to an array.

public static function ensureArray($input): array

Parameters:

  • $input (mixed): The input to be converted to an array.

Returns:

  • (array): The converted array.

toggleItem

Toggle the presence of an item in an array. If the item exists, it will be removed. If it doesn't exist, it will be added.

public static function toggleItem(&$array, $item): void

Parameters:

  • $array (array): The array to modify (passed by reference).
  • $item (mixed): The item to toggle in the array.

Returns:

  • (void)

addOnce

Add an item to an array only if it doesn't already exist.

public static function addOnce(&$array, $item): void

Parameters:

  • $array (array): The array to modify (passed by reference).
  • $item (mixed): The item to add to the array if it doesn't exist.

Returns:

  • (void)

scalarList

Check if all elements in the array are scalar values.

public static function scalarList(array $arr): bool

Parameters:

  • $arr (array): The array to check.

Returns:

  • (bool): True if all elements are scalar values, false otherwise.

objectList

Check if all elements in the array are objects.

public static function objectList(array $arr): bool

Parameters:

  • $arr (array): The array to check.

Returns:

  • (bool): True if all elements are objects, false otherwise.

clean

Clean an array by trimming string values and removing empty or null values.

public static function clean(array $arr): array

Parameters:

  • $arr (array): The array to clean.

Returns:

  • (array): The cleaned array with empty values removed and strings trimmed.

Addresses Helper

The Addresses class provides helper methods for formatting address information.

Namespace: Medialight\Textstem\Helpers

formatAddress

Formats the address details into HTML representation.

public static function formatAddress($record): string

Parameters:

  • $record (stdClass): The object containing address details.

Returns:

  • (string): The formatted HTML address.

Colours Helper

The Colours class provides helper methods for color manipulation and generation.

Namespace: Medialight\Textstem\Helpers

getColourSetFromStr

Generates a background and foreground color set from a string.

public static function getColourSetFromStr($str = 'undefined'): array

Parameters:

  • $str (string): The string to generate colors from. Default is 'undefined'.

Returns:

  • (array): An array containing the background color and foreground color.

colourFromStr

Generates a color from a string.

public static function colourFromStr($str): string

Parameters:

  • $str (string): The string to generate a color from.

Returns:

  • (string): The generated color in hexadecimal format.

getContrastColor

Determines the best contrast color (black or white) for a given background color.

public static function getContrastColor($hexcolor): string

Parameters:

  • $hexcolor (string): The hexadecimal color to find a contrast for.

Returns:

  • (string): Either 'black' or 'white' depending on which provides better contrast.

hsl2rgb

Converts HSL (Hue, Saturation, Lightness) color values to RGB hexadecimal format.

public static function hsl2rgb($H, $S, $V): string

Parameters:

  • $H (float): The hue value (0-1).
  • $S (float): The saturation value (0-1).
  • $V (float): The lightness/value (0-1).

Returns:

  • (string): The color in hexadecimal RGB format.

hueFromStr

Generates a hue value from a string using a hash function.

public static function hueFromStr($tstr): int

Parameters:

  • $tstr (string): The string to generate a hue from.

Returns:

  • (int): The generated hue value.

colourSet

Returns a predefined set of colors.

public static function colourSet(): array

Returns:

  • (array): An array of hexadecimal color values.

textColor

Determines the best text color (black or white) based on RGB values.

public static function textColor($r, $g, $b): string

Parameters:

  • $r (int): The red component (0-255).
  • $g (int): The green component (0-255).
  • $b (int): The blue component (0-255).

Returns:

  • (string): Either '#000' (black) or '#FFF' (white) depending on which provides better contrast.

Dates Helper

The Dates class provides helper methods for formatting dates and times.

Namespace: Medialight\Textstem\Helpers

format_date

Formats a date string according to the specified format.

public static function format_date($date, $format = 'd/m/y'): string

Parameters:

  • $date (string): The date string to format.
  • $format (string): The format to use. Default is 'd/m/y'.

Returns:

  • (string): The formatted date string or an empty string if the input is empty.

format_time

Formats a time string according to the specified format.

public static function format_time($date, $format = 'h:m a'): string

Parameters:

  • $date (string): The date/time string to format.
  • $format (string): The format to use. Default is 'h:m a'.

Returns:

  • (string): The formatted time string or an empty string if the input is empty.

format_datetime

Formats a date and time string according to the specified format.

public static function format_datetime($date, $format = 'd/m/y h:m a'): string

Parameters:

  • $date (string): The date/time string to format.
  • $format (string): The format to use. Default is 'd/m/y h:m a'.

Returns:

  • (string): The formatted date and time string or an empty string if the input is empty.

format_datetime_ml

Formats a date and time string on multiple lines.

public static function format_datetime_ml($date, $format = 'd/m/y', $format2 = 'h:m a'): string

Parameters:

  • $date (string): The date/time string to format.
  • $format (string): The format to use for the date. Default is 'd/m/y'.
  • $format2 (string): The format to use for the time. Default is 'h:m a'.

Returns:

  • (string): The formatted date and time string with a line break between them, or an empty string if the input is empty.

format_daterange_str

Display a daterange in a compact format.

public static function format_daterange_str($start_date = '', $end_date = ''): string

Parameters:

  • $start_date (string): The start date string.
  • $end_date (string): The end date string.

Returns:

  • (string): The formatted date range string.

formatTimeRange

Given two time objects, return a formatted time range that is formatted nicely and compactly.

public static function formatTimeRange($t1, $t2): string

Parameters:

  • $t1 (mixed): The start time (string or timestamp).
  • $t2 (mixed): The end time (string or timestamp).

Returns:

  • (string): The formatted time range string.

CastStrData Helper

The CastStrData class provides helper methods for casting data to different types.

Namespace: Medialight\Textstem\Helpers

cast

Casts a value to the specified type.

public static function cast($v, $casts)

Parameters:

  • $v (mixed): The value to cast.
  • $casts (string): The type to cast to ('array', 'int', or default).

Returns:

  • (mixed): The value cast to the specified type.

Countries Helper

The Countries class provides helper methods for working with country data.

Namespace: Medialight\Textstem\Helpers

countryCode

Gets the country code for a given country name.

public static function countryCode($country): bool|int|string

Parameters:

  • $country (string): The country name to get the code for.

Returns:

  • (bool|int|string): The country code if found, or false/0 if not found.

DataHelper Helper

The DataHelper class provides helper methods for data manipulation and validation.

Namespace: Medialight\Textstem\Helpers

castAsId

Casts a value to an integer ID.

public static function castAsId($value): int

Parameters:

  • $value (mixed): The value to cast to an ID.

Returns:

  • (int): The value cast to an integer ID, or 0 if the value cannot be cast.

isDate

Checks if a string is a valid date.

public static function isDate($dateStr): bool

Parameters:

  • $dateStr (string): The string to check.

Returns:

  • (bool): True if the string is a valid date, false otherwise.

isDateTime

Checks if a string or object is a valid date/time.

public static function isDateTime($dateStr): bool

Parameters:

  • $dateStr (mixed): The string or object to check.

Returns:

  • (bool): True if the input is a valid date/time, false otherwise.

emptySet

An empty method with no implementation.

public static function emptySet()

Returns:

  • (void)

DirectoryTree Helper

The DirectoryTree class provides helper methods for rendering a directory tree as HTML.

Namespace: Medialight\Textstem\Helpers

make

Static method that creates a new instance and calls render.

public static function make(): string

Returns:

  • (string): The rendered HTML directory tree.

render

Renders the entire directory tree.

public function render(): string

Returns:

  • (string): The rendered HTML directory tree.

renderNode

Renders a single node in the tree.

public function renderNode($node): void

Parameters:

  • $node (array): The node to render.

Returns:

  • (void): This method modifies the internal tree property.

FileHelper Helper

The FileHelper class provides helper methods for file operations.

Namespace: Medialight\Textstem\Helpers

__construct (FileHelper)

Constructor that takes a source file path.

public function __construct($src, $disk = 'public')

Parameters:

  • $src (string): The source file path.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (void)

rename

Renames a file.

public function rename($newName): string

Parameters:

  • $newName (string): The new name or path for the file.

Returns:

  • (string): The new path of the file.

copy {#copy}

Copies a file.

public function copy($newName): string

Parameters:

  • $newName (string): The new name or path for the copied file.

Returns:

  • (string): The path of the copied file.

moveFile {#movefile}

Static method to move a file.

public static function moveFile($fileName, $newPath, $disk = 'public'): string

Parameters:

  • $fileName (string): The file to move.
  • $newPath (string): The new path for the file.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (string): The new path of the file.

copyFile {#copyfile}

Static method to copy a file.

public static function copyFile($fileName, $newPath, $disk = 'public'): string

Parameters:

  • $fileName (string): The file to copy.
  • $newPath (string): The new path for the copied file.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (string): The path of the copied file.

duplicateFile {#duplicatefile}

Static method to duplicate a file.

public static function duplicateFile($fileName, $disk = 'public'): string

Parameters:

  • $fileName (string): The file to duplicate.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (string): The path of the duplicated file, or an empty string if the original file doesn't exist.

getNewFileName {#getnewfilename}

Static method to get a new file name.

public static function getNewFileName($fileName, $disk = 'public'): string

Parameters:

  • $fileName (string): The original file name.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (string): A new file name that doesn't exist in the storage.

assetTypeFromMime {#assettypefrommime}

Determines the asset type based on the given MIME type.

public static function assetTypeFromMime($mime): string

Parameters:

  • $mime (string): The MIME type of the asset.

Returns:

  • (string): The asset type, which can be one of the following:
    • "image" for image assets
    • "video" for video assets
    • "audio" for audio assets
    • "file" for other types of assets

FolderHelper Helper {#folderhelper-helper}

The FolderHelper class provides helper methods for folder operations.

Namespace: Medialight\Textstem\Helpers

__construct (FolderHelper) {#__construct-folderhelper}

Constructor that takes a source folder path.

public function __construct($src, $disk = 'public')

Parameters:

  • $src (string): The source folder path.
  • $disk (string): The storage disk to use. Default is 'public'.

Returns:

  • (void)

directoryTree {#directorytree}

Returns a tree structure of directories.

public function directoryTree(): array

Returns:

  • (array): A tree structure of directories.

browse {#browse}

Returns a list of directories and files in the source folder.

public function browse(): array

Returns:

  • (array): A list of directories and files in the source folder.

Formatters Helper {#formatters-helper}

The Formatters class provides helper methods for formatting various types of data.

Namespace: Medialight\Textstem\Helpers

format_for_id {#format_for_id}

Formats a string for use as an ID.

public static function format_for_id($str)

Parameters:

  • $str (string): The string to format.

Returns:

  • (string): The formatted string suitable for use as an ID.

format_for_sort {#format_for_sort}

Formats a string for sorting.

public static function format_for_sort($str)

Parameters:

  • $str (string): The string to format.

Returns:

  • (string): The formatted string suitable for sorting.

format_from_name_sort {#format_from_name_sort}

Formats a string from a name sort.

public static function format_from_name_sort($str, $harsh)

Parameters:

  • $str (string): The string to format.
  • $harsh (bool): Whether to use harsh formatting.

Returns:

  • (string): The formatted string.

nicefy (Formatters) {#nicefy-formatters}

Makes a string more readable.

public static function nicefy($str, $ucwrds, $keepHyphens)

Parameters:

  • $str (string): The string to format.
  • $ucwrds (bool): Whether to convert the result to title case.
  • $keepHyphens (bool): Whether to keep hyphens in the string.

Returns:

  • (string): The formatted string.

titleFromFileName {#titlefromfilename}

Extracts a title from a file name.

public static function titleFromFileName($filepath)

Parameters:

  • $filepath (string): The file path to extract a title from.

Returns:

  • (string): The extracted title.

format_daterange_str (Formatters) {#format_daterange_str-formatters}

Formats a date range.

public static function format_daterange_str($start_date, $end_date)

Parameters:

  • $start_date (string): The start date string.
  • $end_date (string): The end date string.

Returns:

  • (string): The formatted date range string.

formatTimeRange (Formatters) {#formattimerange-formatters}

Formats a time range.

public static function formatTimeRange($t1, $t2)

Parameters:

  • $t1 (mixed): The start time (string or timestamp).
  • $t2 (mixed): The end time (string or timestamp).

Returns:

  • (string): The formatted time range string.

makePreview {#makepreview}

Creates a preview of an array.

public static function makePreview($arr, $maxchar)

Parameters:

  • $arr (array): The array to create a preview of.
  • $maxchar (int): The maximum number of characters in the preview.

Returns:

  • (string): The preview string.

Images Helper {#images-helper}

The Images class provides helper methods for working with images.

Namespace: Medialight\Textstem\Helpers

imageFromAsset {#imagefromasset}

Creates an HTML img tag from an asset.

public static function imageFromAsset($asset, $attributes = [])

Parameters:

  • $asset (object): The asset object.
  • $attributes (array): Additional attributes for the img tag.

Returns:

  • (string): The HTML img tag.

pictureFromAsset {#picturefromasset}

Creates an HTML picture tag from an asset.

public static function pictureFromAsset($asset, $attributes = [])

Parameters:

  • $asset (object): The asset object.
  • $attributes (array): Additional attributes for the img tag inside the picture tag.

Returns:

  • (string): The HTML picture tag.

getExifThumb {#getexifthumb}

Extracts an EXIF thumbnail from an image.

public static function getExifThumb($path, $thumbPath)

Parameters:

  • $path (string): The path to the image.
  • $thumbPath (string): The path to save the thumbnail to.

Returns:

  • (mixed): The result of saving the thumbnail, or null if no thumbnail was found.

JsonFormatter Helper {#jsonformatter-helper}

The JsonFormatter class provides helper methods for formatting JSON data.

Namespace: Medialight\Textstem\Helpers

spaced {#spaced}

Adds spaces after commas and colons in JSON.

public static function spaced($json)

Parameters:

  • $json (string): The JSON string to format.

Returns:

  • (string): The formatted JSON string.

array {#array}

Formats a JSON array as HTML badges.

public static function array($json, $link = '')

Parameters:

  • $json (string): The JSON string to format.
  • $link (string): Optional link to wrap around each badge.

Returns:

  • (string): The HTML badges.

objectBadges {#objectbadges}

Parses JSON into objects and loops through printing as badges assuming obj->name exists.

public static function objectBadges($json, $link = '')

Parameters:

  • $json (string): The JSON string to format.
  • $link (string): Optional link to wrap around each badge.

Returns:

  • (string): The HTML badges.

generateHtmlFromJson {#generatehtmlfromjson}

Generates HTML from JSON data.

public static function generateHtmlFromJson($data)

Parameters:

  • $data (mixed): The JSON data to format (string or array).

Returns:

  • (string): The generated HTML.

generateHtmlForElement {#generatehtmlforelement}

Generates HTML for a specific element.

public static function generateHtmlForElement($key, $value)

Parameters:

  • $key (string): The key of the element.
  • $value (mixed): The value of the element.

Returns:

  • (string): The generated HTML.

MediaAsset Helper {#mediaasset-helper}

The MediaAsset class provides helper methods for working with media assets.

Namespace: Medialight\Textstem\Helpers

loadForPath {#loadforpath}

Loads an asset for a given path.

public static function loadForPath($srcPath, $alwaysCreate = false)

Parameters:

  • $srcPath (string): The source path of the asset.
  • $alwaysCreate (bool): Whether to always create a new asset if one doesn't exist. Default is false.

Returns:

  • (mixed): The asset object or null if not found and not created.

checkAssetFile {#checkassetfile}

Checks if an asset file exists.

public static function checkAssetFile($asset): bool

Parameters:

  • $asset (object): The asset object to check.

Returns:

  • (bool): True if the asset file exists, false otherwise.

checkAssetThumb {#checkassetthumb}

Checks if an asset thumbnail exists.

public static function checkAssetThumb($asset)

Parameters:

  • $asset (object): The asset object to check.

Returns:

  • (mixed): The result of checking the thumbnail.

checkThumb {#checkthumb}

Checks if a thumbnail exists for a given path.

public static function checkThumb($srcPath, $thumbPath = null, $useExistingIfExists = true, $silent = false, $x = null, $y = null)

Parameters:

  • $srcPath (string): The source path of the image.
  • $thumbPath (string|null): The path to save the thumbnail to. Default is null.
  • $useExistingIfExists (bool): Whether to use an existing thumbnail if it exists. Default is true.
  • $silent (bool): Whether to suppress errors. Default is false.
  • $x (int|null): The width of the thumbnail. Default is null.
  • $y (int|null): The height of the thumbnail. Default is null.

Returns:

  • (mixed): The result of checking or creating the thumbnail.

thumbPath {#thumbpath}

Gets the thumbnail path for a given source path.

public static function thumbPath($srcPath): string

Parameters:

  • $srcPath (string): The source path of the image.

Returns:

  • (string): The thumbnail path.

makeThumb {#makethumb}

Creates a thumbnail for a given image path.

public static function makeThumb($srcImgPath): string

Parameters:

  • $srcImgPath (string): The source path of the image.

Returns:

  • (string): The path of the created thumbnail.

createAssetForFile {#createassetforfile}

Creates an asset for a given file path.

public static function createAssetForFile($file_path, $info = null)

Parameters:

  • $file_path (string): The path of the file.
  • $info (array|null): Additional information about the file. Default is null.

Returns:

  • (mixed): The created asset object.

assetTypeFromMime (MediaAsset) {#assettypefrommime-mediaasset}

Determines the asset type from a MIME type.

public static function assetTypeFromMime($mime)

Parameters:

  • $mime (string): The MIME type of the asset.

Returns:

  • (string): The asset type.

MimeType Helper {#mimetype-helper}

The MimeType class provides helper methods for working with MIME types.

Namespace: Medialight\Textstem\Helpers

getMimeFromExtension {#getmimefromextension}

Gets the MIME type for a given file extension.

public static function getMimeFromExtension($ext)

Parameters:

  • $ext (string): The file extension.

Returns:

  • (string): The MIME type for the given extension.

Model Helper

The Model class provides helper methods for working with Eloquent models.

Namespace: Medialight\Textstem\Helpers

isModelUsingSoftDeletes

Checks if a model is using soft deletes.

public static function isModelUsingSoftDeletes($model): bool

Parameters:

  • $model (mixed): The model to check.

Returns:

  • (bool): True if the model is using soft deletes, false otherwise.

NumberFormats Helper

The NumberFormats class provides helper methods for formatting numbers, particularly file sizes.

Namespace: Medialight\Textstem\Helpers

bytesToHuman

Converts bytes to a human-readable format (e.g., KB, MB, GB).

public static function bytesToHuman($size, $precision = 2): string

Parameters:

  • $size (int): The size in bytes.
  • $precision (int): The number of decimal places to round to. Default is 2.

Returns:

  • (string): The human-readable file size.

humanToBytes

Converts a human readable file size value to a number of bytes that it represents. Supports the following modifiers: K, M, G and T.

public static function humanToBytes($value): int

Parameters:

  • $value (number|string): The human-readable file size (e.g., '10K', '5MB').

Returns:

  • (int): The size in bytes.

Examples:

humanToBytes(10);          // 10
humanToBytes('10b');       // 10
humanToBytes('10k');       // 10240
humanToBytes('10K');       // 10240
humanToBytes('10kb');      // 10240
humanToBytes('10Kb');      // 10240
humanToBytes('   10 KB '); // 10240

OpenAiHelper Helper

The OpenAiHelper class provides helper methods for working with OpenAI prompts.

Namespace: Medialight\Textstem\Helpers

prepareForPrompt

Prepares text for a prompt by trimming and limiting its length.

public static function prepareForPrompt(?string $text = '', int $maxTokens = 2000): string

Parameters:

  • $text (string|null): The text to prepare. Default is an empty string.
  • $maxTokens (int): The maximum number of tokens allowed. Default is 2000.

Returns:

  • (string): The prepared text.

getContentFromHtml

Extracts content from HTML for use in a prompt.

public static function getContentFromHtml(?string $html = '', int $maxTokens = 2000): string

Parameters:

  • $html (string|null): The HTML to extract content from. Default is an empty string.
  • $maxTokens (int): The maximum number of tokens allowed. Default is 2000.

Returns:

  • (string): The extracted content.

OptionFormatter Helper

The OptionFormatter class provides helper methods for formatting options arrays.

Namespace: Medialight\Textstem\Helpers

format

Makes sure an array of options takes a specific format.

public static function format($setup, $class = null)

Parameters:

  • $setup (mixed): The array of options to format, or a string which is either a method name in the component class or class name for a helper class (which should have method 'collectForSelectOptions').
  • $class (ClassString): The class of the component being set up. Default is null.

Returns:

  • (array): The formatted options array.

Format:

'options' => [
    'label' => 'Choose One',
    'value' => "value_1"
], [
    // ...etc
]

This function lets you specify options as a simple linear array like this:

'options' => ['publish', 'pending', 'archive']

Linear lists are treated as lists of values (and a label is created using the nicefy method). If you want to treat the list as a list of labels (and use the index or key as the value), include 'usekey' = 1 in the setup.

Smartcrop Helper

The Smartcrop class provides helper methods for intelligently cropping images.

Namespace: Medialight\Textstem\Helpers

__construct (Smartcrop)

Constructor that takes an image and options.

public function __construct(Image $image, array $options)

Parameters:

  • $image (Image): The image to crop.
  • $options (array): Options for the cropping algorithm.

Returns:

  • (void)

canvasImageScale

Scales the canvas image.

public function canvasImageScale()

Returns:

  • (mixed): The scaled canvas image.

analyse

Analyzes the image.

public function analyse()

Returns:

  • (mixed): The analysis result.

downSample

Downsamples the image.

public function downSample($factor)

Parameters:

  • $factor (int): The factor to downsample by.

Returns:

  • (mixed): The downsampled image.

edgeDetect

Detects edges in the image.

public function edgeDetect($x, $y, $w, $h)

Parameters:

  • $x (int): The x-coordinate.
  • $y (int): The y-coordinate.
  • $w (int): The width.
  • $h (int): The height.

Returns:

  • (mixed): The edge detection result.

skinDetect

Detects skin in the image.

public function skinDetect($r, $g, $b, $lightness)

Parameters:

  • $r (int): The red component.
  • $g (int): The green component.
  • $b (int): The blue component.
  • $lightness (float): The lightness value.

Returns:

  • (mixed): The skin detection result.

saturationDetect

Detects saturation in the image.

public function saturationDetect($r, $g, $b, $lightness)

Parameters:

  • $r (int): The red component.
  • $g (int): The green component.
  • $b (int): The blue component.
  • $lightness (float): The lightness value.

Returns:

  • (mixed): The saturation detection result.

generateCrops

Generates crop options.

public function generateCrops()

Returns:

  • (array): The generated crop options.

score

Scores a crop option.

public function score($output, $crop)

Parameters:

  • $output (array): The output data.
  • $crop (array): The crop option to score.

Returns:

  • (float): The score of the crop option.

importance

Calculates the importance of a pixel.

public function importance($crop, $x, $y)

Parameters:

  • $crop (array): The crop option.
  • $x (int): The x-coordinate.
  • $y (int): The y-coordinate.

Returns:

  • (float): The importance value.

thirds

Applies the rule of thirds.

public function thirds($x)

Parameters:

  • $x (float): The position value.

Returns:

  • (float): The thirds value.

sample

Samples a pixel.

public function sample($x, $y)

Parameters:

  • $x (int): The x-coordinate.
  • $y (int): The y-coordinate.

Returns:

  • (array): The sampled pixel data.

cie

Converts RGB to CIE.

public function cie($r, $g, $b)

Parameters:

  • $r (int): The red component.
  • $g (int): The green component.
  • $b (int): The blue component.

Returns:

  • (float): The CIE value.

skinColor

Detects skin color.

public function skinColor($r, $g, $b)

Parameters:

  • $r (int): The red component.
  • $g (int): The green component.
  • $b (int): The blue component.

Returns:

  • (float): The skin color value.

saturation

Calculates saturation.

public function saturation($r, $g, $b)

Parameters:

  • $r (int): The red component.
  • $g (int): The green component.
  • $b (int): The blue component.

Returns:

  • (float): The saturation value.

TailwindGenerator Helper

The TailwindGenerator class provides helper methods for generating Tailwind CSS classes.

Namespace: Medialight\Textstem\Helpers

widthClasses

Generates a string of tailwind CSS classes for column widths based on the given widths and prefixes.

public static function widthClasses(...$widths)

Parameters:

  • $widths (int): The column widths for which the CSS classes should be generated. Multiple widths can be specified as separate arguments.

Returns:

  • (string): The generated CSS classes as a space-separated string.

spanClasses

Generates a string of tailwind CSS classes for column spans based on the given widths.

public static function spanClasses(...$widths)

Parameters:

  • $widths (int): The column widths for which the CSS classes should be generated. Multiple widths can be specified as separate arguments.

Returns:

  • (string): The generated CSS classes as a space-separated string.

colSpanToWidth

Converts a column span value to a corresponding tailwind width class. Eg colspan of "12" corresponds to "w-full".

public static function colSpanToWidth($span, $prefix = '')

Parameters:

  • $span (int): The column span value to be converted.
  • $prefix (string): Optional prefix to be prepended to the CSS width class.

Returns:

  • (string): The CSS width class corresponding to the given column span value.

formatForSelectOptions

Formats an array for select options.

public function formatForSelectOptions($arr)

Parameters:

  • $arr (array): The array to format.

Returns:

  • (array): The formatted array.

Thumbnails Helper

The Thumbnails class provides helper methods for working with thumbnail sizes.

Namespace: Medialight\Textstem\Helpers

sizeRules

Returns size rules for a given size name.

public static function sizeRules($sizeName)

Parameters:

  • $sizeName (string): The name of the size to get rules for.

Returns:

  • (object): An object with width, height, and fit properties.

JsonHelper Helper

The JsonHelper class provides secure JSON decoding with depth and size limits to prevent DoS attacks from deeply nested payloads.

Namespace: Medialight\Textstem\Helpers

Limits: max depth 512 (PHP default), max size 10 MB.

safeDecode

Safely decodes a JSON string, throwing on invalid input or limit violations.

public static function safeDecode(string $json, bool $assoc = true, ?int $maxDepth = null): array|object|null

Parameters:

  • $json (string): JSON string to decode.
  • $assoc (bool): When true (default), returns associative arrays instead of objects.
  • $maxDepth (int|null): Override the depth limit. Defaults to 512.

Returns:

  • (array|object|null): Decoded value.

Throws: \InvalidArgumentException if the JSON is invalid or exceeds limits.

safeDecodeArray

Decodes JSON with a fallback to a default array on failure. Logs a warning instead of throwing.

public static function safeDecodeArray(?string $json, array $default = []): array

Parameters:

  • $json (string|null): JSON string to decode.
  • $default (array): Returned when $json is empty or decoding fails. Default is [].

Returns:

  • (array): Decoded array or $default.

isValid

Validates a JSON string without decoding it.

public static function isValid(string $json): bool

Parameters:

  • $json (string): JSON string to validate.

Returns:

  • (bool): True if the string is valid JSON and within the size limit.

Urls Helper

The Urls class is a Laravel facade backed by Medialight\Textstem\Services\UrlsService (accessor: urls). It provides URL manipulation utilities.

Namespace: Medialight\Textstem\Helpers

url_add_query_params

Adds or merges query parameters onto a URL, preserving any existing query string.

public static function url_add_query_params(mixed $url, ?array $params = null): string

Parameters:

  • $url (string|array): Target URL, or an associative array of params to apply to the current request URL.
  • $params (array|null): Key/value pairs to add. When null, $url is treated as the params array and the current request URL is used as the base.

Returns:

  • (string): The resulting URL with merged query string.

Example:

Urls::url_add_query_params('https://example.com/page?foo=1', ['bar' => 2]);
// https://example.com/page?foo=1&bar=2

itemUrl

Generates a URL for a resource item, either as a path segment or query string.

public static function itemUrl(string $base, string|int $id, string $key = 'id', bool $nice = true): string

Parameters:

  • $base (string): The base URL.
  • $id (string|int): The item identifier.
  • $key (string): The parameter name. Default is 'id'.
  • $nice (bool): When true (default), produces a path-style URL (/base/key/123). When false, uses a query string (/base?key=123).

Returns:

  • (string): The constructed URL.

VideoHelper Helper

The VideoHelper class is a Laravel facade backed by Medialight\Textstem\Services\VideoHelperService (accessor: videohelper). It wraps FFProbe for video metadata extraction.

Namespace: Medialight\Textstem\Helpers

Requires the FFProbe class to be available (provided by php-ffmpeg/php-ffmpeg).

isEnabled

Checks whether FFProbe is available in the current environment.

public static function isEnabled(): bool

Returns:

  • (bool): True if the FFProbe class exists and video inspection is available.

getVideoInfo

Retrieves width, height, and duration metadata for a video file.

public static function getVideoInfo(string $videoURL): array

Parameters:

  • $videoURL (string): Path or URL to the video file.

Returns:

  • (array): ['width' => int, 'height' => int, 'duration' => float], or an empty array if FFProbe is unavailable.
esc