|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace StringEncoder\Proxy; |
| 6 | + |
| 7 | +use StringEncoder\Contracts\ConvertWriteInterface; |
| 8 | +use StringEncoder\Encoder as EncoderImplementation; |
| 9 | +use StringEncoder\Exceptions\InvalidEncodingException; |
| 10 | + |
| 11 | +final class Encoder |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var EncoderImplementation |
| 15 | + */ |
| 16 | + private static $encoder = null; |
| 17 | + |
| 18 | + /** |
| 19 | + * @throws InvalidEncodingException |
| 20 | + */ |
| 21 | + public static function mountFromEncoding(string $targetEncoding, ?string $sourceEncoding = null): void |
| 22 | + { |
| 23 | + $encoder = new EncoderImplementation(); |
| 24 | + $encoder->setTargetEncoding($targetEncoding); |
| 25 | + if ($sourceEncoding !== null) { |
| 26 | + $encoder->setSourceEncoding($sourceEncoding); |
| 27 | + } |
| 28 | + self::mount('Encoder', $encoder); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Call this to mount the static facade. The facade allows you to use |
| 33 | + * this object as a $className. |
| 34 | + */ |
| 35 | + public static function mount(string $className = 'Encoder', ?EncoderImplementation $encoder = null): bool |
| 36 | + { |
| 37 | + if (!\class_exists($className)) { |
| 38 | + \class_alias(__CLASS__, $className); |
| 39 | + } |
| 40 | + if ($encoder instanceof EncoderImplementation) { |
| 41 | + self::$encoder = $encoder; |
| 42 | + } |
| 43 | + |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + public static function getMountedEncoder(): ?EncoderImplementation |
| 48 | + { |
| 49 | + return self::$encoder; |
| 50 | + } |
| 51 | + |
| 52 | + public static function unload(): void |
| 53 | + { |
| 54 | + self::$encoder = null; |
| 55 | + } |
| 56 | + |
| 57 | + public static function getTargetEncoding(): ?string |
| 58 | + { |
| 59 | + return self::$encoder->getTargetEncoding(); |
| 60 | + } |
| 61 | + |
| 62 | + public static function setTargetEncoding(string $encoding): void |
| 63 | + { |
| 64 | + self::$encoder->setTargetEncoding($encoding); |
| 65 | + } |
| 66 | + |
| 67 | + public static function getSourceEncoding(): ?string |
| 68 | + { |
| 69 | + return self::$encoder->getSourceEncoding(); |
| 70 | + } |
| 71 | + |
| 72 | + public static function setSourceEncoding(string $encoding): void |
| 73 | + { |
| 74 | + self::$encoder->setSourceEncoding($encoding); |
| 75 | + } |
| 76 | + |
| 77 | + public static function convert(): ConvertWriteInterface |
| 78 | + { |
| 79 | + return self::$encoder->convert(); |
| 80 | + } |
| 81 | +} |
0 commit comments