<?php
class BreadCrumbs{
public $separator = " > ";
public $indexkey = "index";
public $wrap = "li";
public $text = "";
public function __construct(){
$this -> pattern = array();
$this -> uri = "";
}
public function setPattern( $arg ){
$this -> pattern = $arg;
}
public function setURI($arg){
$this -> uri = $this -> trimURI($arg);
}
public function setAfterText($arg){
$this -> text = $arg;
}
public function setIndexKey($arg){
$this -> indexkey = $arg;
}
public function setWrap($arg){
$this -> wrap = $arg;
}
public function setSeparator( $arg ){
$this -> separator = $arg;
}
public function getString(){
$str = "";
if($this->uri == "") $this->uri = $this->trimURI($_SERVER["REQUEST_URI"]);
$exp = explode("/",$this->trimURI($this->uri));
$v = $this -> patternSearch($this->pattern,$exp);
if(!$v)return false;
if($this->extraPattern($this -> uri)){
unset($v[1][count($v[1])-1]);
}
foreach($v[1] as $e){
$str .= $this -> link($e["name"],$e["url"]);
$str .= $this -> separator."\n";
}
$str .= is_string($v[0])? $v[0]: (is_object($v[0])?$v[0]():"E");
return $str;
}
private function extraPattern($uri){
$regex = "/^\/.*?\/$/";
return preg_match($regex,$uri);
}
private function patternSearch($v,$exp){
$uri = "";
$cnt = count($exp);
$history= array();
for($i =0; $i<$cnt;$i++){
if(isset($result) && is_array($result) && isset($result["index"])) {
$history[] = array( "name" => $result["index"], "url" => $uri);
}
$result = $this -> inArrayKey($v,$exp[$i]);
if($result === false) return false;
if(is_array($result)){
$uri .= $exp[$i]."/";
}else{
$uri .= $exp[$i];
}
$v = $result;
}
return array($v,$history);
}
private function inArrayKey($v,$x){
if( $x == "") $x = $this -> indexkey;
return (is_array($v) && isset($v[$x]))?$v[$x]:false;
}
private function link($text,$url){
if($this -> wrap != ""){
return "<{$this->wrap}><a href=\"{$url}\">{$text}</a>{$this->text}</{$this->wrap}>";
}
return "<a href=\"{$url}\">{$text}</a>";
}
private function trimURI( $uri ){
if(strpos($uri,'?')!== false){
list($uri) = explode('?',$uri,2);
}
if(strpos($uri,'#')!== false){
list($uri) = explode('#',$uri,2);
}
return $uri;
}
}
$pattern = array(
"index"=>array(
"index" => "TOP",
"contents" => array("index"=> "コンテンツ","archive"=>function(){return "アーカイブ";}),
"contact" => array("index"=> "お問い合わせ"),
),
);
$bc = new BreadCrumbs();
$bc -> setPattern($pattern);
$bc -> setWrap("span");
$bc -> setURI("/contents/archive");
echo $bc -> getString();