| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* This file is part of Optimole PHP SDK. |
| 7 |
* |
| 8 |
* (c) Optimole Team <friends@optimole.com> |
| 9 |
* |
| 10 |
* For the full copyright and license information, please view the LICENSE |
| 11 |
* file that was distributed with this source code. |
| 12 |
*/ |
| 13 |
|
| 14 |
namespace Optimole\Sdk\Resource; |
| 15 |
|
| 16 |
abstract class AbstractResource |
| 17 |
{ |
| 18 |
/** |
| 19 |
* The Optimole domain to use when generating the URL. |
| 20 |
*/ |
| 21 |
private string $domain; |
| 22 |
|
| 23 |
/** |
| 24 |
* The optimization properties used to optimize the resource. |
| 25 |
* |
| 26 |
* @var PropertyInterface[] |
| 27 |
*/ |
| 28 |
private array $properties; |
| 29 |
|
| 30 |
/** |
| 31 |
* The source of the resource being optimized. |
| 32 |
*/ |
| 33 |
private string $source; |
| 34 |
|
| 35 |
/** |
| 36 |
* Constructor. |
| 37 |
*/ |
| 38 |
public function __construct(string $domain, string $source, string $cacheBuster = '') |
| 39 |
{ |
| 40 |
$this->domain = $domain; |
| 41 |
$this->properties = []; |
| 42 |
$this->source = $source; |
| 43 |
|
| 44 |
if (!empty($cacheBuster)) { |
| 45 |
$this->properties[] = new CacheBusterProperty($cacheBuster); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Convert the optimized resource to its string representation. |
| 51 |
*/ |
| 52 |
public function __toString(): string |
| 53 |
{ |
| 54 |
return $this->getUrl(); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Get the optimization properties used to optimize the resource. |
| 59 |
*/ |
| 60 |
public function getProperties(): array |
| 61 |
{ |
| 62 |
return $this->properties; |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* Get the source of the resource being optimized. |
| 67 |
*/ |
| 68 |
public function getSource(): string |
| 69 |
{ |
| 70 |
return is_numeric($this->source) ? sprintf('id:%s', $this->source) : $this->source; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Get the URL for the optimized resource. |
| 75 |
*/ |
| 76 |
public function getUrl(): string |
| 77 |
{ |
| 78 |
$url = sprintf('https://%s', trim($this->domain, '/')); |
| 79 |
|
| 80 |
if (!empty($this->properties)) { |
| 81 |
$url .= sprintf('/%s', implode('/', $this->properties)); |
| 82 |
} |
| 83 |
|
| 84 |
return sprintf('%s/%s', $url, ltrim($this->getSource(), '/')); |
| 85 |
} |
| 86 |
|
| 87 |
/** |
| 88 |
* Add a property to the optimization properties. |
| 89 |
*/ |
| 90 |
protected function addProperty(PropertyInterface $property): void |
| 91 |
{ |
| 92 |
$this->properties[] = $property; |
| 93 |
} |
| 94 |
} |
| 95 |
|