123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214 |
- <?php
- namespace Cube\View\Helper;
- class HeadMeta extends AbstractHelper
- {
-
- const SET = 'set';
- const APPEND = 'append';
- const PREPEND = 'prepend';
-
- protected $_container = array();
-
- public function headMeta()
- {
- return $this;
- }
-
- public function __call($method, $args)
- {
- if (preg_match('/^(?P<action>set|(pre|ap)pend)(?P<type>Name|HttpEquiv|Property|Charset)$/', $method, $matches)
- ) {
- $action = '_' . $matches['action'];
- $type = strtolower(
- preg_replace("/([a-z])([A-Z])/", '$1-$2', $matches['type']));
- $nbArgs = count($args);
- if ($nbArgs < 1 || $nbArgs > 2) {
- throw new \InvalidArgumentException("Invalid number of arguments given in headMeta function call.");
- }
- if (!isset($args[1])) {
- $args[1] = null;
- }
- $data = $this->_createData($type, $args[0], $args[1]);
- $this->$action($data);
- }
- return $this;
- }
-
- protected function _append($data)
- {
- array_push($this->_container, $data);
- return $this;
- }
-
- protected function _prepend($data)
- {
- array_unshift($this->_container, $data);
- return $this;
- }
-
- protected function _set($data)
- {
- foreach ($this->_container as $key => $item) {
- if (strcmp($item['value'], $data['value']) === 0 && strcmp($item['key'], $data['key']) === 0) {
- unset($this->_container[$key]);
- }
- }
- return $this->_append($data);
- }
-
- public function clearContainer()
- {
- $this->_container = array();
- return $this;
- }
-
- protected function _createData($keyName, $keyValue, $content)
- {
- return array(
- 'key' => $keyName,
- 'value' => $keyValue,
- 'content' => $content,
- );
- }
-
- public function __toString()
- {
- $output = null;
- foreach ($this->_container as $item) {
- if (isset($item['content'])) {
- if (!empty($item['content'])) {
- $output .= sprintf('<meta %s="%s" content="%s">', $item['key'], $item['value'],
- str_ireplace('"', '', $item['content'])) . "\n";
- }
- }
- else {
- $output .= sprintf('<meta %s="%s">', $item['key'], $item['value']) . "\n";
- }
- }
- return strval($output);
- }
-
- protected function _normalizeType($type)
- {
- switch ($type) {
- case 'Name':
- return 'name';
- case 'HttpEquiv':
- return 'http-equiv';
- default:
- throw new \InvalidArgumentException("Invalid headMeta type function called.");
- }
- }
- }
|