|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * @link https://github.com/phpviet/laravel-number-to-words |
| 4 | + * |
| 5 | + * @copyright (c) PHP Viet |
| 6 | + * @license [MIT](https://opensource.org/licenses/MIT) |
| 7 | + */ |
| 8 | + |
| 9 | +namespace PHPViet\Laravel\NumberToWords\Facades; |
| 10 | + |
| 11 | +use InvalidArgumentException; |
| 12 | +use PHPViet\NumberToWords\Transformer; |
| 13 | +use Illuminate\Support\Facades\Facade; |
| 14 | +use PHPViet\NumberToWords\DictionaryInterface; |
| 15 | + |
| 16 | +/** |
| 17 | + * @method static string toWords($number) |
| 18 | + * @method static string toCurrency($number, $unit = 'đồng') |
| 19 | + * |
| 20 | + * @author Vuong Minh <vuongxuongminh@gmail.com> |
| 21 | + * @since 1.0.0 |
| 22 | + */ |
| 23 | +class N2W extends Facade |
| 24 | +{ |
| 25 | + /** |
| 26 | + * Từ điển hiện tại. |
| 27 | + * |
| 28 | + * @var null|DictionaryInterface |
| 29 | + */ |
| 30 | + public static $dictionary; |
| 31 | + |
| 32 | + /** |
| 33 | + * Cache data của các từ điển. |
| 34 | + * |
| 35 | + * @var array|DictionaryInterface[] |
| 36 | + */ |
| 37 | + private static $dictionaries = []; |
| 38 | + |
| 39 | + /** |
| 40 | + * @inheritDoc |
| 41 | + */ |
| 42 | + protected static function getFacadeAccessor(): Transformer |
| 43 | + { |
| 44 | + $dictionary = static::$dictionary ?? static::getDefaultDictionary(); |
| 45 | + $dictionary = static::getDictionaryInstance($dictionary); |
| 46 | + |
| 47 | + return app('n2w', [$dictionary]); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Trả về từ điển mặc định trong config. |
| 52 | + * |
| 53 | + * @return DictionaryInterface |
| 54 | + */ |
| 55 | + public static function getDefaultDictionary(): DictionaryInterface |
| 56 | + { |
| 57 | + return config('n2w.defaults.dictionary'); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Tạo từ điển. |
| 62 | + * |
| 63 | + * @param string $dictionary |
| 64 | + * @return DictionaryInterface |
| 65 | + */ |
| 66 | + protected static function getDictionaryInstance(string $dictionary): DictionaryInterface |
| 67 | + { |
| 68 | + if (!$dictionaryClass = config("n2w.dictionaries.{$dictionary}")) { |
| 69 | + throw new InvalidArgumentException(sprintf('Dictionary (%s) is not defined!', $dictionary)); |
| 70 | + } |
| 71 | + |
| 72 | + if (!isset(static::$dictionaries[$dictionaryClass])) { |
| 73 | + return static::$dictionaries[$dictionaryClass] = app()->make($dictionaryClass); |
| 74 | + } |
| 75 | + |
| 76 | + return static::$dictionaries[$dictionaryClass]; |
| 77 | + } |
| 78 | + |
| 79 | + |
| 80 | +} |
0 commit comments