maintenance-1.0.0-beta1/src/MaintenanceStringHelperTrait.php
src/MaintenanceStringHelperTrait.php
<?php
namespace Drupal\maintenance;
/**
* Provides helper methods for converting strings to arrays and vice versa.
*
* Used to process multi-line text input fields (e.g., IPs, paths) into
* structured arrays and format them back into storage-friendly strings.
*/
trait MaintenanceStringHelperTrait {
/**
* Converts a string with newline characters into an array of trimmed lines.
*
* Converts user input from multiline text fields (e.g., IPs or paths)
* into an array by normalizing line endings, trimming each line,
* and removing any blank entries to ensure clean structured data.
*
* @param string $text
* Input text with line breaks (\n or \r\n).
*
* @return array|null
* Array of non-empty trimmed lines, or NULL if input is invalid.
*/
protected function stringToArray($text): array|null {
// Validate input: must be a string.
if (!is_string($text)) {
return NULL;
}
// Normalize Windows line endings to Unix style.
$text = str_replace("\r\n", "\n", $text);
// Explode the text by newline and remove empty lines.
return array_filter(
array_map('trim', explode("\n", $text)),
static fn($line) => $line !== ''
);
}
/**
* Converts an array of lines into a single string separated by line breaks.
*
* Formats a list of string values for use in multiline form fields by
* filtering out invalid or empty lines and combining entries with consistent
* Windows-style line breaks to maintain configuration integrity.
*
* @param array $array
* An array of strings to be joined.
*
* @return string|null
* A string with each value on its own line, or NULL if input is invalid.
*/
protected function arrayToString($array): string|null {
// Ensure input is a valid array.
if (!is_array($array)) {
return NULL;
}
// Filter out empty or non-string values.
$array = array_filter($array, static fn($item) => is_string($item) && trim($item) !== '');
// Join array elements using Windows-style line breaks for consistency.
return implode("\r\n", $array);
}
}
