/** * Get new collection groupped by $groupper argument * If the $grupper * @param int|string|callable $groupper * @param bool $force_property Force to handle $groupper as property name * @return Collection */ public function group($groupper, $force_property = false) { $res = new Collection(); $initial_key = key($this->data); if (!$force_property) { if (is_numeric($groupper)) { $c = 0; $r = 0; foreach ($this as $item) { if ($c % $groupper == 0) { $r++; } if (!isset($res[$r])) { $res[$r] = new Collection(); } $res[$r][] = $item; $c++; } $this->setPosition($initial_key); return $res; } if (is_callable($groupper)) { foreach ($this as $item) { $key = call_user_func($groupper, $item); if (!isset($res[$key])) { $res[$key] = new Collection(); } $res[$key][] = $item; } $this->setPosition($initial_key); return $res; } } if (is_string($groupper)) { $modifiers = array(); if (preg_match("~\\|~", $groupper)) { $groupper_parts = explode("|", $groupper, 2); $groupper = trim($groupper_parts[0]); $p = new Template\ModifierParser(); $parsed_modifiers = $p->parse('|' . $groupper_parts[1]); if ($parsed_modifiers) { foreach ($parsed_modifiers as $pmod) { $callback = $pmod['name']; $args = $pmod['args']; if (!is_callable($callback)) { continue; } $self_key = array_keys($args, "self"); if (isset($self_key[0])) { $self_key = $self_key[0]; } else { array_unshift($args, ''); $self_key = 0; } foreach ($args as &$arg_v) { $arg_v = trim($arg_v, '"\''); } $modifiers[] = array($callback, $args, $self_key); } } } foreach ($this as $item) { $key = $item[$groupper]; if (is_null($key)) { $key = ''; } else { foreach ($modifiers as $mod) { $callback = $mod[0]; $self_key = $mod[2]; $args = $mod[1]; $args[$self_key] = $key; $key = call_user_func_array($callback, $args); } } if ($key instanceof Entity) { $key_index = $key['id']; } else { $key_index = $key; } if (!isset($res[$key_index])) { $group_collection = $this->fork(); $group_collection->group_key = $key; $res[$key_index] = $group_collection; } $res[$key_index][] = $item; } $this->setPosition($initial_key); return $res; } $this->setPosition($initial_key); }
public static function getVarModifiers($source_str) { $p = new ModifierParser(); $res = $p->parse($source_str); return $res; }