julienmonnerie/kirby/src/Filesystem/Asset.php

101 lines
2 KiB
PHP
Raw Normal View History

2022-06-17 17:51:59 +02:00
<?php
namespace Kirby\Filesystem;
use Kirby\Cms\FileModifications;
/**
* Anything in your public path can be converted
* to an Asset object to use the same handy file
* methods as for any other Kirby files. Pass a
* relative path to the class to create the asset.
*
* @package Kirby Filesystem
* @author Bastian Allgeier <bastian@getkirby.com>
* @link https://getkirby.com
* @copyright Bastian Allgeier
* @license https://getkirby.com/license
*/
class Asset
{
2022-08-31 15:02:43 +02:00
use IsFile;
use FileModifications;
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Relative file path
*/
2022-12-19 14:56:05 +01:00
protected string|null $path = null;
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Creates a new Asset object for the given path.
*/
public function __construct(string $path)
{
$this->setProperties([
'path' => dirname($path),
'root' => $this->kirby()->root('index') . '/' . $path,
'url' => $this->kirby()->url('base') . '/' . $path
]);
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns a unique id for the asset
*/
public function id(): string
{
return $this->root();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Create a unique media hash
*/
public function mediaHash(): string
{
return crc32($this->filename()) . '-' . $this->modified();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns the relative path starting at the media folder
*/
public function mediaPath(): string
{
return 'assets/' . $this->path() . '/' . $this->mediaHash() . '/' . $this->filename();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns the absolute path to the file in the public media folder
*/
public function mediaRoot(): string
{
return $this->kirby()->root('media') . '/' . $this->mediaPath();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns the absolute Url to the file in the public media folder
*/
public function mediaUrl(): string
{
return $this->kirby()->url('media') . '/' . $this->mediaPath();
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Returns the path of the file from the web root,
* excluding the filename
*/
public function path(): string
{
return $this->path;
}
2022-06-17 17:51:59 +02:00
2022-08-31 15:02:43 +02:00
/**
* Setter for the path
*
* @return $this
*/
2022-12-19 14:56:05 +01:00
protected function setPath(string $path): static
2022-08-31 15:02:43 +02:00
{
$this->path = $path === '.' ? '' : $path;
return $this;
}
2022-06-17 17:51:59 +02:00
}