migunov/laravel-services

Little Useful Services for Laravel

1.6.10 2025-06-14 08:43 UTC

This package is auto-updated.

Last update: 2025-06-14 05:47:53 UTC


README

A collection of everyday useful services designed for Laravel applications.

Installing

composer require migunov/laravel-services

Usage

Below is a guide to the services and their public methods.

Helper Service

The Helper class provides a collection of static utility methods.

fileExtension(string $path): string

Extracts the file extension from a given path string.

Signature:

Migunov\Services\Helper::fileExtension(string $path): string

Example:

use Migunov\Services\Helper;

$extension = Helper::fileExtension('storage/files/document.pdf?version=2');
// $extension will be '.pdf'

$extension = Helper::fileExtension('archive.tar.gz');
// $extension will be '.gz'

$extension = Helper::fileExtension('no_extension_file');
// $extension will be ''

fileExtensionFromMime(string $contentType): string

Extracts a file extension from a MIME type string.

Signature:

Migunov\Services\Helper::fileExtensionFromMime(string $contentType): string

Example:

use Migunov\Services\Helper;

$extension = Helper::fileExtensionFromMime('image/jpeg');
// $extension will be '.jpeg'

$extension = Helper::fileExtensionFromMime('application/vnd.oasis.opendocument.text');
// $extension will be '.opendocument.text' (Note: current implementation filters for 'image/' prefix, so this example might not work as expected with current code. It would return '')

$extension = Helper::fileExtensionFromMime('image/svg+xml');
// $extension will be '.svg'

getMetaTags(string $urlOrContent, bool $noThrow = true): array

Fetches and parses meta tags from a given URL or HTML content string.

Signature:

Migunov\Services\Helper::getMetaTags(string $urlOrContent, bool $noThrow = true): array

Example:

use Migunov\Services\Helper;

// From URL
$metaFromUrl = Helper::getMetaTags('https://example.com');
/*
$metaFromUrl might look like:
[
    'title' => 'Example Domain',
    'description' => 'This domain is for use in illustrative examples in documents.',
    // ... other meta tags like 'og:title', 'icon', etc.
]
*/

// From HTML content
$htmlContent = '<!DOCTYPE html><html><head><title>My Page</title><meta name="description" content="Page description."></head><body></body></html>';
$metaFromHtml = Helper::getMetaTags($htmlContent);
/*
$metaFromHtml will be:
[
    'title' => 'My Page',
    'description' => 'Page description.'
]
*/

host(string $url, bool $onlyDomain = true): string

Extracts the host (and optionally port) from a URL. If $onlyDomain is false, the scheme is also included.

Signature:

Migunov\Services\Helper::host(string $url, bool $onlyDomain = true): string

Example:

use Migunov\Services\Helper;

$hostOnly = Helper::host('https://www.example.com:8080/path?query=1');
// $hostOnly will be 'www.example.com:8080'

$fullHost = Helper::host('http://localhost:3000/test', false);
// $fullHost will be 'http://localhost:3000'

htmlCut(string $text, int $maxLength): string

Truncates HTML text to a specified maximum length of visible characters, attempting to preserve HTML tag integrity by closing any open tags. Note: This function can be complex with deeply nested or malformed HTML. Test thoroughly.

Signature:

Migunov\Services\Helper::htmlCut(string $text, int $maxLength): string

Example:

use Migunov\Services\Helper;

$html = '<p>This is some <strong>bold</strong> and <em>italic</em> text.</p>';
$cutHtml = Helper::htmlCut($html, 15); // Truncate to 15 visible characters
// $cutHtml might be '<p>This is some <strong>bo</strong></p>'
// (Visible text: "This is some bo")

$html2 = '<div><span><em>Complex nesting</em></span></div>';
$cutHtml2 = Helper::htmlCut($html2, 7); // Truncate to 7 visible characters
// $cutHtml2 will be '<div><span><em>Complex</em></span></div>'
// (Visible text: "Complex")

httpClient(): Illuminate\Http\Client\PendingRequest

Returns a Laravel HTTP client instance pre-configured with a common user agent (Mozilla/5.0 ...).

Signature:

Migunov\Services\Helper::httpClient(): Illuminate\Http\Client\PendingRequest

Example:

use Migunov\Services\Helper;

$response = Helper::httpClient()->get('https://api.example.com/data');
if ($response->successful()) {
    $data = $response->json();
}

sanitizeData(array $data): array

Trims whitespace from string values within an array. Non-string values and non-UTF-8 strings are returned unchanged. Array keys are not affected.

Signature:

Migunov\Services\Helper::sanitizeData(array $data): array

Example:

use Migunov\Services\Helper;

$input = ['name' => '  John Doe  ', ' email ' => ' test@example.com ', 'age' => 30];
$sanitized = Helper::sanitizeData($input);
/*
$sanitized will be:
[
    'name' => 'John Doe',
    ' email ' => 'test@example.com', // Note: key " email " is not trimmed
    'age' => 30
]
*/

socialName(string $url): string

Identifies a social network name (e.g., 'facebook', 'github', 'x-twitter') from a URL. If no specific social network is matched, it returns the host (with 'www.' removed if present). Returns an empty string for invalid URLs or if the host cannot be parsed.

Signature:

Migunov\Services\Helper::socialName(string $url): string

Example:

use Migunov\Services\Helper;

$name1 = Helper::socialName('https://twitter.com/laravelphp');
// $name1 will be 'x-twitter'

$name2 = Helper::socialName('https://www.mypersonalblog.com/article');
// $name2 will be 'mypersonalblog.com'

$name3 = Helper::socialName('invalid-url');
// $name3 will be ''

stringToArray(string $value, string $separator = ','): array

Splits a string by a specified separator and trims whitespace from each resulting element. If the separator is an empty string, the original value is returned as a single-element array (after trimming).

Signature:

Migunov\Services\Helper::stringToArray(string $value, string $separator = ','): array

Example:

use Migunov\Services\Helper;

$tags = Helper::stringToArray(' php, laravel , web development ');
// $tags will be ['php', 'laravel', 'web development']

$items = Helper::stringToArray('item1|item2 | item3', '|');
// $items will be ['item1', 'item2', 'item3']

timeFormat(int $seconds): string

Formats a duration in seconds into a human-readable string (e.g., "1 hr. 30 min.", "3 minutes"). For durations less than one hour, the number of minutes is determined by rounding. Note: Currently provides English-only output. Returns an empty string for durations less than 10 seconds.

Signature:

Migunov\Services\Helper::timeFormat(int $seconds): string

Example:

use Migunov\Services\Helper;

echo Helper::timeFormat(9);      // Outputs: ''
echo Helper::timeFormat(10);     // Outputs: '1 minute'
echo Helper::timeFormat(59);     // Outputs: '1 minute'
echo Helper::timeFormat(119);    // Outputs: '2 minutes'
echo Helper::timeFormat(150);    // Outputs: '3 minutes'
echo Helper::timeFormat(3599);   // Outputs: '60 minutes'
echo Helper::timeFormat(5400);   // Outputs: '1 hr. 30 min.'
echo Helper::timeFormat(90000);  // Outputs: '1 d. 1 hr. 0 min.'

ImageService

The ImageService provides methods for image manipulation, leveraging the Intervention Image library. Note: All file paths used in these methods are typically relative to your public storage disk (e.g., storage/app/public/).

getManager(string $driver = 'gd'): Intervention\Image\ImageManager

Returns an Intervention Image manager instance.

Signature:

Migunov\Services\ImageService::getManager(string $driver = 'gd'): Intervention\Image\ImageManager

Example:

use Migunov\Services\ImageService;

$manager = ImageService::getManager(); // Uses 'gd' driver by default
$image = $manager->read('path/to/your/image.jpg');

isImageFile(string $path): bool

Checks if a given path likely points to an image file based on its extension.

Signature:

Migunov\Services\ImageService::isImageFile(string $path): bool

Example:

use Migunov\Services\ImageService;

ImageService::isImageFile('photo.jpg');    // true
ImageService::isImageFile('document.pdf'); // false

saveImageFromUrlPage(string $url, string $path, array $params): ?array

Downloads the og:image from a webpage URL, saves it, and creates specified resized versions. The $path is the directory within public storage to save images. The $params array defines dimensions for the original and derived images.

Signature:

Migunov\Services\ImageService::saveImageFromUrlPage(string $url, string $path, array $params): ?array

Example $params structure:

$params = [
    // Main image
    ['name' => 'my-image', 'width' => 1200, 'height' => 600],
    // Preview version
    ['postfix' => '.preview.jpg', 'width' => 400, 'height' => 400],
    // Mini version
    ['postfix' => '.mini.jpg', 'width' => 64, 'height' => 64],
];
$savedPaths = Migunov\Services\ImageService::saveImageFromUrlPage('https://example.com', 'articles/images', $params);
// $savedPaths might be: ['articles/images/my-image.jpg', 'articles/images/my-image.jpg.preview.jpg', 'articles/images/my-image.jpg.mini.jpg']
// or null if og:image is not found.

cover(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

Resizes the image to fill the specified dimensions, cropping if necessary to maintain aspect ratio.

Signature:

Migunov\Services\ImageService::cover(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

crop(string $path, int $width = 1200, int $height = 600, float $x = 0, float $y = 0, ?string $targetPath = null): void

Crops an image to the specified dimensions from a starting (x, y) coordinate.

Signature:

Migunov\Services\ImageService::crop(string $path, int $width = 1200, int $height = 600, float $x = 0, float $y = 0, ?string $targetPath = null): void

cropAndResize(string $path, int $width = 1200, int $height = 600, float $x = 0, float $y = 0, int $newWidth = 300, int $newHeight = 300, ?string $targetPath = null): void

First crops the image, then resizes the cropped portion.

Signature:

Migunov\Services\ImageService::cropAndResize(string $path, int $width = 1200, int $height = 600, float $x = 0, float $y = 0, int $newWidth = 300, int $newHeight = 300, ?string $targetPath = null): void

resize(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

Resizes an image to the given dimensions, constraining aspect ratio. If width or height is 0 or less, it's auto-calculated.

Signature:

Migunov\Services\ImageService::resize(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

resizeDown(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

Resizes an image to the given dimensions only if the original image is larger. Aspect ratio is constrained.

Signature:

Migunov\Services\ImageService::resizeDown(string $path, int $width = 1200, int $height = 600, ?string $targetPath = null): void

General Image Manipulation Example:

use Migunov\Services\ImageService;
use Illuminate\Support\Facades\Storage;

// Assuming 'source.jpg' exists in storage/app/public/uploads/
$sourcePath = 'uploads/source.jpg';
$targetPath = 'uploads/source.resized.jpg';

if (Storage::disk('public')->exists($sourcePath)) {
    ImageService::resize($sourcePath, 300, 200, $targetPath);
    // Now 'storage/app/public/uploads/source.resized.jpg' contains the resized image.
}

ResponseService

The ResponseService helps in creating standardized JSON responses.

json(array $data, array $params = [], int $status = \Illuminate\Http\Response::HTTP_OK): \Illuminate\Http\JsonResponse

Creates a structured JSON response. It wraps the main data under a data key and adds a meta key for timestamp and any additional parameters.

Signature:

Migunov\Services\ResponseService::json(
    array $data,
    array $params = [],
    int $status = \Illuminate\Http\Response::HTTP_OK
): \Illuminate\Http\JsonResponse

Example:

use Migunov\Services\ResponseService;
use Illuminate\Http\Response;

// Basic success response
return ResponseService::json(['message' => 'User created successfully!'], [], Response::HTTP_CREATED);
/*
Output:
{
    "meta": {
        "timestamp": 1678886400 // Example timestamp
    },
    "data": {
        "message": "User created successfully!"
    }
}
*/

// Response with data and custom parameters
$user = ['id' => 1, 'name' => 'Jane Doe'];
return ResponseService::json($user, ['source' => 'api_v1']);
/*
Output:
{
    "meta": {
        "timestamp": 1678886400, // Example timestamp
        "params": {
            "source": "api_v1"
        }
    },
    "data": {
        "id": 1,
        "name": "Jane Doe"
    }
}
*/

This README provides a guide to the services. You can expand it with more details and examples as your library grows.