FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Location.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred;
4 
5 class Location extends Component{
6 
7  public $rules = []; //!< Location rules (key = mask, value = array with path, version, and format - all optional).
8  public $version = null; //!< Default version (empty = FRED™ version).
9  public $format = '[full]?v=[version]'; //!< Default version format ([full] or [base] and [ext], and [version] are replaced).
10 
11  protected function init(){
12  parent::init();
13  if(!$this->version) $this->version = $this->_fred->version;
14  }
15  /**
16  * Add a rule.
17  * @param string $mask Location mask (case insensitive prefix or regex) for locations that should follow this rule.
18  * @param string $path Path for this type (replaces the last capturing group of the mask, or complete match if no group).
19  * @param string $version Default version for this type.
20  * @param string $format Filename format ([full] or [base] and [ext], and [version] are replaced).
21  */
22  public function rule($mask,$path,$version = null,$format = null){
23  $this->rules[$mask] = array_filter(compact('path','version','format'));
24  }
25  /**
26  * Rewrite a location according to the rules.
27  * @param string $url Base/default location.
28  * @return string Rewritten location.
29  */
30  public function rewrite($url){
31  $rule = null;
32  $remote = strpos($url,'//') !== false;
33  foreach($this->rules as $mask => $params)
34  if(
35  preg_match(substr($mask,0,1) == '/' ? $mask : '/^\\/' . preg_quote($mask,'/') . '\\//i',$url,$match) &&
36  (!$remote || ($params['remote'] ?? null))
37  ){
38  if($path = \Rsi\Record::get($rule = $params,'path')) $url = str_replace(array_pop($match),$path,$url);
39  break;
40  }
41  if(is_array($rule) && ($i = strrpos($url,'.'))){
42  $rule += ['version' => $this->version,'format' => $this->format];
43  $time = $this->filemtime(\Rsi\Http::docRoot() . $url);
44  $url = strtr($rule['format'],['[full]' => $url,'[base]' => substr($url,0,$i),'[ext]' => substr($url,$i + 1),'[version]' => $time
45  ? ($this->_fred->debug ? date('Ymd-His',$time) : base_convert($time - 1433116800,10,36))
46  : preg_replace('/\\W/','-',$rule['version'])
47  ]);
48  }
49  return $url;
50  }
51 
52 }
$format
Default version format ([full] or [base] and [ext], and [version] are replaced).
Definition: Location.php:9
version(&$hash=null)
Version without hash.
Definition: Fred.php:359
filemtime($filename)
Filemtime with session cache.
Definition: Component.php:66
$version
Default version (empty = FRED™ version).
Definition: Location.php:8
rule($mask, $path, $version=null, $format=null)
Add a rule.
Definition: Location.php:22
Basic component class.
Definition: Component.php:8
rewrite($url)
Rewrite a location according to the rules.
Definition: Location.php:30
$rules
Location rules (key = mask, value = array with path, version, and format - all optional).
Definition: Location.php:7