{"id":17846444,"url":"https://github.com/technicalguru/php-utils","last_synced_at":"2026-01-21T21:33:04.058Z","repository":{"id":57066124,"uuid":"312082742","full_name":"technicalguru/php-utils","owner":"technicalguru","description":"Basic Classes for PHP","archived":false,"fork":false,"pushed_at":"2023-10-07T15:51:14.000Z","size":107,"stargazers_count":0,"open_issues_count":2,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-11-19T17:29:27.414Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"lgpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/technicalguru.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-11T20:31:29.000Z","updated_at":"2022-01-09T18:29:13.000Z","dependencies_parsed_at":"2024-10-27T22:28:23.667Z","dependency_job_id":"bab73779-7cc5-48f0-ad6e-f830ac7aadfe","html_url":"https://github.com/technicalguru/php-utils","commit_stats":{"total_commits":87,"total_committers":1,"mean_commits":87.0,"dds":0.0,"last_synced_commit":"4297d95f9ea9773d65f5785db1bd5daf096a62a9"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"purl":"pkg:github/technicalguru/php-utils","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/technicalguru%2Fphp-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/technicalguru%2Fphp-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/technicalguru%2Fphp-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/technicalguru%2Fphp-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/technicalguru","download_url":"https://codeload.github.com/technicalguru/php-utils/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/technicalguru%2Fphp-utils/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28644075,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-21T21:29:11.980Z","status":"ssl_error","status_checked_at":"2026-01-21T21:24:31.872Z","response_time":86,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-27T21:39:58.103Z","updated_at":"2026-01-21T21:33:04.043Z","avatar_url":"https://github.com/technicalguru.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# php-utils\nThis is a collection of useful classes and functions for every day PHP life. It includes things such as:\n\n* Handling dates and times and various appearances of it\n* Searching and sorting of arrays of objects\n* Logging to error_log with different levels\n* Notification to users across various requests within a session\n* Extracting information from the current HTTP request\n* Obfuscating sensitive information to protect data against spambots\n* Slugifying strings for usage in URLs\n* Generating random strings\n* Formatting prices and units\n* Simple text templating\n\nThese classes are no rocket science, just simple helpers that prevent from wiriting the\nsame code in various flavours over and over again.\n\n# License\nThis project is licensed under [GNU LGPL 3.0](LICENSE.md). \n\n# Installation\n\n## By Composer\n\n```sh\ncomposer require technicalguru/utils\n```\n\n## By Package Download\nYou can download the source code packages from [GitHub Release Page](https://github.com/technicalguru/php-utils/releases)\n\n# Classes\n\n## Request class\nThe Request class extracts many useful information from the current HTTP request. It provides:\n\n* Header information\n* GET and POST parameter values, assigning defaults if not present\n* Getting the method, protocol, host and path information from the HTTP request\n* Checking the elapsed time of this request\n\nIt is possible to create an object yourself, but it is recommend to use the singleton:\n\n```\n$request = \\TgUtils\\Request::getRequest();\n```\n\nInspect the [source code](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Request.php) to find out about the various methods available.\n\n## Date class\n\nThe date class handles issues for localization, timezones and conversion into different formats or creation from various formats. Here are some examples:\n\n```\nuse TgUtils\\Date;\n\n$timezone = 'Europe/Berlin';\n\n// Creating instances with local timezone\n$date = new Date(time(), $timezone);\n$date = Date::createLocalInstance(time(), $timezone);\n$date = Date::createFromMysql($mySqlTimestampString, $timezone);\n\n// The Epoch time in seconds\n$unixTimestamp = $date-\u003etoUnix();\n\n// Converting and formatting with local timezone \n$mysqlTimstamp = $date-\u003etoMysql(TRUE);\n$iso8601       = $date-\u003etoISO8601(TRUE);\n$someString    = $date-\u003eformat('d.m.Y H:i:s', TRUE);\n\n// Converting to UTC timezones instances\n$mysqlTimstamp = $date-\u003etoMysql();\n$iso8601       = $date-\u003etoISO8601();\n$someString    = $date-\u003eformat('d.m.Y H:i:s');\n```\n\nInspect the [source code](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Date.php) to find out about the various methods available.\n\n## Logging\n\nLogging is very simple. Set your log level (if not INFO) and start logging:\n\n```\nuse TgLog\\Log;\n\n// Set default settings before using the log:\nLog::setDefaultLogLevel(Log::ERROR);\nLog::setDefaultAppName('MyApplication');\n\n// Or just on the singleton logging instance\nLog::instance()-\u003esetLogLevel(Log::ERROR);\nLog::instance()-\u003esetAppName('MyAppName');\n\n// Simple line\nLog::error('A simple error message');\n\n// This message will not go into the log\nLog::info('This message is lost.');\n\n// Log an exception\nLog::error('An expception was caught: ', $exception);\n\n// Log an object for later debugging\nLog::error('We have some problem here:', $object);\n```\n\nThe Log can also help when you need to debug something:\n\n```\nuse TgLog\\Log;\n\n// Get the stacktrace\n$stacktrace = Log::getStackTrace(__FILE__);\n\n// Or log it with INFO level\nLog::infoStackTrace(__FILE__);\n```\n\nThe `__FILE__` parameter will oppress the current file from appearing in the stacktrace. You\ncan easily use the function without this argument to have the current file included:\n\n```\n$stacktrace = Log::getStackTrace();\nLog::infoStackTrace();\n```\n\nFinally, you can create your special instances of a log for some modules and log from there, e.g.\n\n```\n$moduleLog = new Log(Log::ERROR, 'MyAppModule');\n\n$moduleLog-\u003elogInfo('Module started');\n$moduleLog-\u003elogError('Exception occurred:', $exception);\n\n```\n\n## User Notifications\n\nSometimes it is hard to display success or error messages because the message needs to\nbe displayed in another script, another HTTP call or even just later. The following snippet\nwill remember the message across multiple call within a session.\n\n```\nuse TgLog\\Log;\nuse TgLog\\Success;\n\nLog::register(new Success('Your data was saved successfully.));\n```\n\nThe registartion will not only remember the message but also print the message into\nthe error log when it's an instance of `Debug`, `Error`, `Warning` or `Info`.\n\nIn another call or script you can retrieve your messages again to display:\n\n```\nuse TgLog\\Log;\nuse TgLog\\Success;\n\nforeach (Log::get() AS $message) {\n\tswitch ($message-\u003egetType()) {\n\tcase 'success':\n\t\techo '\u003cdiv class=\"text-success\"\u003e'.$message-\u003egetMessage().'\u003c/div\u003e';\n\t\tbreak;\n\tcase 'error':\n\t\techo '\u003cdiv class=\"text-danger\"\u003e'.$message-\u003egetMessage().'\u003c/div\u003e';\n\t\tbreak;\n\t}\n}\n\n// Finally, clean all messages\nLog::clean();\n```\n\n## Authentication Helper\nA simple authentication helper interface along with a default implementation is provided:\n\n* [TgUtils\\Auth\\CredentialsProvider](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Auth/CredentialsProvider.php) - Interface to provide username and password to other objects\n* [TgUtils\\Auth\\DefaultCredentialsProvider](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Auth/DefaultCredentialsProvider.php) - Simple default implementation of the interface\n\n## Sensitive Data Obfuscation\n\nPublishing sensitive data such as e-mail addresses and phone numbers is dangerous nowadays as spammers\ngrab such information automatically from websites. The utils package provides a javascript-based way\nto obfuscate this information on websites. Its' idea is based on the rot13 obfuscation method but uses a\nrandom character mapping instead of a fixed rotation. This idea was chosen because rot13 seems to be a kind of standard\nin obfuscation and spammers might already be able to read them.\n\nIt shall be noted that it is still not impossible to read the information even when obfuscated. But it requires\na bit more sophisticated effort (Javascript execution) to gain the sensitive information.\n\n**Idea:** The text to be obfuscated is replaced - char by char - by other characters from a map. This map is\ngenerated uniquely for this special obfuscation instance. Other obfuscations on the same page will use different\nmaps. The HTML source displays only: `[javascript protected]`. However, a special javascript will run after\nthe page loaded and replace exactly this text with the real content.\n\nTwo obfuscation methods exists: a simple text obfuscation and an e-mail obfuscation which also creates a mailto: link\nthat the user can click.\n\nHere is how you use it:\n\n```\nuser \\TgUtils\\Obfuscation;\n\n/*** Just create everything and put it in your HTML page **/\n$htmlSource = Obfuscation::obfuscateText('+49 555 0123456');\n$emailLink  = Obfuscation::obfuscateEmail('john.doe@example.com');\n\n/*************************** OR ***************************/\n// Use your own tag ID \n$id         = Obfuscation::generateObfuscationId();\n\n// Use this ID to get the bot-resistent HTML source\n$htmlSource = Obfuscation::getObfuscatedHtmlSpan($id);\n\n// And get the javascript\n$textJavascript   = Obfuscation::obfuscateText('+49 555 0123456', $id);\n$emailJavascript  = Obfuscation::obfuscateEmail('john.doe@example.com', $id);\n\n```\n\nPlease notice that not all characters are supported in the default character map. It covers mainly\ne-mail addresses and phone numbers. However, you can pass your own character set to the obfuscate methods\nas third argument. Please consult the [source code](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Obfuscation.php) for more details.\n\n## Text Templating\n\nTo ease the generation of dynamic texts, a template processor is provided. This processor can work on texts that contain variables in \ncurly brackets `{{variable-definition}}`. The processor knows objects, snippets and formatters.\n\n**Objects** are application objects that hold attributes that you want to be replaced. An object's attribute will be referenced in a template\nwith `{{objectKey.attributeName}}`, e.g. `{{user.name}}`.\n\n**Snippets** are more complex replacements that will be inserted in your template. This is useful when you need the same complex\ntext structure in multiple template generations, e.g. for a footer or a header text. Snippets are referenced in a template by\ntheir keys only: `{{snippetKey}}`. A snippet is implemented by the interface [`Snippet`](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Templating/Snippet.php). A snippet can take parameters as `{{snippetKey:param1:param2...}}`.\n\n**Formatters** can be used to format an object's attribute. Formatters can take parameters to further customize the formatting. A good example\nis the [`DateFormatter`](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Templating/DateFormatter.php). The formatter\nis referenced with the object's attribute by `{{objectKey.attribute:formatterKey:param1:param2...}}`, e.g. `{{user.created_on:date:rfc822}}`.\n\nAll three elements - objects, snippets and formatters - are given to the [`Processor`](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Templating/Processor.php) in its constructor:\n\n```\n$objects    = array('user'   =\u003e $myUser);\n$snippets   = array('header' =\u003e new HeaderSnippet(), 'footer' =\u003e $new FooterSnippet());\n$formatters = array('date'   =\u003e new DateFormatter());\n$language   = 'en';\n$processor = new Processor($objects, $snippets, $formatters, $language);\n```\n\nThe language is for information and can be used in snippets or formatters to select the right text.\n\nFinally you can process a template:\n\n```\n$template = '{{header}} Hello {{user.name}}! Your account was created on {{user.created_on:date:d/m/Y}}.{{footer}}';\necho $processor-\u003eprocess($template);\n\n// Output is:\n// IMPORTANT MESSAGE! Hello John Doe! Your account was created on 02/03/2017. Best regards!\n```\n\n## Other Utils\nThere are some daily tasks that need to be done in applications. The `Utils` class addresses a few of them:\n\n```\nuse TgUtils\\Utils;\nuse TgUtils\\FormatUtils;\nuse TgUtils\\Slugify;\n\n// create a random string\n$myId = Utils::generateRandomString(20);\n\n// Find an object with UID 1\n$myObject = Utils::findByUid($objectList, 3);\n\n// Find an object with a certain name\n$myObject = Utils::findBy($objectList, 'name', 'John');\n\n// Sort an array of objects by its names\nUtils::sort($objectList, 'name');\n\n// Sort an array of objects in reverse order of names\nUtils::sort($objectList, 'name', TRUE);\n\n// Sort an array of objects in reverse order of names, ignore upper/lower case\nUtils::sort($objectList, 'name', TRUE, TRUE);\n\n// Get all names from the list of objects\n$allNames = Utils::extractAttributeFromList($objectList, 'name');\n\n// Mask a sensitive string\n$masked = Utils::anonymize($aPhoneNumber);\n\n// Slugify a string\n$slug = Slugify::slugify('A text that turn into an URL');\n\n// Format a price\n$priceString = FormatUtils::formatPrice(3000.643, 'EUR');\n\n// Format a file size\n$fileSize = FormatUtils::formatUnit(3000643, 'B');\n```\n\nInspect the [source code](https://github.com/technicalguru/php-utils/blob/main/src/TgUtils/Utils.php) to find more about the methods available.\n\n# Contribution\nReport a bug, request an enhancement or pull request at the [GitHub Issue Tracker](https://github.com/technicalguru/php-utils/issues).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechnicalguru%2Fphp-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftechnicalguru%2Fphp-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftechnicalguru%2Fphp-utils/lists"}