andreas-glaser / php-helpers
A simple php library of various helper functions and classes.
Installs: 75 945
Dependents: 5
Suggesters: 0
Security: 0
Stars: 13
Watchers: 1
Forks: 2
Open Issues: 0
Requires
- php: ^7.4|^8.0
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- friendsofphp/php-cs-fixer: @stable
- phpunit/phpunit: ^8
README
A comprehensive collection of PHP helper functions and classes to simplify common programming tasks.
Requirements
- PHP 7.4 or higher
- PHP 8.0 or higher
- ext-mbstring
- ext-json
Installation
composer require andreas-glaser/php-helpers
Features
Array Helper (ArrayHelper.php
)
A powerful utility class for array manipulation and operations.
Key Functions:
ArrayHelper::get(array $array, $key, $default = null)
: Get value by key with default fallbackArrayHelper::getByPath(array $array, $path, $throwException = false, $default = null)
: Get value using dot notation pathArrayHelper::setByPath(array $array, $path, $value)
: Set value using dot notation pathArrayHelper::unsetByPath(array $array, string $path)
: Remove value using dot notation pathArrayHelper::existsByPath(array $array, $path)
: Check if path existsArrayHelper::prepend(array $array, $value, $key = false)
: Add element at array startArrayHelper::append(array $array, $value, $key = false)
: Add element at array endArrayHelper::insertBefore(array &$array, $position, array $values)
: Insert values before positionArrayHelper::insertAfter(array &$array, $position, array $values)
: Insert values after positionArrayHelper::getFirstValue(array $array, $default = null)
: Get first array valueArrayHelper::getLastValue(array $array, $default = null)
: Get last array valueArrayHelper::getRandomValue(array $array)
: Get random array valueArrayHelper::removeFirstElement(array $array)
: Remove first elementArrayHelper::removeLastElement(array $array)
: Remove last elementArrayHelper::removeByValue(array $array, $value, $strict = true)
: Remove element by valueArrayHelper::keysCamelToUnderscore(array $array)
: Convert array keys to underscore caseArrayHelper::unsetEmptyValues(array $array, $recursive = false)
: Remove empty valuesArrayHelper::isAssoc(array $array)
: Check if array is associativeArrayHelper::merge()
: Merge multiple arrays
String Helper (StringHelper.php
)
Comprehensive string manipulation and formatting utilities.
Key Functions:
StringHelper::is($string, $stringToMatch, $caseSensitive = true)
: Compare stringsStringHelper::isOneOf($string, array $stringsToCompare, $caseSensitive = true)
: Check if string matches any in arrayStringHelper::contains($haystack, $needle, $caseSensitive = true)
: Check if string contains substringStringHelper::startsWith($haystack, $needle, $caseSensitive = true)
: Check if string starts withStringHelper::endsWith($haystack, $needle, $caseSensitive = true)
: Check if string ends withStringHelper::trimMulti($string, array $chars)
: Trim multiple charactersStringHelper::camelToUnderscore($string)
: Convert camelCase to snake_caseStringHelper::removeLineBreaks($string, $replaceWith = ' ')
: Remove line breaksStringHelper::removeRedundantWhiteSpaces($string)
: Remove extra spacesStringHelper::machineReadable($string)
: Convert to machine-readable formatStringHelper::limitWords($str, $limit = 100, $end_char = null)
: Limit string to word countStringHelper::limitChars($str, $limit = 100, $end_char = null)
: Limit string to character countStringHelper::isBlank($string)
: Check if string is blankStringHelper::removeFromStart($string, $stringToRemove)
: Remove prefixStringHelper::removeFromEnd($string, $stringToRemove)
: Remove suffix
Date Helper (DateHelper.php
)
Date and time manipulation utilities.
Key Functions:
DateHelper::format($date, $format)
: Format dateDateHelper::isValid($date)
: Validate dateDateHelper::isValidFormat($date, $format)
: Validate date formatDateHelper::getAge($date)
: Calculate age from dateDateHelper::getDaysBetween($date1, $date2)
: Calculate days between datesDateHelper::getMonthsBetween($date1, $date2)
: Calculate months between datesDateHelper::getYearsBetween($date1, $date2)
: Calculate years between dates
HTML Helper (HtmlHelper.php
)
HTML generation and manipulation utilities.
Key Functions:
HtmlHelper::tag($name, $content = null, array $attributes = [])
: Generate HTML tagHtmlHelper::link($url, $text = null, array $attributes = [])
: Generate linkHtmlHelper::img($src, array $attributes = [])
: Generate image tagHtmlHelper::script($src, array $attributes = [])
: Generate script tagHtmlHelper::style($href, array $attributes = [])
: Generate style tagHtmlHelper::meta($name, $content, array $attributes = [])
: Generate meta tagHtmlHelper::escape($string)
: Escape HTML special characters
JSON Helper (JsonHelper.php
)
JSON encoding and decoding utilities.
Key Functions:
JsonHelper::encode($value, $options = 0)
: Encode to JSONJsonHelper::decode($json, $assoc = false, $depth = 512)
: Decode from JSONJsonHelper::isValid($json)
: Validate JSON string
Number Helper (NumberHelper.php
)
Number formatting and manipulation utilities.
Key Functions:
NumberHelper::format($number, $decimals = 2)
: Format numberNumberHelper::formatCurrency($number, $currency = 'USD')
: Format as currencyNumberHelper::formatPercent($number, $decimals = 2)
: Format as percentageNumberHelper::isEven($number)
: Check if number is evenNumberHelper::isOdd($number)
: Check if number is odd
Random Helper (RandomHelper.php
)
Random value generation utilities.
Key Functions:
RandomHelper::string($length = 10)
: Generate random stringRandomHelper::number($min = 0, $max = 100)
: Generate random numberRandomHelper::element(array $array)
: Get random array elementRandomHelper::boolean()
: Generate random boolean
Timer Helper (TimerHelper.php
)
Time measurement and execution timing utilities.
Key Functions:
TimerHelper::start()
: Start timerTimerHelper::stop()
: Stop timerTimerHelper::getTime()
: Get elapsed timeTimerHelper::getMemory()
: Get memory usage
Value Helper (ValueHelper.php
)
Value manipulation and type conversion utilities.
Key Functions:
ValueHelper::isDateTime($value)
: Check if value is datetimeValueHelper::isJson($value)
: Check if value is JSONValueHelper::isEmail($value)
: Check if value is emailValueHelper::isUrl($value)
: Check if value is URLValueHelper::toArray($value)
: Convert to arrayValueHelper::toString($value)
: Convert to string
Counter Helper (CounterHelper.php
)
Counter implementation for tracking and incrementing values.
Key Functions:
CounterHelper::increment()
: Increment counterCounterHelper::decrement()
: Decrement counterCounterHelper::getValue()
: Get current valueCounterHelper::reset()
: Reset counter
CSV Helper (CsvHelper.php
)
CSV file handling and manipulation utilities.
Key Functions:
CsvHelper::read($file)
: Read CSV fileCsvHelper::write($file, array $data)
: Write to CSV fileCsvHelper::parse($string)
: Parse CSV stringCsvHelper::generate(array $data)
: Generate CSV string
Email Helper (EmailHelper.php
)
Email validation and formatting utilities.
Key Functions:
EmailHelper::isValid($email)
: Validate email addressEmailHelper::normalize($email)
: Normalize email addressEmailHelper::getDomain($email)
: Get email domainEmailHelper::getLocalPart($email)
: Get email local part
IO Helper (IOHelper.php
)
Input/Output utilities for file and stream operations.
Key Functions:
IOHelper::read($file)
: Read fileIOHelper::write($file, $content)
: Write to fileIOHelper::append($file, $content)
: Append to fileIOHelper::delete($file)
: Delete fileIOHelper::exists($file)
: Check if file exists
Additional Components
Color
Color manipulation and conversion utilities.
HTTP
HTTP request and response handling utilities.
HTML
HTML-specific utilities and helpers.
Validate
Data validation utilities.
View
View rendering and template utilities.
Traits
Reusable traits for common functionality.
Interfaces
Interface definitions for the library components.
Exceptions
Custom exception classes for error handling.
Usage
use AndreasGlaser\Helpers\ArrayHelper; use AndreasGlaser\Helpers\StringHelper; use AndreasGlaser\Helpers\DateHelper; // Array operations $array = ['a' => 1, 'b' => 2]; $value = ArrayHelper::get($array, 'a', 'default'); // Returns 1 $nestedArray = ['user' => ['profile' => ['name' => 'John']]]; $name = ArrayHelper::getByPath($nestedArray, 'user.profile.name'); // Returns 'John' // String operations $string = 'Hello World'; $contains = StringHelper::contains($string, 'World'); // Returns true $startsWith = StringHelper::startsWith($string, 'Hello'); // Returns true $underscore = StringHelper::camelToUnderscore('helloWorld'); // Returns 'hello_world' // Date operations $date = new DateTime(); $formatted = DateHelper::format($date, 'Y-m-d'); // Returns current date in Y-m-d format $isValid = DateHelper::isValid('2024-03-20'); // Returns true
Testing
composer test
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
- Andreas Glaser - GitHub
Support
If you find this library helpful, please consider giving it a star on GitHub!