1<?php 2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project 3// 4// All Rights Reserved. See copyright.txt for details and a complete list of authors. 5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. 6// $Id$ 7 8namespace Tiki\Yaml\Directive; 9 10use Symfony\Component\Yaml\Yaml; 11 12class DirectiveInclude 13{ 14 protected $props; 15 16 public function process(&$value, $key, $props) 17 { 18 $this->props = $props; 19 20 if (is_array($value)) { 21 foreach ($value as $definition) { 22 if ($this->conditionalInclude($definition, $value, $key)) { 23 return; 24 } 25 } 26 } else { 27 $this->conditionalInclude($value, $value, $key); 28 } 29 } 30 31 protected function conditionalInclude($definition, &$value, $key) 32 { 33 $parsed = $this->parse($definition); 34 35 $yamlFile = $parsed[0]; 36 37 if (count($parsed) == 1) { 38 $result = true; 39 } else { 40 if (count($parsed) == 2) { 41 $leftValue = $parsed[1]; 42 $operation = 'eq'; 43 $rightValue = $parsed[2]; 44 } else { 45 $leftValue = $parsed[1]; 46 $operation = $parsed[2]; 47 $rightValue = $parsed[3]; 48 } 49 50 $result = $this->checkCondition($operation, $leftValue, $rightValue); 51 } 52 53 if ($result) { 54 $yaml = Yaml::parse(file_get_contents($this->props['path'] . '/' . $yamlFile)); 55 if (is_array($yaml) && (count($yaml) == 1) && array_key_exists($key, $yaml)) { 56 $value = $yaml[$key]; 57 } else { 58 $value = $yaml; 59 } 60 } 61 return $result; 62 } 63 64 protected function parse($str) 65 { 66 $str = trim(substr($str, strlen('!include'))); 67 $parts = explode(" ", $str); 68 return $parts; 69 } 70 71 /** 72 * @param $operation 73 * @param $leftValue 74 * @param $rightValue 75 * @return bool 76 */ 77 protected function checkCondition($operation, $leftValue, $rightValue) 78 { 79 switch ($operation) { 80 case 'eq': 81 return ($leftValue == $rightValue); 82 case 'neq': 83 return ($leftValue != $rightValue); 84 case 'lt': 85 return ($leftValue < $rightValue); 86 case 'le': 87 return ($leftValue <= $rightValue); 88 case 'gt': 89 return ($leftValue > $rightValue); 90 case 'ge': 91 return ($leftValue >= $rightValue); 92 default: 93 return false; 94 } 95 } 96} 97