StringHelper.php
58 lines
| 1 | <?php |
| 2 | /** |
| 3 | * String Helper class. |
| 4 | * |
| 5 | * @package Automattic\WooCommerce\Internal\ProductFeed |
| 6 | */ |
| 7 | |
| 8 | declare(strict_types=1); |
| 9 | |
| 10 | namespace Automattic\WooCommerce\Internal\ProductFeed\Utils; |
| 11 | |
| 12 | if ( ! defined( 'ABSPATH' ) ) { |
| 13 | exit; |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * String utility helper functions |
| 18 | * |
| 19 | * @since 10.5.0 |
| 20 | */ |
| 21 | class StringHelper { |
| 22 | /** |
| 23 | * Convert value to boolean string ('true' or 'false') |
| 24 | * |
| 25 | * @since 10.5.0 |
| 26 | * |
| 27 | * @param mixed $value Value to convert. |
| 28 | * @return string 'true' or 'false'. |
| 29 | */ |
| 30 | public static function bool_string( $value ): string { |
| 31 | if ( is_bool( $value ) ) { |
| 32 | return $value ? 'true' : 'false'; |
| 33 | } |
| 34 | if ( is_scalar( $value ) || null === $value ) { |
| 35 | $value = strtolower( (string) $value ); |
| 36 | } else { |
| 37 | $value = ''; |
| 38 | } |
| 39 | return ( 'true' === $value || '1' === $value || 'yes' === $value ) ? 'true' : 'false'; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Truncate text to specified length |
| 44 | * |
| 45 | * @since 10.5.0 |
| 46 | * |
| 47 | * @param string $text Text to truncate. |
| 48 | * @param int $max_length Maximum length. |
| 49 | * @return string Truncated text. |
| 50 | */ |
| 51 | public static function truncate( string $text, int $max_length ): string { |
| 52 | if ( mb_strlen( $text ) > $max_length ) { |
| 53 | return mb_substr( $text, 0, $max_length ); |
| 54 | } |
| 55 | return $text; |
| 56 | } |
| 57 | } |
| 58 |