*/ public static function placeholders() { return array( 'first_name' => __( 'Customer first name', 'orderchirp' ), 'last_name' => __( 'Customer last name', 'orderchirp' ), 'order_number' => __( 'Order number', 'orderchirp' ), 'order_total' => __( 'Order total with currency', 'orderchirp' ), 'order_status' => __( 'Order status', 'orderchirp' ), 'order_date' => __( 'Order date', 'orderchirp' ), 'items' => __( 'Items, one per line', 'orderchirp' ), 'item_count' => __( 'Number of items', 'orderchirp' ), 'payment_method' => __( 'Payment method', 'orderchirp' ), 'order_url' => __( 'Link to the order', 'orderchirp' ), 'tracking_number' => __( 'Tracking number (when a tracking plugin added one)', 'orderchirp' ), 'tracking_provider' => __( 'Carrier name (when known)', 'orderchirp' ), 'tracking_url' => __( 'Tracking link (when known)', 'orderchirp' ), 'shop_name' => __( 'Your shop name', 'orderchirp' ), ); } /** * Placeholders whose line is dropped when they are all empty. Only these: a missing first * name must not take "Hi {first_name}, thanks for your order" away with it. * * @var string[] */ const OPTIONAL = array( 'tracking_number', 'tracking_provider', 'tracking_url', 'items', 'payment_method', 'order_url' ); /** * Render a template. * * @param string $text Template text. * @param array $vars Values by placeholder name; unknown placeholders stay as typed. * @return string */ public static function render( $text, array $vars ) { $text = str_replace( array( "\r\n", "\r" ), "\n", (string) $text ); $out = array(); foreach ( explode( "\n", $text ) as $line ) { preg_match_all( '/\{([a-z_]+)\}/', $line, $found ); $names = array_values( array_intersect( array_unique( $found[1] ), array_keys( $vars ) ) ); if ( $names && array_intersect( $names, self::OPTIONAL ) ) { $all_empty = true; foreach ( $names as $name ) { if ( '' !== trim( (string) $vars[ $name ] ) ) { $all_empty = false; break; } } if ( $all_empty ) { continue; } } $rendered = preg_replace_callback( '/\{([a-z_]+)\}/', static function ( $m ) use ( $vars ) { return array_key_exists( $m[1], $vars ) ? trim( (string) $vars[ $m[1] ] ) : $m[0]; }, $line ); // Two placeholders with one of them empty leave a double space behind. $out[] = rtrim( (string) preg_replace( '/ {2,}/', ' ', (string) $rendered ) ); } $message = trim( implode( "\n", $out ) ); $message = (string) preg_replace( "/\n{3,}/", "\n\n", $message ); return self::truncate( $message ); } /** * Cut to Telegram's limit on a character (not byte) boundary. * * @param string $message Message. * @return string */ public static function truncate( $message ) { if ( function_exists( 'mb_strlen' ) && mb_strlen( $message, 'UTF-8' ) > self::MAX_LENGTH ) { return mb_substr( $message, 0, self::MAX_LENGTH - 1, 'UTF-8' ) . '…'; } return $message; } }