PHPackages                             starburst/utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. starburst/utils

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

starburst/utils
===============

1.19.0(11mo ago)011.7k↓43%1MITPHPPHP ^8.0

Since May 24Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/StarburstPhp/utils)[ Packagist](https://packagist.org/packages/starburst/utils)[ RSS](/packages/starburst-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (1)Versions (7)Used By (1)

Starburst Utils
===============

[](#starburst-utils)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9cf873a74a0daaf2bf05ff1264688ddf0ae36f7c4d3084407a11f45fa1640b05/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7374617262757273742f7574696c732e737667)](https://packagist.org/packages/starburst/utils)[![Software License](https://camo.githubusercontent.com/ddcfb352cb40d0a012bc90214085f7213efe585a6f1493a5816c9ac5bc0b9c63/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f5374617262757273745068702f7574696c732e737667)](LICENSE)

Package that contain some common helper classes

Requirements
------------

[](#requirements)

PHP 8.0 or higher.

Installation
------------

[](#installation)

```
composer require starburst/utils
```

Usage
-----

[](#usage)

### Json

[](#json)

The `Starburst\Utils\Json` class provides static methods for encoding and decoding Json in PHP. Below, you'll find detailed documentation on how to use it:

#### `encode(mixed $value, bool $encodeNull = true): ?string`

[](#encodemixed-value-bool-encodenull--true-string)

This method accepts a variable of any type and converts it to a JSON string.

**Parameters:**

- `$value (mixed)`: The value you want to encode to JSON.
- `$encodeNull (bool)`: If we should encode `null` as `string` or not

**Returns:**

- JSON Encoded string. If `$encodeNull` is false this can also return null

**Usage:**

```
$jsonString = \Starburst\Utils\Json::encode(["name" => "John Doe", "age" => 30]);

// behaviour is using encodeNull flag
\Starburst\Utils\Json::encode(null, encodeNull: true) === 'null';
\Starburst\Utils\Json::encode(null, encodeNull: false) === null;
```

#### `decode(string $value): mixed`

[](#decodestring-value-mixed)

This method accepts a JSON string and decodes it to the corresponding PHP value or array.

**Parameters:**

- `$value (string)`: The JSON string you want to decode.

**Returns:**

- The PHP value that was encoded in the JSON string. If json is an object it's returned as an assoc array

**Usage:**

```
$phpValue = \Starburst\Utils\Json::decode($jsonString);
```

#### `decodeArray(string $value, bool $allowNull = false): ?array`

[](#decodearraystring-value-bool-allownull--false-array)

This method decodes a JSON string to an associative array in PHP.

The method throws a JsonException if the decoded value is not an array.

**Parameters:**

- `$value (string)`: The JSON string you want to decode to an array.
- `$allowNull (bool)`: Allow encoded null values to return null without exception

**Returns:**

- The associative array that was encoded in the JSON string.

**Usage:**

```
$associativeArray = \Starburst\Utils\Json::decodeArray($jsonString);

// behaviour is using allowNull flag
\Starburst\Utils\Json::decodeArray('null', allowNull: false); // throw exception
\Starburst\Utils\Json::decodeArray('null', allowNull: true) === null;
```

#### `decodeList(string $value, bool $allowNull = false): ?array`

[](#decodeliststring-value-bool-allownull--false-array)

This method decodes a JSON string to a numeric array (list) in PHP.

The method throws a JsonException if the decoded value is not a list.

**Parameters:**

- `$value (string)`: The JSON string you want to decode to an array.
- `$allowNull (bool)`: Allow encoded null values to return null without exception

**Returns:**

- The numeric array (list) that was encoded in the JSON string.

**Usage:**

```
$list = \Starburst\Utils\Json::decodeList($jsonString);

// behaviour is using allowNull flag
\Starburst\Utils\Json::decodeList('null', allowNull: false); // throw exception
\Starburst\Utils\Json::decodeList('null', allowNull: true) === null;
```

### Validators

[](#validators)

The `Starburst\Utils\Validators` class provides static methods to validate different types of input.

### `isUnicode(mixed $value): bool`

[](#isunicodemixed-value-bool)

This function checks if the provided value is a valid UTF-8 string.

**Parameters:**

- `$value (mixed)`: The value you want to check.

**Returns:**

- True or false. It will always return false for none string types

**Usage:**

```
$isValid = \Starburst\Utils\Validators::isUnicode($value);
```

#### `isKennitala(mixed $value): bool`

[](#iskennitalamixed-value-bool)

This function checks if the provided value is a valid kennitala.

**Parameters:**

- `$value (mixed)`: The value you want to check.

**Returns:**

- True or false

**Usage:**

```
$isValid = \Starburst\Utils\Validators::isKennitala($value);
```

#### `isEmail(string $value): bool`

[](#isemailstring-value-bool)

This function checks if the provided string is a valid email address. Note that it only checks the syntax of the email and not if the email domain actually exists.

**Parameters:**

- `$value (string)`: The value you want to check.

**Returns:**

- True or false

**Usage:**

```
$isValid = \Starburst\Utils\Validators::isEmail($value);
```

#### `isIcelandicPhoneNumber(string $value): bool`

[](#isicelandicphonenumberstring-value-bool)

This function checks if the provided string is a valid icelandic phone number.

**Parameters:**

- `$value (string)`: The value you want to check.

**Returns:**

- True or false

**Usage:**

```
$isValid = \Starburst\Utils\Validators::isIcelandicPhoneNumber($value);
```

### Text

[](#text)

Static class that helps normalize texts

#### `normalize(string $value): string`

[](#normalizestring-value-string)

Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines, trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.

#### `truncate(string $string, int $maxLen, string $append = "\u{2026}"): string`

[](#truncatestring-string-int-maxlen-string-append--u2026-string)

Truncates a UTF-8 string to a given maximal length while trying not to split whole words. Only if the string is truncated, an ellipsis (or something else set with the third argument) is appended to the string.

#### `slugify(string $string, string $separator = '-', bool $allowPeriod = false, string $locale = 'is'): string`

[](#slugifystring-string-string-separator----bool-allowperiod--false-string-locale--is-string)

Converts a string into a URL-friendly slug by transliterating characters based on locale-specific rules.

Supported locales: 'de', 'is', 'en', 'ru', 'uk'

#### `normalizeIcelandicPhoneNumber(string $phoneNumber): string`

[](#normalizeicelandicphonenumberstring-phonenumber-string)

Normalizes a phone number to the format +3541234567.

If it's not a valid Icelandic phone number, throws InvalidArgumentException

### GetArrayCopy

[](#getarraycopy)

Trait that helps convert an object into an assoc array.

It supports value resolvers that can be used to format some properties in a custom way.

#### Example

[](#example)

```
class TestObject
{
	use \Starburst\Utils\Traits\GetArrayCopyTrait;

	public function __construct(
		public int $id,
		#[\Starburst\Utils\Attributes\DateFormat('Y-m-d')]
		public \DateTimeImmutable $startDate,
		public \DateTimeImmutable $createdOn,
		#[\Starburst\Utils\Attributes\HiddenProperty]
		public string $internalField,
		#[\Starburst\Utils\Attributes\CustomName('parent')]
		public ?TestObject $parentObject = null,
	) {}
}

$obj = new TestObject(
	1,
	new DateTimeImmutable('2024-05-24 08:00:00'),
	new DateTimeImmutable('2024-05-20 12:23:01'),
	'internalValue'
);

$obj->getArrayCopy() === [
	'id' => 1,
	'startOn' => '2024-05-24',
	'createdOn' => '2024-05-20 12:23:01',
	'parent' => null,
];
```

#### Configure custom value resolvers

[](#configure-custom-value-resolvers)

```
#[\Attribute(\Attribute::TARGET_PROPERTY)]
class CustomAttribute {}
class CustomResolver implements \Starburst\Utils\ValueResolvers\ValueResolver
{
	/**
	 * @param \WeakMap $tracker
	 */
	public function resolve(mixed $value, \WeakMap $tracker, ?\ReflectionProperty $reflectionProperty = null): mixed
	{
		$attrs = $reflectionProperty?->getAttributes(CustomAttribute::class);
		if (!$attrs) {
			return $value;
		}
		if ($value instanceof \DateTimeInterface) {
			return $value->format('j.m k\l. H:i');
		}

		return 'Random string';
	}

}

$collection = new \Starburst\Utils\ValueResolvers\ResolverCollection(
	new \Starburst\Utils\Tests\Stubs\CustomValueResolver(),
);

$obj = new class (1) {
	use \Starburst\Utils\Traits\GetArrayCopyTrait;

	public function __construct(
		#[CustomAttribute]
		private mixed $value,
	) {}
};

$obj->getArrayCopy() === [
	'value' => 'Random string'
];

$obj = new class (new \DateTimeImmutable('2024-05-24 08:12:42')) {
	use \Starburst\Utils\Traits\GetArrayCopyTrait;

	public function __construct(
		#[CustomAttribute]
		private mixed $value,
	) {}
};

$obj->getArrayCopy() === [
	'value' => '24.05 kl. 08:12:42'
];
```

### Path

[](#path)

The `Path` class provides utility methods for working with file paths in a platform-independent manner.

### `normalize(string $path): string`

[](#normalizestring-path-string)

Normalizes a given file path.

During normalization, all slashes are replaced by forward slashes ("/"). It also makes sure to remove trailing slashes. Contrary to `canonicalize`, this method does not remove invalid or dot path segments. Consequently, it is much more efficient and should be used whenever the given path is known to be a valid, absolute system path.

**Example:**

```
