|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodeOfDigital\LaravelUrlShortener; |
| 4 | + |
| 5 | +use CodeOfDigital\LaravelUrlShortener\Contracts\UrlFactory; |
| 6 | +use http\Exception\InvalidArgumentException; |
| 7 | +use Illuminate\Foundation\Application; |
| 8 | +use Illuminate\Support\Str; |
| 9 | + |
| 10 | +class UrlShortenerInstance implements UrlFactory |
| 11 | +{ |
| 12 | + protected $app; |
| 13 | + protected $shorteners; |
| 14 | + |
| 15 | + /** |
| 16 | + * Create a new URL Shortener instance. |
| 17 | + * |
| 18 | + * @param Application $app |
| 19 | + */ |
| 20 | + public function __construct(Application $app) |
| 21 | + { |
| 22 | + $this->app = $app; |
| 23 | + $this->shorteners = []; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Get the default URL shortener driver |
| 28 | + * |
| 29 | + * @return string |
| 30 | + */ |
| 31 | + public function getUrlDefaultDriver(): string |
| 32 | + { |
| 33 | + return $this->app['config']['url-shortener.default']; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Set the default URL shortener driver |
| 38 | + * |
| 39 | + * @return $this |
| 40 | + */ |
| 41 | + public function setUrlDefaultDriver($name): UrlShortenerInstance |
| 42 | + { |
| 43 | + $this->app['config']['url-shortener.default'] = $name; |
| 44 | + return $this; |
| 45 | + } |
| 46 | + |
| 47 | + public function getUrlShortenerConfig($name) |
| 48 | + { |
| 49 | + return config("url-shortener.shorteners.{$name}"); |
| 50 | + } |
| 51 | + |
| 52 | + public function resolveUrlDriver($name) |
| 53 | + { |
| 54 | + $config = $this->getUrlShortenerConfig($name); |
| 55 | + |
| 56 | + if (is_null($config) || !array_key_exists('driver', $config)) |
| 57 | + throw new InvalidArgumentException("URL shortener driver [{$name}] is not defined in the configuration."); |
| 58 | + |
| 59 | + $driverMethodName = 'create'.Str::studly($config['driver']).'Driver'; |
| 60 | + |
| 61 | + if (method_exists($this, $driverMethodName)) |
| 62 | + return $this->{$driverMethodName}($config); |
| 63 | + |
| 64 | + throw new InvalidArgumentException("URL shortener driver [{$config['driver']}] is not supported in this package."); |
| 65 | + } |
| 66 | + |
| 67 | + public function shortener($name = null) |
| 68 | + { |
| 69 | + $name = $name ?: $this->getUrlDefaultDriver(); |
| 70 | + |
| 71 | + if (array_key_exists($name, $this->shorteners)) |
| 72 | + return $this->shorteners[$name]; |
| 73 | + |
| 74 | + return $this->shorteners[$name] = $this->resolveUrlDriver($name); |
| 75 | + } |
| 76 | +} |
0 commit comments