/** * Switch Context. * * @Route("/switch/{context}/{values}", name="bigfoot_context_switch") */ public function switchAction($context, $values) { $values = explode(',', $values); $chosenContexts = array($context => $values); $user = $this->getUser(); $requestStack = $this->getRequestStack(); if ($this->getContextManager()->isEntityContextualizable(get_class($user), $context)) { $context = $this->getEntityManager()->getRepository('BigfootContextBundle:Context')->findOneByEntityIdEntityClass($user->getId(), get_class($user)); if ($context) { $allowedContexts = $context->getContextValues(); $contextsIntersect = array_udiff($chosenContexts, $allowedContexts, array($this, 'intersectContexts')); $sessionChosenContexts = $this->getSession()->get('bigfoot/context/chosen_contexts'); if ($sessionChosenContexts) { $contextsDiff = array_udiff($contextsIntersect, $sessionChosenContexts, array($this, 'diffContexts')); } if (isset($contextsDiff) && !$contextsDiff) { $this->getSession()->set('bigfoot/context/chosen_contexts', null); } else { $this->getSession()->set('bigfoot/context/chosen_contexts', $contextsIntersect); } } else { $this->getSession()->set('bigfoot/context/chosen_contexts', $chosenContexts); } } else { $this->getSession()->set('bigfoot/context/chosen_contexts', $chosenContexts); } return $this->redirect($requestStack->headers->get('referer')); }
public function execute(array $collection) { $comparer = $this->getComparer(); return array_values(array_udiff($collection, $this->collectionToExcept, function ($a, $b) use($comparer) { return $comparer->equals($a, $b); })); }
function removeUnit(Unit $unit) { // удаление объекта типа Unit $this->units = array_udiff($this->units, [$unit], function ($a, $b) { return $a === $b ? 0 : 1; }); }
protected function PersistRelationshipChanges(Object\Domain $Domain, Object\UnitOfWork $UnitOfWork, $ParentEntity, $CurrentValue, $HasOriginalValue, $OriginalValue) { $RelationshipChanges = []; $OriginalEntities = []; $CurrentEntities = []; if ($HasOriginalValue) { $OriginalEntities =& $OriginalValue; } if (is_array($CurrentValue)) { $CurrentEntities =& $CurrentValue; } else { throw new Object\ObjectException('Invalid value for property on entity %s, array expected, %s given', $this->GetEntityType(), \Storm\Core\Utilities::GetTypeOrClass($CurrentValue)); } if ($CurrentEntities === $OriginalEntities) { return $RelationshipChanges; } $NewEntities = array_udiff($CurrentEntities, $OriginalEntities, [$this, 'ObjectComparison']); $RemovedEntities = array_udiff($OriginalEntities, $CurrentEntities, [$this, 'ObjectComparison']); foreach ($NewEntities as $NewEntity) { $RelationshipChanges[] = new Object\RelationshipChange($this->RelationshipType->GetPersistedRelationship($Domain, $UnitOfWork, $ParentEntity, $NewEntity), null); } foreach ($RemovedEntities as $RemovedEntity) { $RelationshipChanges[] = new Object\RelationshipChange(null, $this->RelationshipType->GetDiscardedRelationship($Domain, $UnitOfWork, $ParentEntity, $RemovedEntity)); } return $RelationshipChanges; }
/** * Returns true if the callbacks $a and $b are the same. * * @param callback $a * @param callback $b * @return bool */ public static function compareCallbacks($a, $b) { if (is_string($a) || is_string($b)) { return $a === $b; } return count(array_udiff($a, $b, array('ezcSignalCallbackComparer', 'comp_func'))) == 0; }
/** * Tests that updating the start time of an event keeps the occurrence IDs. * This *may* change as occurrences may be able to share the same date * @see https://github.com/stephenharris/Event-Organiser/issues/240 * * @see https://wordpress.org/support/topic/all-events-showing-1200-am-as-start-and-end-time * @see https://github.com/stephenharris/Event-Organiser/issues/195 */ public function testUpdateTimeOnly() { $tz = eo_get_blog_timezone(); $event = array('start' => new DateTime('2013-10-19 15:30:00', $tz), 'end' => new DateTime('2013-10-19 15:45:00', $tz), 'frequeny' => 1, 'schedule' => 'weekly', 'number_occurrences' => 4); //Create event and store occurrences $event_id = eo_insert_event($event); $original_occurrences = eo_get_the_occurrences($event_id); //Update event $new_event_data = $event; $new_event_data['start'] = new DateTime('2013-10-19 14:30:00', $tz); eo_update_event($event_id, $new_event_data); //Get new occurrences $new_occurrences = eo_get_the_occurrences($event_id); //Compare $added = array_udiff($new_occurrences, $original_occurrences, '_eventorganiser_compare_dates'); $removed = array_udiff($original_occurrences, $new_occurrences, '_eventorganiser_compare_dates'); $updated = array_intersect_key($new_occurrences, $original_occurrences); $updated_2 = array_intersect_key($original_occurrences, $new_occurrences); $updated = $this->array_map_assoc('eo_format_datetime', $updated, array_fill(0, count($updated), 'Y-m-d H:i:s')); $updated_2 = $this->array_map_assoc('eo_format_datetime', $updated_2, array_fill(0, count($updated_2), 'Y-m-d H:i:s')); //Check added/removed/update dates are as expected: all dates should just be updated $this->assertEquals(array(), $added); $this->assertEquals(array(), $removed); $this->assertEquals(array('2013-10-19 14:30:00', '2013-10-26 14:30:00', '2013-11-02 14:30:00', '2013-11-09 14:30:00'), array_values($updated)); //Now check that dates have been updated as expected (i.e. there have been no 'swapping' of IDs). //First: Sanity check, make sure IDs agree. $diff = array_diff_key($updated, $updated_2); $this->assertTrue(empty($diff) && count($updated) == count($updated_2)); ksort($updated); ksort($updated_2); $updated_map = array_combine($updated_2, $updated); //Now check that the dates have been updated as expected: original => new $this->assertEquals(array('2013-10-19 15:30:00' => '2013-10-19 14:30:00', '2013-10-26 15:30:00' => '2013-10-26 14:30:00', '2013-11-02 15:30:00' => '2013-11-02 14:30:00', '2013-11-09 15:30:00' => '2013-11-09 14:30:00'), $updated_map); }
/** * @param Unit $unit * @return $this|void */ public function removeUnit(Unit $unit) { $this->units = array_udiff($this->units, [$unit], function ($a, $b) { return $a === $b ? 0 : 1; }); return $this; }
/** *@Security("has_role('ROLE_USER')") *@Route("/programme/booking/{projection_id}", name ="booking") */ public function bookingAction(Request $request, $projection_id) { $em = $this->getDoctrine()->getManager(); //retrieve a projection from the database $projection = $em->getRepository('AppBundle:Projection')->find($projection_id); //all seats available for the projection $allSeats = $projection->getHall()->getSeats()->toArray(); //get reserved tickets for the projection $reservedTickets = $em->createQueryBuilder()->select('t')->from('AppBundle:Ticket', 't')->where('t.projection = ?1')->setParameter(1, $projection)->getQuery()->getResult(); //get reserved seats for the projection $reservedSeats = array(); foreach ($reservedTickets as $ticket) { $reservedSeats[] = $ticket->getSeat(); } // get free seats $freeSeats = array_udiff($allSeats, $reservedSeats, function ($hallSeat, $reservedSeat) { return $hallSeat->getId() - $reservedSeat->getId(); }); //a ticket which will be stored $ticket = new Ticket(); $form = $this->createForm(new BookProjectionForm($freeSeats), $ticket); $form->handleRequest($request); if ($form->isValid()) { //set the other fields $ticket->setUser($this->getUser())->setProjection($projection)->setTicketPrice($ticket->getPriceCategory()->getCategoryPrice())->setBookingDate(new \DateTime('now')); $em->persist($ticket); $em->flush(); // redirect to reservations page return $this->redirectToRoute('reservations'); } return $this->render('User/booking.html.twig', array('projection' => $projection, 'form' => $form->createView())); }
/** * Parses the search text to a query wich will search in each of the specified fields. * If operators AND, OR or NOT are used in the text it is considered search text query and is passed as it is. * If it is a simple text - it is escaped and truncated. * * @param string $searchText * @param array $fields * @param string $truncate */ public function parse($searchText, $truncate, $fields) { $nonTokenizedFields = array_uintersect($fields, self::$_nonTokenizedFields, array('OpenSKOS_Solr_Queryparser_Editor_ParseSearchText', 'compareMultiLangFields')); $fields = array_udiff($fields, self::$_nonTokenizedFields, array('OpenSKOS_Solr_Queryparser_Editor_ParseSearchText', 'compareMultiLangFields')); $simpleFieldsQuery = ''; $normalFieldsQuery = ''; if ($this->_isSearchTextQuery($searchText)) { $simpleFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchText . ')', $nonTokenizedFields); $normalFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchText . ')', $fields); } else { $trimedSearchText = trim($searchText); if (empty($trimedSearchText)) { $searchText = '*'; } $searchTextForNonTokenized = $this->_escapeSpecialChars($searchText); $simpleFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchTextForNonTokenized . ')', $nonTokenizedFields); $searchTextForTokenized = $this->_replaceTokenizeDelimiterChars($searchText); $normalFieldsQuery = $this->_buildQueryForSearchTextInFields('(' . $searchTextForTokenized . ')', $fields); } if ($simpleFieldsQuery != '' && $normalFieldsQuery != '') { return $simpleFieldsQuery . ' OR ' . $normalFieldsQuery; } else { return $simpleFieldsQuery . $normalFieldsQuery; } }
/** * */ public function index() { if ($this->session->userdata('logged_in')) { $thisUserID = $this->session->userdata('logged_in')['userID']; $courses = $this->Model_course->GetAllCourses(); $userCourses = $this->Model_usercourse->GetUserCourses($thisUserID); if ($courses) { $coursesAvail = array_udiff($courses, $userCourses, function ($courses, $userCourses) { return $courses->courseID - $userCourses->courseID; }); $data['courses'] = $courses; $data['coursesAvail'] = $coursesAvail; $data['count_coursesAvail'] = count($coursesAvail); } //List of courses the user is enrolled in if ($userCourses) { $data['userCourses'] = $userCourses; } //Count of courses the user is enrolled in $count = $this->Model_usercourse->GetNumberOfUserCourses(); if ($count) { $data['NoOfUserCourses'] = $count; } //Count of the total nunmber of courses $count = $this->Model_course->GetNumberOfCourses(); if ($count) { $data['NoOfCourses'] = $count; } //Count of the number of groups in the system $count = $this->Model_group->GetNumberofGroups(); if ($count) { $data['NoOfGroups'] = $count; } //List of groups in the system $groups = $this->Model_group->GetGroups(); if ($groups) { $data['userGroups'] = $groups; } $session_data = $this->session->userdata('logged_in'); $data['userID'] = $session_data['userID']; $data['fname'] = $session_data['fname']; $data['lname'] = $session_data['lname']; $data['usertype'] = $session_data['usertype']; $data['email'] = $session_data['email']; $data['menu'] = "home"; //List of courses completed by a user, null if there is none $query = $this->Model_usercourse->GetCompletedUserCourse($data['userID']); if ($query) { $data['completedUserCourses'] = $query; } else { $data['completedUserCourses'] = null; } $this->load->view('header', $data); $this->load->view('view_dashboard'); } else { //If no session, redirect to login page redirect('login', 'refresh'); } }
function removeUnit(Unit $unit) { // >= php 5.3 //$this->units = array_udiff( $this->units, array( $unit ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->units = array_udiff($this->units, array($unit), create_function('$a,$b', 'return ($a === $b)?0:1;')); }
public function execute(array $collection) { $comparer = $this->getComparer(); $diffed = array_udiff($this->additionalCollection, $collection, function ($a, $b) use($comparer) { return $comparer->equals($a, $b); }); return array_merge($collection, $diffed); }
function detach(Observer $observer) { // >= php 5.3 //$this->observers = array_udiff( $this->observers, array( $observer ), // function( $a, $b ) { return ($a === $b)?0:1; } ); // < php 5.3 $this->observers = array_udiff($this->observers, array($observer), create_function('$a,$b', 'return ($a === $b)?0:1;')); }
/** * {@inheritdoc} */ public function removePermission(PermissionInterface $permission) { if ($this->hasPermission($permission)) { $this->permissions = array_udiff($this->permissions, [$permission], function ($objectA, $objectB) { return $objectA->getHash() - $objectB->getHash(); }); } return $this; }
public static function diff(array $a, array $b) { return array_udiff($a, $b, function ($a, $b) { if (gettype($a) !== gettype($b)) { return -1; } return $a === $b ? 0 : 1; }); }
private function diffArrays(array $from, array $against) { return array_udiff($from, $against, function ($fromElement, $againstElement) { if (is_object($fromElement) && is_object($againstElement)) { return strcmp(spl_object_hash($fromElement), spl_object_hash($againstElement)); } return $fromElement !== $againstElement; }); }
/** * Remove any files added during the test * @after */ public function restoreFileList() { $newFiles = array_udiff($this->getService('filesystem')->listContents(self::FILESYSTEM . '://'), $this->oldFiles, function (HandlerInterface $file1, HandlerInterface $file2) { return strcmp($file2->getPath(), $file2->getPath()); }); /** @var HandlerInterface $file */ foreach ($newFiles as $file) { $file->delete(); } }
/** * {@inheritdoc} */ public function synchronize() { $persistedThemes = $this->themeRepository->findAll(); $loadedThemes = $this->themeLoader->load(); $removedThemes = $this->removeAbandonedThemes($persistedThemes, $loadedThemes); $existingThemes = array_udiff($persistedThemes, $removedThemes, function (ThemeInterface $firstTheme, ThemeInterface $secondTheme) { return (int) ($firstTheme->getName() === $secondTheme->getName()); }); $this->updateThemes($existingThemes, $loadedThemes); }
/** * {@inheritDoc} */ public function hydrate($value) { $collection = $this->getCollectionFromObjectByReference(); $collectionArray = $collection->toArray(); $toAdd = array_udiff($value, $collectionArray, array($this, 'compareObjects')); foreach ($toAdd as $element) { $collection->add($element); } return $collection; }
/** * Возвращает элементы отсутствующие в новом массиве и присутствующие в оригинальном * @param Array $newArray новые данные * @param Array $originArray текущие данные * @return Array */ public static function itemsForRemove(array $newArray, array $originArray) { return array_udiff($originArray, $newArray, function ($a, $b) { if ($a['id'] < $b['id']) { return -1; } elseif ($a['id'] > $b['id']) { return 1; } else { return 0; } }); }
/** * {@inheritDoc} */ public function hydrate($value) { // AllowRemove strategy need "adder" $adder = 'add' . ucfirst($this->collectionName); if (!method_exists($this->object, $adder)) { throw new LogicException(sprintf('AllowRemove strategy for DoctrineModule hydrator requires %s to be defined in %s entity domain code, but it seems to be missing', $adder, get_class($this->object))); } $collection = $this->getCollectionFromObjectByValue()->toArray(); $toAdd = new ArrayCollection(array_udiff($value, $collection, array($this, 'compareObjects'))); $this->object->{$adder}($toAdd); return $collection; }
public function execute() { $realTable = $this->getRealTables(); $metadataTable = $this->getMetadataTables(); $createTables = array_diff_key($metadataTable, $realTable); $changedTables = array_diff_key(array_udiff($metadataTable, $realTable, function ($table1, $table2) { if ($table1 === $table2) { return 0; } return -1; }), $createTables); var_dump($createTables); echo current($this->createTables($createTables)); }
public static function addVendorItem($id) { self::check_logged_in(); $item = new Item(array('id' => $id)); $options = array(); $allvendoritems = VendorItem::all($options); $curvendoritems = $item->getVendorItems(); function compare_vendoritems($obj_a, $obj_b) { return $obj_a->id - $obj_b->id; } $vendoritems = array_udiff($allvendoritems, $curvendoritems, 'compare_vendoritems'); View::make('item/vendoritem/add.html', array('item_id' => $id, 'vendoritems' => $vendoritems)); }
public function register(Application $app) { $app['memcached'] = $app->share(function () use($app) { $memcached = new \Memcached($app['memcached.identifier']); $memcached->setOption(\Memcached::OPT_COMPRESSION, false); $memcached->setOption(\Memcached::OPT_PREFIX_KEY, $app['memcached.prefix']); $serversToAdd = array_udiff($app['memcached.servers'], $memcached->getServerList(), function ($a, $b) { return $a['host'] == $b['host'] && $a['port'] == $b['port'] ? 0 : 1; }); if (count($serversToAdd)) { $memcached->addServers($serversToAdd); } return $memcached; }); }
/** * Verify role access * * @param mixed $role The role name to check * @param \Warden\Model_User $user The user to check against, if no user is given (null) * it will check against the currently logged in user * * @return bool */ public function has_access($role, Model_User $user = null) { $status = !!$user; if (!empty($role) && $status) { $role = is_array($role) ? $role : array($role); $diff = array_udiff($role, $user->roles, function ($r, $ur) { // check for a role object $r = is_object($r) ? $r->name : $r; // compare each given role against the user's roles return $r != $ur->name; }); // empty = true $status = empty($diff); } return $status; }
protected function _extractKeywords($str, $minWordLen = 3, $minWordOccurrences = 2, $asArray = false, $maxWords = 8, $restrict = false) { $stringHelper = $this->_commonHelper()->getStrings(); $str = str_replace(array("?", "!", ";", "(", ")", ":", "[", "]"), " ", $str); $str = str_replace(array("\n", "\r", " "), " ", $str); $str = $stringHelper->strtolower($str); $str = $stringHelper->ereg_replace('[^\\w0-9 ]', ' ', $str); $str = trim($stringHelper->ereg_replace('\\s+', ' ', $str)); $words = explode(' ', $str); // Only compare to common words if $restrict is set to false // Tags are returned based on any word in text // If we don't restrict tag usage, we'll remove common words from array if ($restrict == false) { $commonWords = array('i', 'a', 'about', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'com', 'de', 'en', 'for', 'from', 'how', 'in', 'is', 'it', 'la', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'with', 'und', 'the', 'www', 'и', 'мне', 'я', 'мы', 'они', 'в', 'на', 'по', 'под', 'к', 'от', 'это', 'как', 'что', 'когда', 'зачем', 'он', 'оно'); $words = array_udiff($words, $commonWords, 'strcasecmp'); } // Restrict Keywords based on values in the $allowedWords array // Use if you want to limit available tags // if ($restrict == true) { // $allowedWords = array('engine', 'boeing', 'electrical', 'pneumatic', 'ice'); // $words = array_uintersect($words, $allowedWords, 'strcasecmp'); // } $keywords = array(); while (($c_word = array_shift($words)) !== null) { if ($stringHelper->strlen($c_word) < $minWordLen) { continue; } $c_word = $stringHelper->strtolower($c_word); if (array_key_exists($c_word, $keywords)) { $keywords[$c_word][1]++; } else { $keywords[$c_word] = array($c_word, 1); } } usort($keywords, array(&$this, '_keywordCountSort')); $final_keywords = array(); foreach ($keywords as $keyword_det) { if ($keyword_det[1] < $minWordOccurrences) { break; } array_push($final_keywords, $keyword_det[0]); } $final_keywords = array_slice($final_keywords, 0, $maxWords); return $asArray ? $final_keywords : implode(', ', $final_keywords); }
public function editAction() { $team = Scalr_Account_Team::init(); $team->loadById($this->getParam('teamId')); if ($team->accountId == $this->user->getAccountId() && ($this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER || $this->user->isTeamOwner($team->id))) { $users = $this->db->GetAll("SELECT id, email, fullname FROM account_users WHERE type = ? AND status = ? AND account_id = ?", array(Scalr_Account_User::TYPE_TEAM_USER, Scalr_Account_User::STATUS_ACTIVE, $this->user->getAccountId())); $teamUsers = $team->getUsers(); foreach ($teamUsers as $key => $user) { $teamUsers[$key]['groups'] = $team->getUserGroups($user['id']); } $envs = $this->db->GetAll("SELECT id, name FROM client_environments WHERE client_id = ?", array($this->user->getAccountId())); $users = array_udiff($users, $teamUsers, array($this, 'diffUsersCmp')); sort($users); $this->response->page('ui/account/teams/create.js', array('users' => $users, 'envs' => $envs, 'teamManage' => $this->user->getType() == Scalr_Account_User::TYPE_ACCOUNT_OWNER ? true : false, 'permissionsManage' => $this->user->getAccount()->isFeatureEnabled(Scalr_Limits::FEATURE_USERS_PERMISSIONS), 'teamCreate' => false, 'team' => array('id' => $team->id, 'name' => $team->name, 'envs' => $team->getEnvironments(), 'users' => $teamUsers, 'groups' => $team->getGroups()))); } else { throw new Scalr_Exception_InsufficientPermissions(); } }
/** * {@inheritdoc} */ public function getResult() { $result = $this->getRoot(); if ($result) { $meta = null; $included = null; $links = null; // strip out included part, since it does not belong to the primary resource data if (isset($result['included'])) { $included = $result['included']; unset($result['included']); } if (isset($result['meta'])) { $meta = $result['meta']; unset($result['meta']); } if (isset($result['links'])) { $links = $result['links']; unset($result['links']); } // filter out duplicate primary resource objects that are in `included` $included = array_udiff((array) $included, $result, function ($a, $b) { return strcmp($a['type'] . $a['id'], $b['type'] . $b['id']); }); $root = array(); if ($this->showVersionInfo) { $root['jsonapi'] = array('version' => '1.0'); } if ($meta) { $root['meta'] = $meta; } if ($links) { $root['links'] = $links; } $root['data'] = array_values($result); if ($included) { $root['included'] = array_values($included); } $this->setRoot($root); } return parent::getResult(); }
public function vote(TokenInterface $token, $object, array $attributes) { if ($object !== 'context') { return VoterInterface::ACCESS_DENIED; } $user = $token->getUser(); $context = $this->entityManager->getRepository('BigfootContextBundle:Context')->findOneByEntityIdEntityClass($user->getId(), get_class($user)); if (!$this->supportsClass($context)) { return VoterInterface::ACCESS_DENIED; } $allowedContexts = $context->getContextValues(); $values = explode('.', $attributes[0]); $testedContexts = array($values[0] => array($values[1])); if ($allowedContexts) { $contextsIntersect = array_udiff($testedContexts, $allowedContexts, array($this, 'intersectContexts')); if (count($contextsIntersect)) { return VoterInterface::ACCESS_GRANTED; } } return VoterInterface::ACCESS_ABSTAIN; }
/** * Get components to be added. * * @return array */ protected function getComponentsToRegister() { static $components = null; if (!is_null($components)) { return $components; } $mode = Settings::get('mode', 'all'); $componentsTmp = []; if ($mode == 'allBut') { $componentsTmp = array_udiff($this->componentList, $this->getSettingsList(), 'strcasecmp'); } elseif ($mode == 'only') { $componentsTmp = array_uintersect($this->componentList, $this->getSettingsList(), 'strcasecmp'); } else { $componentsTmp = $this->componentList; } $components = []; foreach ($componentsTmp as $component) { $components['Krisawzm\\Embed\\Components\\' . $component] = $component . 'Embed'; } return $components; }