Punic APIs
  • Namespace
  • Class
  • Tree
  • Todo

Namespaces

  • Punic
    • Exception

Classes

  • Punic\Calendar
  • Punic\Comparer
  • Punic\Currency
  • Punic\Data
  • Punic\Language
  • Punic\Misc
  • Punic\Number
  • Punic\Phone
  • Punic\Plural
  • Punic\Territory
  • Punic\Unit

Exceptions

  • Punic\Exception
  • Punic\Exception\BadArgumentType
  • Punic\Exception\BadDataFileContents
  • Punic\Exception\DataFileNotFound
  • Punic\Exception\DataFileNotReadable
  • Punic\Exception\DataFolderNotFound
  • Punic\Exception\InvalidDataFile
  • Punic\Exception\InvalidLocale
  • Punic\Exception\NotImplemented
  • Punic\Exception\ValueNotInList
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 
<?php

namespace Punic;

/**
 * Units helper stuff.
 */
class Unit
{
    /**
     * Get the list of all the available units.
     *
     * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
     */
    public static function getAvailableUnits($locale = '')
    {
        $data = Data::get('units', $locale);
        $categories = array();
        foreach ($data as $width => $units) {
            if ($width[0] !== '_') {
                foreach ($units as $category => $units) {
                    if ($category[0] !== '_') {
                        $unitIDs = array_keys($units);
                        if (isset($categories[$category])) {
                            $categories[$category] = array_unique(array_merge($categories[$category], $unitIDs));
                        } else {
                            $categories[$category] = array_keys($units);
                        }
                    }
                }
            }
        }
        ksort($categories);
        foreach (array_keys($categories) as $category) {
            sort($categories[$category]);
        }

        return $categories;
    }

    /**
     * Get the localized name of a unit.
     *
     * @param string $unit The unit identifier (eg 'duration/millisecond' or 'millisecond')
     * @param string $width The format name; it can be 'long' ('milliseconds'), 'short' (eg 'millisecs') or 'narrow' (eg 'msec')
     * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
     *
     * @throws Exception\ValueNotInList
     *
     * @return string
     */
    public static function getName($unit, $width = 'short', $locale = '')
    {
        $data = static::getDataForWidth($width, $locale);
        $unitData = static::getDataForUnit($data, $unit);

        return $unitData['_name'];
    }

    /**
     * Format a unit string.
     *
     * @param int|float|string $number The unit amount
     * @param string $unit The unit identifier (eg 'duration/millisecond' or 'millisecond')
     * @param string $width The format name; it can be 'long' (eg '3 milliseconds'), 'short' (eg '3 ms') or 'narrow' (eg '3ms'). You can also add a precision specifier ('long,2' or just '2')
     * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
     *
     * @throws Exception\ValueNotInList
     *
     * @return string
     */
    public static function format($number, $unit, $width = 'short', $locale = '')
    {
        $precision = null;
        if (is_int($width)) {
            $precision = $width;
            $width = 'short';
        } elseif (is_string($width) && preg_match('/^(?:(.*),)?([+\\-]?\\d+)$/', $width, $m)) {
            $precision = (int) $m[2];
            $width = (string) $m[1];
            if ($width === '') {
                $width = 'short';
            }
        }
        $data = static::getDataForWidth($width, $locale);
        $rules = static::getDataForUnit($data, $unit);
        $pluralRule = Plural::getRule($number, $locale);
        //@codeCoverageIgnoreStart
        // These checks aren't necessary since $pluralRule should always be in $rules, but they don't hurt ;)
        if (!isset($rules[$pluralRule])) {
            if (isset($rules['other'])) {
                $pluralRule = 'other';
            } else {
                $availableRules = array_keys($rules);
                $pluralRule = $availableRules[0];
            }
        }
        //@codeCoverageIgnoreEnd
        return sprintf($rules[$pluralRule], Number::format($number, $precision, $locale));
    }

    /**
     * Retrieve the measurement systems and their localized names.
     *
     * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
     *
     * @return array The array keys are the measurement system codes (eg 'metric', 'US', 'UK'), the values are the localized measurement system names (eg 'Metric', 'US', 'UK' for English)
     */
    public static function getMeasurementSystems($locale = '')
    {
        return Data::get('measurementSystemNames', $locale);
    }

    /**
     * Retrieve the measurement system for a specific territory.
     *
     * @param string $territoryCode The territory code (eg. 'US' for 'United States of America').
     *
     * @return string Return the measurement system code (eg: 'metric') for the specified territory. If $territoryCode is not valid we'll return an empty string.
     */
    public static function getMeasurementSystemFor($territoryCode)
    {
        $result = '';
        if (is_string($territoryCode) && preg_match('/^[a-z0-9]{2,3}$/i', $territoryCode)) {
            $territoryCode = strtoupper($territoryCode);
            $data = Data::getGeneric('measurementData');
            while ($territoryCode !== '') {
                if (isset($data['measurementSystem'][$territoryCode])) {
                    $result = $data['measurementSystem'][$territoryCode];
                    break;
                }
                $territoryCode = Territory::getParentTerritoryCode($territoryCode);
            }
        }

        return $result;
    }

    /**
     * Returns the list of countries that use a specific measurement system.
     *
     * @param string $measurementSystem The measurement system identifier ('metric', 'US' or 'UK')
     *
     * @return array The list of country IDs that use the specified measurement system (if $measurementSystem is invalid you'll get an empty array)
     */
    public static function getCountriesWithMeasurementSystem($measurementSystem)
    {
        $result = array();
        if (is_string($measurementSystem) && $measurementSystem !== '') {
            $someGroup = false;
            $data = Data::getGeneric('measurementData');
            foreach ($data['measurementSystem'] as $territory => $ms) {
                if (strcasecmp($measurementSystem, $ms) === 0) {
                    $children = Territory::getChildTerritoryCodes($territory, true);
                    if (empty($children)) {
                        $result[] = $territory;
                    } else {
                        $someGroup = true;
                        $result = array_merge($result, $children);
                    }
                }
            }
            if ($someGroup) {
                $otherCountries = array();
                foreach ($data['measurementSystem'] as $territory => $ms) {
                    if (($territory !== '001') && (strcasecmp($measurementSystem, $ms) !== 0)) {
                        $children = Territory::getChildTerritoryCodes($territory, true);
                        if (empty($children)) {
                            $otherCountries[] = $territory;
                        } else {
                            $otherCountries = array_merge($otherCountries, $children);
                        }
                    }
                }
                $result = array_values(array_diff($result, $otherCountries));
            }
        }

        return $result;
    }

    /**
     * Retrieve the standard paper size for a specific territory.
     *
     * @param string $territoryCode The territory code (eg. 'US' for 'United States of America').
     *
     * @return string Return the standard paper size (eg: 'A4' or 'US-Letter') for the specified territory. If $territoryCode is not valid we'll return an empty string.
     */
    public static function getPaperSizeFor($territoryCode)
    {
        $result = '';
        if (is_string($territoryCode) && preg_match('/^[a-z0-9]{2,3}$/i', $territoryCode)) {
            $territoryCode = strtoupper($territoryCode);
            $data = Data::getGeneric('measurementData');
            while ($territoryCode !== '') {
                if (isset($data['paperSize'][$territoryCode])) {
                    $result = $data['paperSize'][$territoryCode];
                    break;
                }
                $territoryCode = Territory::getParentTerritoryCode($territoryCode);
            }
        }

        return $result;
    }

    /**
     * Returns the list of countries that use a specific paper size by default.
     *
     * @param string $paperSize The paper size identifier ('A4' or 'US-Letter')
     *
     * @return array The list of country IDs that use the specified paper size (if $paperSize is invalid you'll get an empty array)
     */
    public static function getCountriesWithPaperSize($paperSize)
    {
        $result = array();
        if (is_string($paperSize) && $paperSize !== '') {
            $someGroup = false;
            $data = Data::getGeneric('measurementData');
            foreach ($data['paperSize'] as $territory => $ms) {
                if (strcasecmp($paperSize, $ms) === 0) {
                    $children = Territory::getChildTerritoryCodes($territory, true);
                    if (empty($children)) {
                        $result[] = $territory;
                    } else {
                        $someGroup = true;
                        $result = array_merge($result, $children);
                    }
                }
            }
            if ($someGroup) {
                $otherCountries = array();
                foreach ($data['paperSize'] as $territory => $ms) {
                    if (($territory !== '001') && (strcasecmp($paperSize, $ms) !== 0)) {
                        $children = Territory::getChildTerritoryCodes($territory, true);
                        if (empty($children)) {
                            $otherCountries[] = $territory;
                        } else {
                            $otherCountries = array_merge($otherCountries, $children);
                        }
                    }
                }
                $result = array_values(array_diff($result, $otherCountries));
            }
        }

        return $result;
    }

    /**
     * Get the width-specific unit data.
     *
     * @param string $width the data width
     * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
     *
     * @throws Exception\ValueNotInList
     *
     * @return array
     */
    private static function getDataForWidth($width, $locale = '')
    {
        $data = Data::get('units', $locale);
        if ($width[0] === '_' || !isset($data[$width])) {
            $widths = array();
            foreach (array_keys($data) as $w) {
                if (strpos($w, '_') !== 0) {
                    $widths[] = $w;
                }
            }
            throw new Exception\ValueNotInList($width, $widths);
        }

        return $data[$width];
    }

    /**
     * Get a unit-specific data.
     *
     * @param array $data the width-specific data
     * @param string $unit The unit identifier (eg 'duration/millisecond' or 'millisecond')
     *
     * @throws Exception\ValueNotInList
     *
     * @return array
     */
    private static function getDataForUnit(array $data, $unit)
    {
        $chunks = explode('/', $unit, 2);
        if (isset($chunks[1])) {
            list($unitCategory, $unitID) = $chunks;
        } else {
            $unitCategory = null;
            $unitID = null;
            foreach (array_keys($data) as $c) {
                if ($c[0] !== '_') {
                    if (isset($data[$c][$unit])) {
                        if ($unitCategory === null) {
                            $unitCategory = $c;
                            $unitID = $unit;
                        } else {
                            $unitCategory = null;
                            break;
                        }
                    }
                }
            }
        }
        if (
            $unitCategory === null || $unitCategory[0] === '_'
            || !isset($data[$unitCategory])
            || $unitID === null || $unitID[0] === '_'
            || !isset($data[$unitCategory][$unitID])
            ) {
            $units = array();
            foreach ($data as $c => $us) {
                if (strpos($c, '_') === false) {
                    foreach (array_keys($us) as $u) {
                        if (strpos($c, '_') === false) {
                            $units[] = "$c/$u";
                        }
                    }
                }
            }
            throw new \Punic\Exception\ValueNotInList($unit, $units);
        }

        return $data[$unitCategory][$unitID];
    }
}
Punic APIs API documentation generated by ApiGen