1: <?php
2:
3: namespace Deimos\Flow\Extension\TForeach;
4:
5: use Deimos\Flow\FlowFunction;
6:
7: class TForeach extends FlowFunction
8: {
9:
10: public static $level = 0;
11: public static $name = [];
12:
13: public function view()
14: {
15: self::$level++;
16: $separator = array_shift($this->data);
17:
18: if ($separator === ':')
19: {
20: self::$name[self::$level] = array_shift($this->data);
21: array_shift($this->data);
22: }
23:
24: $implode = implode($this->data);
25:
26: preg_match(sprintf('~from=(?<from>%s)~', self::REGEXP_VARIABLE), $implode, $from);
27: preg_match(sprintf('~key=(?<key>%s)~', self::REGEXP_CALLBACK), $implode, $key);
28: preg_match(sprintf('~item=(?<item>%s)~', self::REGEXP_CALLBACK), $implode, $item);
29: preg_match(sprintf('~name=(?<name>%s)~', self::REGEXP_CALLBACK), $implode, $name);
30:
31: $regExp = true;
32:
33: if (!empty($from['from']))
34: {
35: $variable = $from['from'];
36: $matches['variable'] = $variable;
37: $matches['item'] = empty($item['item']) ? '' : '$' . $item['item'];
38: $matches['key'] = empty($key['key']) ? '' : '$' . $key['key'];
39: self::$name[self::$level] = $name['name'];
40: $regExp = false;
41: }
42: else
43: {
44: $variable = array_shift($this->data);
45: }
46:
47: if ($variable{0} !== '$')
48: {
49: throw new \InvalidArgumentException(
50: 'Foreach error!
51: Not found ARRAY ' . $variable . var_export($this->data, true) . '!'
52: );
53: }
54:
55: $if = sprintf('<?php if (!empty(%s)): ?>', $variable);
56: $init = '';
57:
58: if ($regExp)
59: {
60:
61: $regExp = sprintf(
62: '~(?<variable>%s) as (?<key>%s)? ?=?>? ?(?<item>%s)~',
63: self::REGEXP_VARIABLE,
64: self::REGEXP_VARIABLE,
65: self::REGEXP_VARIABLE
66: );
67:
68: preg_match($regExp, $variable . implode($this->data), $matches);
69: unset($variable);
70:
71: }
72:
73: if (empty($matches['variable']))
74: {
75: throw new \InvalidArgumentException('Foreach not found variable');
76: }
77:
78: if (empty($matches['item']))
79: {
80: throw new \InvalidArgumentException('Foreach not found item');
81: }
82:
83: if (empty($matches['key']))
84: {
85: $matches['key'] = '$key' . $this->random() . $this->random();
86: }
87:
88: if (!empty(self::$name[self::$level]))
89: {
90: $if .= ' <?php $this->foreach->register(\'' . self::$name[self::$level] . '\', ' . $matches['variable'] . '); ?>';
91: $init = '$this->foreach->' . self::$name[self::$level] . '(' . $matches['key'] . ');';
92: }
93:
94: $foreach = sprintf(
95: '<?php foreach (%s as %s => %s): %s ?>',
96: $matches['variable'],
97: $matches['key'],
98: $matches['item'],
99: $init
100: );
101:
102: return $if . $foreach;
103: }
104:
105: }