+ return $this->truncateForDatabase( $string, $length, $ellipsis, $adjustLength );
+ }
+
+ /**
+ * Truncate a string to a specified length in bytes, appending an optional
+ * string (e.g. for ellipsis)
+ *
+ * If $length is negative, the string will be truncated from the beginning
+ *
+ * @since 1.31
+ *
+ * @param string $string String to truncate
+ * @param int $length Maximum length in bytes
+ * @param string $ellipsis String to append to the end of truncated text
+ * @param bool $adjustLength Subtract length of ellipsis from $length
+ *
+ * @return string
+ */
+ function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
+ return $this->truncateInternal(
+ $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
+ );
+ }
+
+ /**
+ * Truncate a string to a specified number of characters, appending an optional
+ * string (e.g. for ellipsis).
+ *
+ * This provides multibyte version of truncate() method of this class, suitable for truncation
+ * based on number of characters, instead of number of bytes.
+ *
+ * If $length is negative, the string will be truncated from the beginning.
+ *
+ * @since 1.31
+ *
+ * @param string $string String to truncate
+ * @param int $length Maximum number of characters
+ * @param string $ellipsis String to append to the end of truncated text
+ * @param bool $adjustLength Subtract length of ellipsis from $length
+ *
+ * @return string
+ */
+ function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
+ // Passing encoding to mb_strlen and mb_substr is optional.
+ // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
+ // explicit specification of encoding is skipped.
+ // Note: Both multibyte methods are callables invoked in truncateInternal.
+ return $this->truncateInternal(
+ $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
+ );
+ }
+
+ /**
+ * Internal method used for truncation. This method abstracts text truncation into
+ * one common method, allowing users to provide length measurement function and
+ * function for finding substring.
+ *
+ * For usages, see truncateForDatabase and truncateForVisual.
+ *
+ * @param string $string String to truncate
+ * @param int $length Maximum length of final text
+ * @param string $ellipsis String to append to the end of truncated text
+ * @param bool $adjustLength Subtract length of ellipsis from $length
+ * @param callable $measureLength Callable function used for determining the length of text
+ * @param callable $getSubstring Callable function used for getting the substrings
+ *
+ * @return string
+ */
+ private function truncateInternal(
+ $string, $length, $ellipsis = '...', $adjustLength = true, $measureLength, $getSubstring
+ ) {
+ if ( !is_callable( $measureLength ) || !is_callable( $getSubstring ) ) {
+ throw new InvalidArgumentException( 'Invalid callback provided' );
+ }
+