Search by

arraypress / wp-format-utils

arraypress

This package is abandoned and no longer maintained. No replacement package was suggested.

Formatting for people to read: bytes, durations, file kinds, compact numbers, text, booleans, monogram avatars, sparklines and spreadsheet-safe CSV.

Package info

github.com/arraypress/wp-format-utils

Homepage

pkg:composer/arraypress/wp-format-utils

Statistics

Installs: 356

Dependents: 2

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-08-25 17:44 UTC

This package is auto-updated.

Last update: 2026-11-18 10:51:43 UTC


README

This library has moved. It is now part of sugarcommerce/text (namespace SugarCommerce\Text, PHP 8.3+). That package's README has a "Moving from arraypress/wp-*" table. This repository is archived and read-only.

WordPress Format Utilities

Turn raw values into something a person can read.

What it does

Every admin screen ends up with the same handful of formatters written inline: bytes as 2.4 MB, a duration as 1:23:45 or "about 2 hours", a boolean as Yes/No, a big number as 1.2k, a list as "red, green and blue".

They are each small, which is exactly why they get rewritten per screen and drift apart. This is one copy of each, so a file size looks the same wherever it appears.

Features

  • Format bytes as KB/MB/GB, and parse 512M back into a number
  • Show a duration as a clock, a compact string, or words
  • Yes/No, Enabled/Disabled, On/Off and Active/Inactive from any truthy value
  • Compact large numbers (1.2k, 3.4M) and format percentages
  • Join a list into "red, green and blue", with an optional cut-off
  • Pluralise against a count, and add ordinal suffixes
  • Describe a file by kind — "Image", "Spreadsheet" — rather than by MIME type
  • Fall back to an em dash for anything empty, instead of a blank cell
  • Generate a coloured initials avatar as an SVG, with the colour derived from the name
  • Give an incoming value its shape with Input: text cut to a column's length without splitting a character, a key, a strict yes/no, a bounded whole number, digits only, JSON left byte for byte
  • Take out what cannot be seen -- bidi overrides, zero-width characters, the tag block -- before a name or a filename is stored
  • Draw a person as an inline monogram in a pale tint and deep shade from a palette, the same colour on every screen
  • Draw a sparkline as an inline SVG, with a gradient id of its own
  • Say which way a figure went: up, down or level
  • Write CSV a spreadsheet will not run as formulas, and read one back by its header

Installation

composer require arraypress/wp-format-utils

Quick start

use ArrayPress\FormatUtils\Bytes;
use ArrayPress\FormatUtils\Duration;
use ArrayPress\FormatUtils\Numbers;
use ArrayPress\FormatUtils\Text;

Bytes::format( 2517834 );          // 2.4 MB
Bytes::parse( '512M' );            // 536870912

Duration::clock( 4530 );           // 1:15:30
Duration::words( 4530 );           // about 1 hour

Numbers::compact( 12400 );         // 12.4k
Text::list( [ 'red', 'green', 'blue' ] );  // red, green and blue
Text::plural( $count, 'order' );   // "1 order" / "4 orders"
Text::dash( $maybe_empty );        // the value, or an em dash
Text::humanize( 'licence_activations' );   // Licence activations

Percentages for a person

Numbers::percent() and Numbers::change() are plain English and stay that way. For a WordPress screen there is a second set, which goes through number_format_i18n() and so writes the site's own separators:

Numbers::rate( 124, 1000 );            // 12.4, or null when the whole is nought
Numbers::percent_i18n( 12.4 );         // 12.4%   (12,4% on a German site; "—" for null)
Numbers::percent_brief( 33.3 );        // 33%     (4.5% stays 4.5%)
Numbers::change_text( 'up', 12.4 );    // +12.4%
Numbers::change_text( 'down', -8.0 );  // −8.0%   (a minus sign, U+2212)
Numbers::change_text( 'new', null );   // New     (translated; or pass your own label)
Numbers::change( 80, 100, 0, true );   // −20%    (the same, from two figures)

Which way a figure went

Numbers::trend( 120, 100 );   // 'up'    (Numbers::TREND_UP)
Numbers::trend( 80, 100 );    // 'down'
Numbers::trend( 3, 3.0 );     // 'level'

Only the direction. Numbers::change() is the same comparison as a percentage, and answers new when there was nothing before.

Text with nothing hidden in it

A filename with U+202E in it renders right to left, so invoice‮txt.exe shows as invoiceexe.txt. A name with a zero-width space is two names that look like one. Input::visible() takes out control characters, zero-width characters, every bidirectional override and isolate, the byte-order mark and the Unicode tag block, and changes nothing else:

use ArrayPress\FormatUtils\Input;

Input::visible( "invoice\u{202E}txt.exe" );   // invoicetxt.exe
Input::text( "  Ada \t\n Lovelace\u{200B} ", 60 );   // Ada Lovelace (one line, capped)
Input::multiline( $note, 2000, 50 );          // lines kept, blank runs one blank line, CRs gone

Text that is not valid UTF-8 is ''.

Monogram avatars and the palette

A Gravatar is a request to somebody else's server for every face on the screen, and for most people what comes back is the same grey silhouette. A monogram is drawn in the page: one or two letters on a pale tile, in a deep shade of the same hue.

use ArrayPress\FormatUtils\Avatar;
use ArrayPress\FormatUtils\Palette;

echo Avatar::monogram( 'Ada Lovelace', 'ada@example.com', 32, array(
    'palette' => Palette::sweet(),     // the default: twelve sweet-shop pairs
    'class'   => 'myplugin-avatar',    // before core's "avatar avatar-32"
    'label'   => '',                   // say who it is only when nothing beside it does
) );

The three questions it answers can be asked on their own:

Avatar::initials( 'Ada King Lovelace' );            // AL  (first and last word)
Avatar::initials( '"Ada"' );                        // A   (punctuation and emoji ignored)
Avatar::initials( '', 'ada.lovelace@example.com' );  // A   (the address when the name has no letters)
Avatar::initials( '' );                             // ''  (a figure of a person is drawn)

Avatar::swatch( 'Ada@Example.com' );   // ['name' => 'Strawberry', 'tint' => '#ffdde1', 'shade' => '#a6283d', 'key' => 'strawberry']
Avatar::swatch( '' );                  // Palette::NEUTRAL + ['key' => '']

Avatar::monogram_svg( 'AL', $swatch, 40, array( 'style' => 'margin-right:8px' ) );

The colour comes from the address, lower-cased and trimmed, so a person is the same colour on every screen. It stays theirs while the palette keeps its length and order.

A palette is colours by key, each a name, a tint and a shade:

$palette = Palette::clean( apply_filters( 'myplugin_palette', Palette::sweet() ), Palette::sweet() );

Palette::pick( $palette, 'ada@example.com' );   // the key; the same every time
Palette::contrast( '#d0ecfb', '#0d5e8c' );       // 5.7 -- WCAG ratio; 4.5 is AA for text

clean() keeps only entries whose tint and shade are hex colours and falls back when nothing is left. The sweet palette is in colour-wheel order, so a chart walking it gets a rainbow; every pair passes 4.5 to 1.

Sparklines

A line with a fading fill under it, as an inline SVG: no script, no canvas, nothing to load. The highest figure touches the top and nought the bottom, so each line is its own shape.

use ArrayPress\FormatUtils\Sparkline;

// In a list column: 64 x 18, the last step drawn bold.
echo Sparkline::svg( $weekly_sales, array(
    'label'          => 'Up 12% on the four weeks before',
    'title'          => true,
    'colour'         => '#2271b1',
    'padding'        => 1.5,
    'stroke_width'   => 1.25,
    'stroke_opacity' => 0.75,
    'emphasise_last' => true,
    'fade'           => array( array( 0, 0.28 ), array( 0.6, 0.08 ), array( 1, 0 ) ),
) );

// Across a card, stretched by CSS; nothing when every day was nought.
echo Sparkline::svg( $daily, array(
    'width'     => 300,
    'height'    => 56,
    'padding'   => array( 'top' => 6, 'bottom' => 4 ),
    'stretch'   => true,
    'skip_flat' => true,
) );

Fewer than two figures is ''. Every drawing has a gradient id of its own -- twenty on a page that share one fight over one fill, and a counter repeats when markup arrives in pieces over REST -- unless you pass id. To put something at each point (hit areas, a dot), take the same geometry from Sparkline::points( $values, $args ) and pass your markup as inside.

Options: width, height, padding, floor (the least the top stands for; default 1, use 0 for fractions), colour (default currentColor), stroke_width, stroke_opacity, emphasise_last, last_width, fade, stretch, skip_flat, label, title, class, area_class, line_class, id, id_prefix, inside (not escaped).

CSV a spreadsheet will not run

Excel, Numbers and Sheets run a cell that starts with = as a formula, and an export is full of what customers typed. Csv puts an apostrophe in front of a cell that starts with =, +, -, @, |, a tab or a carriage return (also after leading whitespace), and leaves numbers alone -- -12.50 is a refund, not a formula, and must still sum.

use ArrayPress\FormatUtils\Csv;

// A whole file, with a byte-order mark so Excel reads UTF-8.
$csv = Csv::build( array( 'Name', 'Email', 'Total' ), $rows );

// In batches, to a file.
$handle = fopen( $path, $first ? 'w' : 'a' );
if ( $first ) {
    Csv::write( $handle, array( $headers ), bom: true );
}
Csv::write( $handle, $batch );
fclose( $handle );

Csv::cell( '=HYPERLINK("https://evil.test")' );  // '=HYPERLINK(...) with an apostrophe
Csv::cell( -12.5 );                               // -12.5
Csv::cell( array( 'a' => 1 ) );                   // {"a":1}

Cells are quoted the RFC 4180 way (a quote is doubled, no backslash escape), and a semicolon also puts a cell in quotes, because Excel in much of Europe splits on semicolons.

Reading goes by the header row, so reordered columns read the same:

use ArrayPress\FormatUtils\MissingColumns;

try {
    foreach ( Csv::read( $path, array( 'Email', 'Date' ) ) as $line => $row ) {
        $row['Email'];
    }
} catch ( MissingColumns $e ) {
    echo 'Missing: ' . implode( ', ', $e->missing );
}

A byte-order mark is stripped, names and values trimmed, blank lines skipped, short rows padded with ''.

Requirements

  • PHP 8.3 or later
  • WordPress 7.1 or later

License

GPL-2.0-or-later