/** * Return all blocks to render in the given row column * * @param int $column Numeric column index, starting with 1 * @return array */ public function getBlocksForColumn($column) { $blocks = new \Cake\Collection\Collection($this->cms_blocks); return $blocks->filter(function ($block) use($column) { return $block->column_index == $column; })->toArray(); }
/** * Index method * * @return \Cake\Network\Response|null */ public function index() { $releases = $this->Releases->find('all')->all(); $collection = new Collection($releases); $attribute_names = array_unique($collection->extract('attribute_name')->toArray()); $idps = array_unique($collection->extract('idp')->toArray()); $releasesByIdp = $collection->groupBy('idp')->toArray(); foreach ($idps as $idp) { foreach ($attribute_names as $attribute) { $releasesByIdPbyAttribute = $collection->match(['idp' => $idp, 'attribute_name' => $attribute]); $temp_result = $releasesByIdPbyAttribute->countBy(function ($result) { return strtolower($result->validated) == 'fail' ? 'fail' : 'pass'; }); $results[$idp][$attribute] = $temp_result->toArray(); } } # My attributes $persistentid_array = preg_split('/!/', $this->request->env('persistent-id')); $persistentid = end($persistentid_array); $myAttributesTemp = $this->Releases->find()->andWhere(['idp' => $this->request->env('Shib-Identity-Provider'), 'persistentid' => $persistentid])->all(); $myAttributesCollection = new Collection($myAttributesTemp); $myAttributes = $myAttributesCollection->groupBy('attribute_name')->toArray(); $this->set(compact('myAttributes')); $this->set('_serialize', ['myAttributes']); $this->set(compact('results')); $this->set('_serialize', ['results']); $this->set(compact('idps')); $this->set('_serialize', ['idps']); $this->set(compact('attribute_names')); $this->set('_serialize', ['attribute_names']); }
/** * Index method * * @return void */ public function index() { //$this->set('categorias', $this->paginate($this->Categorias)); $find = $this->Categorias->find('all', ['fields' => ['id', 'categoria_id', 'nome']])->toArray(); $collection = new Collection($find); $categorias = $collection->nest('id', 'categoria_id')->toArray(); $this->set('categorias', $categorias); $this->set('_serialize', ['categorias']); }
/** * Returns the next highest position for adding a new row * * @return int */ public function getNextRowPosition() { $rows = new Collection($this->cms_rows); $highestRow = $rows->max('position'); $maxPosition = 0; if ($highestRow) { $maxPosition = $highestRow->position; } return $maxPosition + 1; }
public function getPhotosSorted() { if (isset($this->photos) and !empty($this->photos)) { $photosCollection = new Collection($this->photos); return $photosCollection->sortBy(function ($photo) { return $photo->sort_order; }, SORT_ASC)->toArray(); } return []; }
/** * Checks if the provided $roleId is allowed to perform the given $action. * * @param int $roleId Role ID * @param string $action Action to check: create, edit, delete or publish * @return bool */ public function checkPermission($roleId, $action) { if ($roleId == ROLE_ID_ADMINISTRATOR) { return true; } $this->_loadPermissions(); $rule = $this->_permissions->filter(function ($rule) use($roleId, $action) { return $rule->get('role_id') == $roleId && $rule->get('action') == $action; })->first(); return !empty($rule); }
public function _getLastFiveComments() { $alias = Inflector::classify($this->source()); $comment = TableRegistry::get('Social.Comments'); $comments = $comment->find()->where(['Comments.object_id' => $this->id, 'Comments.object' => $alias])->limit(__MAX_COMMENTS_LISTED)->order('Comments.created DESC')->contain(['Authors' => ['fields' => ['id', 'first_name', 'last_name', 'avatar']]]); // Reorder the Comments by creation order // (even though we got them by descending order) $collection = new Collection($comments); $comments = $collection->sortBy('Comment.created'); return $comments->toArray(); }
/** * Method that retrieves select input options by list name. * * @param string $listName list name * @param string $spacer The string to use for prefixing the values according to * their depth in the tree * @param bool $flatten flat list flag * @return array list options */ protected function _getSelectOptions($listName, $spacer = ' - ', $flatten = true) { $result = $this->__getListFieldOptions($listName); $result = $this->__filterOptions($result); if (!$flatten) { return $result; } // flatten list options $collection = new Collection($result); $result = $collection->listNested()->printer('name', 'id', $spacer)->toArray(); return $result; }
protected function _getTagString() { if (isset($this->_properties['tag_string'])) { return $this->_properties['tag_string']; } if (empty($this->tags)) { return ''; } $tags = new Collection($this->tags); $str = $tags->reduce(function ($string, $tag) { return $string . $tag->label . ', '; }, ''); return trim($str, ', '); }
/** * This method is called in case a primary key was defined using the addPrimaryKey() method. * It currently does something only if using SQLite. * If a column is an auto-increment key in SQLite, it has to be a primary key and it has to defined * when defining the column. Phinx takes care of that so we have to make sure columns defined as autoincrement were * not added with the addPrimaryKey method, otherwise, SQL queries will be wrong. * * @return void */ protected function filterPrimaryKey() { if ($this->getAdapter()->getAdapterType() !== 'sqlite' || empty($this->options['primary_key'])) { return; } $primaryKey = $this->options['primary_key']; if (!is_array($primaryKey)) { $primaryKey = [$primaryKey]; } $primaryKey = array_flip($primaryKey); $columnsCollection = new Collection($this->columns); $primaryKeyColumns = $columnsCollection->filter(function ($columnDef, $key) use($primaryKey) { return isset($primaryKey[$columnDef->getName()]); })->toArray(); if (empty($primaryKeyColumns)) { return; } foreach ($primaryKeyColumns as $primaryKeyColumn) { if ($primaryKeyColumn->isIdentity()) { unset($primaryKey[$primaryKeyColumn->getName()]); } } $primaryKey = array_flip($primaryKey); if (!empty($primaryKey)) { $this->options['primary_key'] = $primaryKey; } else { unset($this->options['primary_key']); } }
public function get_for_parent($parent, $page) { $comments = $this->Comments->find()->where(['Comments.object_id' => $parent])->limit(__MAX_COMMENTS_LISTED)->page($page)->order('Comments.created DESC')->contain(['Authors' => ['fields' => ['id', 'first_name', 'last_name', 'avatar']]]); // Reorder the Comments by creation order // (even though we got them by descending order) $collection = new Collection($comments); $comments = $collection->sortBy('Comment.created'); $view = new View($this->request, $this->response, null); $view->layout = 'ajax'; // layout to use or false to disable $view->set('comments', $comments->toArray()); $data['html'] = $view->render('Social.Comments/get_for_parent'); $this->layout = 'ajax'; $this->set('data', $data); $this->render('/Shared/json/data'); }
/** * Evaluates the condition and returns its result, this controls * whether or not more results will be yielded. * * @return bool */ public function valid() { if (!parent::valid()) { return false; } $current = $this->current(); $key = $this->key(); $condition = $this->_condition; return !$condition($current, $key, $this->_innerIterator); }
/** * addPattern * */ public function addPattern($field, $pattern) { $pattern = new Collection((array) $pattern); $validationSet = $this->field($field); $validationPatterns = self::$validationPatterns; $pattern->each(function ($key) use($field, $validationSet, $validationPatterns) { if (empty($validationPatterns[$key])) { if (method_exists($this, $key)) { $this->{$key}($field); return; } throw new NoValidationPatternException('Not found pattern `' . $key . '`'); } $rules = new Collection($validationPatterns[$key]); $rules->each(function ($rule, $name) use($validationSet) { $validationSet->add($name, $rule); }); }); return $this; }
public function getLibrary() { $this->viewBuilder()->layout("ajax"); $this->autoRender = false; $this->loadModel('Playlists'); $this->loadModel('Tracks'); $userId = $this->request->session()->read('user.id'); $library = $this->Playlists->find('all')->where(['user_id' => $userId])->contain('Tracks'); if ($library->count() == 0) { echo json_encode(['success' => false]); return; } $library = $library->toArray(); // remove tracks from playlists $libraryCollection = new Collection($library); $playlists = $libraryCollection->extract(function ($list) { unset($list->tracks); return $list; }); // if tokens is expired get new downloadUrls // GAUTH: is token expired $gotUpdatedDownloadUrls = false; $client = new \Google_Client(); $client->setAuthConfigFile('../client_secret.json'); $client->addScope(\Google_Service_Drive::DRIVE); if ($this->request->session()->check('user.drive_token')) { $client->setAccessToken($this->request->session()->read('user.drive_token')); if ($client->isAccessTokenExpired()) { $gotUpdatedDownloadUrls = true; } } else { $gotUpdatedDownloadUrls = true; } $driveFiles = $this->getMusicFromDrive(); $driveFileUrlById = (new Collection($driveFiles))->combine('id', function ($entity) { return str_replace("?e=download&gd=true", "", $entity['downloadUrl']); })->toArray(); // create tracks by playlist id, also update new download_url if gotten it $tracksByPlaylistId = []; $tracksById = []; foreach ($library as $list) { $tracksByPlaylistId[$list->id] = []; foreach ($list->tracks as $track) { if ($gotUpdatedDownloadUrls) { $this->Tracks->patchEntity($track, ['download_url' => $driveFileUrlById[$track->drive_id]]); $this->Tracks->save($track); } $tracksByPlaylistId[$track->playlist_id][] = $track; $tracksById[$track->id] = $track; } } echo json_encode(['playlists' => $playlists, 'tracksByPlaylistId' => $tracksByPlaylistId, 'tracksById' => $tracksById]); }
public function isPermitted($permissions, $operator = OPERATOR_AND) { $session = $this->request->session()->read('Auth.User'); if ($session['idr_admin']) { return true; } $acoes = new Collection($session['acoes']); if (is_array($permissions)) { if ($operator == OPERATOR_AND) { foreach ($permissions as $k => $p) { $permitido = $acoes->filter(function ($acao, $key) use($p) { return mb_strtoupper($acao['tag']) == mb_strtoupper($p); }); if (count($permitido->toArray()) == 0) { break; } } } else { foreach ($permissions as $k => $p) { $permitido = $acoes->filter(function ($acao, $key) use($p) { return mb_strtoupper($acao['tag']) == mb_strtoupper($p); }); if (count($permitido->toArray()) > 0) { break; } } } } else { $permitido = $acoes->filter(function ($acao, $key) use($permissions) { return mb_strtoupper($acao['tag']) == mb_strtoupper($permissions); }); } if (count($permitido->toArray()) > 0) { return true; } else { return false; } }
private function anyPermitted($permissions, $operator = self::OPERATOR_AND) { $session = $this->request->session()->read('Auth.User'); if ($session['idr_admin']) { return true; } $acoes = new Collection($session['acoes']); if (is_array($permissions)) { if ($operator == self::OPERATOR_AND) { foreach ($permissions as $k => $p) { $permitido = $acoes->filter(function ($acao, $key) use($p) { return mb_strtoupper($acao['tag']) == mb_strtoupper($p); }); if (count($permitido->toArray()) == 0) { break; } } } else { foreach ($permissions as $k => $p) { $permitido = $acoes->filter(function ($acao, $key) use($p) { return mb_strtoupper($acao['tag']) == mb_strtoupper($p); }); if (count($permitido->toArray()) > 0) { break; } } } } else { $permitido = $acoes->filter(function ($acao, $key) use($permissions) { return mb_strtoupper($acao['tag']) == mb_strtoupper($permissions); }); } if (count($permitido->toArray()) == 0) { throw new UnauthorizedException("Usuário da sessão não possui permissão para acessar a ação escolhida"); } }
/** * Wraps this iterator around the passed items so when iterated they are returned * in order. * * The callback will receive as first argument each of the elements in $items, * the value returned in the callback will be used as the value for sorting such * element. Please not that the callback function could be called more than once * per element. * * @param array|\Traversable $items The values to sort * @param callable|string $callback A function used to return the actual value to * be compared. It can also be a string representing the path to use to fetch a * column or property in each element * @param int $dir either SORT_DESC or SORT_ASC * @param int $type the type of comparison to perform, either SORT_STRING * SORT_NUMERIC or SORT_NATURAL */ public function __construct($items, $callback, $dir = SORT_DESC, $type = SORT_NUMERIC) { if (is_array($items)) { $items = new Collection($items); } $items = iterator_to_array($items, false); $callback = $this->_propertyExtractor($callback); $results = []; foreach ($items as $key => $value) { $results[$key] = $callback($value); } $dir === SORT_DESC ? arsort($results, $type) : asort($results, $type); foreach (array_keys($results) as $key) { $results[$key] = $items[$key]; } parent::__construct($results); }
/** * Retrieves a type that should be used for a specific field * * @param string $field Name of field * @param string $type User-specified type * @return string */ public function getType($field, $type) { $reflector = new ReflectionClass('Phinx\\Db\\Adapter\\AdapterInterface'); $collection = new Collection($reflector->getConstants()); $validTypes = $collection->filter(function ($value, $constant) { $value; return substr($constant, 0, strlen('PHINX_TYPE_')) === 'PHINX_TYPE_'; })->toArray(); $fieldType = $type; if ($type === null || !in_array($type, $validTypes)) { if ($type === 'primary') { $fieldType = 'integer'; } elseif ($field === 'id') { $fieldType = 'integer'; } elseif (in_array($field, ['created', 'modified', 'updated'])) { $fieldType = 'datetime'; } else { $fieldType = 'string'; } } return $fieldType; }
public function statistic($tournament_id) { $games = TableRegistry::get('Games')->find()->where(['tournament_id' => $tournament_id]); $statistics['matchs'] = 0; $statistics['goals'] = 0; $statistics['principals_victory'] = 0; $statistics['visitors_victory'] = 0; $statistics['draws'] = 0; foreach ($games as $key => $game) { $statistics['matchs']++; $statistics['goals'] += $game['score_a'] + $game['score_b']; if ($game['score_a'] > $game['score_b']) { $statistics['principals_victory']++; } else { if ($game['score_a'] < $game['score_b']) { $statistics['visitors_victory']++; } else { if (!is_null($game['score_a'])) { $statistics['draws']++; } } } } $conn = ConnectionManager::get('default'); $query = $conn->execute(' SELECT player, team_name, team_shield, IFNULL(sum(goals_pro),0) player_goals_pro, IFNULL(sum(goals_against),0) player_goals_against FROM ( ( SELECT u.id player_id, u.login player, te.name team_name, te.logo team_shield, SUM( score_a ) goals_pro, SUM( score_b ) goals_against FROM games g INNER JOIN tournaments t ON g.tournament_id = t.id INNER JOIN teams_tournaments_users tt ON tt.tournament_id = t.id AND tt.user_id = g.user_a_id INNER JOIN teams te ON te.id = tt.team_id INNER JOIN users u ON u.id = g.user_a_id WHERE t.id =' . $tournament_id . ' GROUP BY g.user_a_id ) UNION ( SELECT u.id player_id, u.login player, te.name team_name, te.logo team_shield, SUM( score_b ) goals_pro, SUM( score_a ) goals_against FROM games g INNER JOIN tournaments t ON g.tournament_id = t.id INNER JOIN teams_tournaments_users tt ON tt.tournament_id = t.id AND tt.user_id = g.user_b_id INNER JOIN teams te ON te.id = tt.team_id INNER JOIN users u ON u.id = g.user_b_id WHERE t.id =' . $tournament_id . ' GROUP BY g.user_b_id ) ORDER BY goals_pro DESC ) a GROUP BY player_id ORDER BY player_goals_pro DESC '); $playersGoals = $query->fetchAll('assoc'); $statistics['best_atack'] = []; $statistics['best_atack'][0]['player'] = $playersGoals[0]['player']; $statistics['best_atack'][0]['team'] = $playersGoals[0]['team_name']; $statistics['best_atack'][0]['shield'] = $playersGoals[0]['team_shield']; $statistics['best_atack'][0]['goals'] = $playersGoals[0]['player_goals_pro']; foreach ($playersGoals as $key => $row) { if ($statistics['best_atack'][0]['goals'] == $row['player_goals_pro']) { $statistics['best_atack'][$key]['player'] = $row['player']; $statistics['best_atack'][$key]['team'] = $row['team_name']; $statistics['best_atack'][$key]['shield'] = $row['team_shield']; $statistics['best_atack'][$key]['goals'] = $row['player_goals_pro']; } } $playersGoalsCollection = new Collection($playersGoals); $playersGoals = $playersGoalsCollection->sortBy('player_goals_against', SORT_ASC, SORT_NUMERIC)->toArray(); $playersGoals = array_values($playersGoals); $statistics['best_defense'] = []; $statistics['best_defense'][0]['player'] = $playersGoals[0]['player']; $statistics['best_defense'][0]['team'] = $playersGoals[0]['team_name']; $statistics['best_defense'][0]['shield'] = $playersGoals[0]['team_shield']; $statistics['best_defense'][0]['goals'] = $playersGoals[0]['player_goals_against']; foreach ($playersGoals as $key => $row) { if ($statistics['best_defense'][0]['goals'] == $row['player_goals_against']) { $statistics['best_defense'][$key]['player'] = $row['player']; $statistics['best_defense'][$key]['team'] = $row['team_name']; $statistics['best_defense'][$key]['shield'] = $row['team_shield']; $statistics['best_defense'][$key]['goals'] = $row['player_goals_against']; } } $playersGoalsCollection = new Collection($playersGoals); $playersGoals = $playersGoalsCollection->sortBy('player_goals_pro', SORT_ASC, SORT_NUMERIC)->toArray(); $playersGoals = array_values($playersGoals); $statistics['worse_atack'] = []; $statistics['worse_atack'][0]['player'] = $playersGoals[0]['player']; $statistics['worse_atack'][0]['team'] = $playersGoals[0]['team_name']; $statistics['worse_atack'][0]['shield'] = $playersGoals[0]['team_shield']; $statistics['worse_atack'][0]['goals'] = $playersGoals[0]['player_goals_pro']; foreach ($playersGoals as $key => $row) { if ($statistics['worse_atack'][0]['goals'] == $row['player_goals_pro']) { $statistics['worse_atack'][$key]['player'] = $row['player']; $statistics['worse_atack'][$key]['team'] = $row['team_name']; $statistics['worse_atack'][$key]['shield'] = $row['team_shield']; $statistics['worse_atack'][$key]['goals'] = $row['player_goals_pro']; } } $playersGoalsCollection = new Collection($playersGoals); $playersGoals = $playersGoalsCollection->sortBy('player_goals_against', SORT_DESC, SORT_NUMERIC)->toArray(); $playersGoals = array_values($playersGoals); $statistics['worse_defense'] = []; $statistics['worse_defense'][0]['player'] = $playersGoals[0]['player']; $statistics['worse_defense'][0]['team'] = $playersGoals[0]['team_name']; $statistics['worse_defense'][0]['shield'] = $playersGoals[0]['team_shield']; $statistics['worse_defense'][0]['goals'] = $playersGoals[0]['player_goals_against']; foreach ($playersGoals as $key => $row) { if ($statistics['worse_defense'][0]['goals'] == $row['player_goals_against']) { $statistics['worse_defense'][$key]['player'] = $row['player']; $statistics['worse_defense'][$key]['team'] = $row['team_name']; $statistics['worse_defense'][$key]['shield'] = $row['team_shield']; $statistics['worse_defense'][$key]['goals'] = $row['player_goals_against']; } } $this->set('statistics', $statistics); }
/** * Returns the column value defined in $path or null if the path could not be * followed * * @return mixed */ public function current() { $current = parent::current(); return $this->_extract($current, $this->_path); }
/** * Resets the collection pointer. * * @return void */ public function rewind() { parent::rewind(); $this->_values->rewind(); $this->_validValues = $this->_values->valid(); }
/** * Advances the iterator pointer to the next element * * @return void */ public function next() { $this->_index++; if (!$this->_finished) { parent::next(); } }
public function getRanking($product_id, $videogame) { $players = []; $titles = TableRegistry::get('Users')->find()->select(['Users.id', 'Users.login', 'Users.photo', 'titles' => TableRegistry::get('Users')->find()->func()->count('Users.id')])->join(['Tournaments' => ['table' => 'tournaments', 'type' => 'INNER', 'conditions' => 'Users.id = Tournaments.champion_user_id']])->where(['Tournaments.product_id' => $product_id, 'Tournaments.videogame' => $videogame])->group(['Users.id', 'Users.login', 'Users.photo']); foreach ($titles as $key => $value) { if (isset($value['login'])) { $players[$value['id']]['login'] = $value['login']; } if (isset($value['photo'])) { $players[$value['id']]['photo'] = $value['photo']; } $players[$value['id']]['titles'] = $value['titles']; } $victoriesA = TableRegistry::get('Users')->find()->select(['Users.id', 'Users.login', 'Users.photo', 'victories' => TableRegistry::get('Users')->find()->func()->count('Users.id')])->join(['Games' => ['table' => 'games', 'type' => 'INNER', 'conditions' => 'Users.id = Games.user_a_id AND Games.score_a > Games.score_b'], 'Tournaments' => ['table' => 'tournaments', 'type' => 'INNER', 'conditions' => 'Tournaments.id = Games.tournament_id']])->where(['Tournaments.product_id' => $product_id, 'Tournaments.videogame' => $videogame])->group(['Users.id']); foreach ($victoriesA as $key => $value) { if (isset($value['login'])) { $players[$value['id']]['login'] = $value['login']; } if (isset($value['photo'])) { $players[$value['id']]['photo'] = $value['photo']; } if (isset($players[$value['id']]['victories'])) { $players[$value['id']]['victories'] += $value['victories']; } else { $players[$value['id']]['victories'] = $value['victories']; } } $victoriesB = TableRegistry::get('Users')->find()->select(['Users.id', 'victories' => TableRegistry::get('Users')->find()->func()->count('Users.id')])->join(['Games' => ['table' => 'games', 'type' => 'INNER', 'conditions' => 'Users.id = Games.user_b_id AND Games.score_b > Games.score_a'], 'Tournaments' => ['table' => 'tournaments', 'type' => 'INNER', 'conditions' => 'Tournaments.id = Games.tournament_id']])->where(['Tournaments.product_id' => $product_id, 'Tournaments.videogame' => $videogame])->group(['Users.id']); foreach ($victoriesB as $key => $value) { if (isset($value['login'])) { $players[$value['id']]['login'] = $value['login']; } if (isset($value['photo'])) { $players[$value['id']]['photo'] = $value['photo']; } if (isset($players[$value['id']]['victories'])) { $players[$value['id']]['victories'] += $value['victories']; } else { $players[$value['id']]['victories'] = $value['victories']; } } $goalA = TableRegistry::get('Users')->find()->select(['Users.id', 'goals' => TableRegistry::get('Users')->find()->func()->sum('Games.score_a')])->join(['Games' => ['table' => 'games', 'type' => 'INNER', 'conditions' => 'Users.id = Games.user_a_id AND Games.score_a > Games.score_b'], 'Tournaments' => ['table' => 'tournaments', 'type' => 'INNER', 'conditions' => 'Tournaments.id = Games.tournament_id']])->where(['Tournaments.product_id' => $product_id, 'Tournaments.videogame' => $videogame])->group(['Users.id']); foreach ($goalA as $key => $value) { if (isset($value['login'])) { $players[$value['id']]['login'] = $value['login']; } if (isset($value['photo'])) { $players[$value['id']]['photo'] = $value['photo']; } if (isset($players[$value['id']]['goals'])) { $players[$value['id']]['goals'] += $value['goals']; } else { $players[$value['id']]['goals'] = $value['goals']; } } $goalB = TableRegistry::get('Users')->find()->select(['Users.id', 'goals' => TableRegistry::get('Users')->find()->func()->sum('Games.score_b')])->join(['Games' => ['table' => 'games', 'type' => 'INNER', 'conditions' => 'Users.id = Games.user_b_id AND Games.score_b > Games.score_a'], 'Tournaments' => ['table' => 'tournaments', 'type' => 'INNER', 'conditions' => 'Tournaments.id = Games.tournament_id']])->where(['Tournaments.product_id' => $product_id, 'Tournaments.videogame' => $videogame])->group(['Users.id']); foreach ($goalB as $key => $value) { if (isset($value['login'])) { $players[$value['id']]['login'] = $value['login']; } if (isset($value['photo'])) { $players[$value['id']]['photo'] = $value['photo']; } if (isset($players[$value['id']]['goals'])) { $players[$value['id']]['goals'] += $value['goals']; } else { $players[$value['id']]['goals'] = $value['goals']; } } $playersCollection = new Collection($players); $players = $playersCollection->sortBy('titles', SORT_DESC, SORT_NUMERIC)->toArray(); $players = array_values($players); return $players; }
/** * Creates a filtered iterator using the callback to determine which items are * accepted or rejected. * * Each time the callback is executed it will receive the value of the element * in the current iteration, the key of the element and the passed $items iterator * as arguments, in that order. * * @param Iterator $items The items to be filtered. * @param callable $callback Callback. */ public function __construct(Iterator $items, callable $callback) { $wrapper = new CallbackFilterIterator($items, $callback); parent::__construct($wrapper); }
/** * Tests the chunk method with non-scalar items * * @return void */ public function testChunkNested() { $collection = new Collection([1, 2, 3, [4, 5], 6, [7, [8, 9], 10], 11]); $chunked = $collection->chunk(2)->toList(); $expected = [[1, 2], [3, [4, 5]], [6, [7, [8, 9], 10]], [11]]; $this->assertEquals($expected, $chunked); }
/** * Tests insert * * @return void */ public function testInsert() { $items = [['a' => 1], ['b' => 2]]; $collection = new Collection($items); $iterator = $collection->insert('c', [3, 4]); $this->assertInstanceOf('\\Cake\\Collection\\Iterator\\InsertIterator', $iterator); $this->assertEquals([['a' => 1, 'c' => 3], ['b' => 2, 'c' => 4]], iterator_to_array($iterator)); }
/** * Returns the value returned by the callback after passing the current value in * the iteration * * @return mixed */ public function current() { $callback = $this->_callback; return $callback(parent::current(), $this->key(), $this->_innerIterator); }
/** * Constructor * * @param array|\Traversable $items Collection items. * @param string|callable $nestKey the property that contains the nested items * If a callable is passed, it should return the childrens for the passed item */ public function __construct($items, $nestKey) { parent::__construct($items); $this->_nestKey = $nestKey; }
/** * Unserialize a resultset. * * Part of Serializable interface. * * @param string $serialized Serialized object * @return void */ public function unserialize($serialized) { parent::__construct(unserialize($serialized)); }
/** * Modifies the results from a table find in order to merge full translation records * into each entity under the `_translations` key * * @param \Cake\Datasource\ResultSetInterface $results Results to modify. * @return \Cake\Collection\Collection */ public function groupTranslations($results) { return $results->map(function ($row) { if (!$row instanceof EntityInterface) { return $row; } $translations = (array) $row->get('_i18n'); $grouped = new Collection($translations); $result = []; foreach ($grouped->combine('field', 'content', 'locale') as $locale => $keys) { $entityClass = $this->_table->entityClass(); $translation = new $entityClass($keys + ['locale' => $locale], ['markNew' => false, 'useSetters' => false, 'markClean' => true]); $result[$locale] = $translation; } $options = ['setter' => false, 'guard' => false]; $row->set('_translations', $result, $options); unset($row['_i18n']); $row->clean(); return $row; }); }