filter() public method

{@inheritDoc}
public filter ( Closure $p )
$p Closure
Example #1
2
 /**
  * @see Command
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var \Doctrine\ORM\EntityManager $em */
     $em = $this->getContainer()->get('doctrine.orm.default_entity_manager');
     $campaignRepo = $em->getRepository('VifeedCampaignBundle:Campaign');
     $campaigns = new ArrayCollection($campaignRepo->getActiveCampaigns());
     $hashes = [];
     foreach ($campaigns as $campaign) {
         /** @var Campaign $campaign */
         $hashes[] = $campaign->getHash();
     }
     $hashes = array_unique($hashes);
     $client = new \Google_Client();
     $client->setDeveloperKey($this->getContainer()->getParameter('google.api.key'));
     $youtube = new \Google_Service_YouTube($client);
     /* Опытным путём выяснилось, что ютуб принимает не больше 50 хешей за раз */
     $hash = 'TjvivnmWcn4';
     $request = $youtube->videos->listVideos('status', ['id' => $hash]);
     foreach ($request as $video) {
         /** @var \Google_Service_YouTube_Video $video */
         /** @var \Google_Service_YouTube_VideoStatistics $stats */
         $stats = $video->getStatistics();
         $hash = $video->getId();
         /* не исключается ситуация, что может быть несколько кампаний с одинаковым hash */
         $filteredCampaigns = $campaigns->filter(function (Campaign $campaign) use($hash) {
             return $campaign->getHash() == $hash;
         });
         foreach ($filteredCampaigns as $campaign) {
             $campaign->setSocialData('youtubeViewCount', $stats->getViewCount())->setSocialData('youtubeCommentCount', $stats->getCommentCount())->setSocialData('youtubeFavoriteCount', $stats->getFavoriteCount())->setSocialData('youtubeLikeCount', $stats->getLikeCount())->setSocialData('youtubeDislikeCount', $stats->getDislikeCount());
             $em->persist($campaign);
         }
     }
     $em->flush();
 }
Example #2
0
 /**
  * @param TaskDescription $description
  * @return mixed
  * @throws DomainException
  */
 public function getTaskByDescription(TaskDescription $description)
 {
     $tasksFound = $this->tasks->filter(function (Task $task) use($description) {
         return $description->equals($task->getDescription());
     });
     if ($tasksFound->isEmpty()) {
         throw new DomainException('Task ' . $description . ' does not exist in working day');
     }
     return $tasksFound->first();
 }
 /**
  * Return the last oxford comma eligible word
  * in the sentence
  *
  * @return ArrayCollection|Word[]
  */
 public function getOxfordItems()
 {
     $words = new ArrayCollection();
     $conjunctions = $this->words->filter(function (Word $word) {
         return $word instanceof Conjunction;
     });
     $conjunctions->map(function ($word) use($words) {
         if ($this->hasOxfordable($word)) {
             $index = $this->words->indexOf($word) - 1;
             $words->add($this->words->get($index));
         }
     });
     return $words;
 }
Example #4
0
 /**
  * @inheritdoc
  */
 public function remove(AmountInterface $amount)
 {
     if (!$this->has($amount)) {
         return $this;
     }
     $a = $this->find($amount);
     if ($a->getBase() > $amount->getBase()) {
         $a->removeBase($amount->getBase());
     } else {
         $this->amounts = $this->amounts->filter(function (AmountInterface $a) use($amount) {
             return !$a->equals($amount);
         });
     }
     return $this;
 }
 /**
  * configureSanbox method with not cached scenario
  */
 public function testConfigureSandboxNotCached()
 {
     $entityClass = 'Oro\\Bundle\\UserBundle\\Entity\\User';
     $configIdMock = $this->getMockForAbstractClass('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\ConfigIdInterface');
     $configIdMock->expects($this->once())->method('getClassName')->will($this->returnValue($entityClass));
     $configuredData = array($entityClass => array('getsomecode'));
     $this->cache->expects($this->once())->method('fetch')->with($this->cacheKey)->will($this->returnValue(false));
     $this->cache->expects($this->once())->method('save')->with($this->cacheKey, serialize($configuredData));
     $configurableEntities = array($configIdMock);
     $this->configProvider->expects($this->once())->method('getIds')->will($this->returnValue($configurableEntities));
     $fieldsCollection = new ArrayCollection();
     $this->configProvider->expects($this->once())->method('filter')->will($this->returnCallback(function ($callback) use($fieldsCollection) {
         return $fieldsCollection->filter($callback);
     }));
     $field1Id = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\FieldConfigId')->disableOriginalConstructor()->getMock();
     $field1Id->expects($this->once())->method('getFieldName')->will($this->returnValue('someCode'));
     $field1 = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface')->disableOriginalConstructor()->getMockForAbstractClass();
     $field2 = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface')->disableOriginalConstructor()->getMockForAbstractClass();
     $field1->expects($this->once())->method('is')->with('available_in_template')->will($this->returnValue(true));
     $field1->expects($this->once())->method('getId')->will($this->returnValue($field1Id));
     $field2->expects($this->once())->method('is')->with('available_in_template')->will($this->returnValue(false));
     $fieldsCollection->add($field1);
     $fieldsCollection->add($field2);
     $this->getRendererInstance();
 }
 /**
  * @param StaticSegment $staticSegment
  * @param string $segmentStateFilter
  * @param string $method
  * @param string $itemState
  * @param bool $deleteMember
  * @return array
  */
 public function handleMembersUpdate(StaticSegment $staticSegment, $segmentStateFilter, $method, $itemState, $deleteMember = false)
 {
     $itemsToWrite = [];
     $items = $staticSegment->getSegmentMembers()->filter(function (StaticSegmentMember $segmentMember) use($segmentStateFilter) {
         return $segmentMember->getState() === $segmentStateFilter;
     })->toArray();
     if (empty($items)) {
         return [];
     }
     $emails = array_map(function (StaticSegmentMember $segmentMember) {
         return $segmentMember->getMember()->getEmail();
     }, $items);
     $response = $this->transport->{$method}(['id' => $staticSegment->getSubscribersList()->getOriginId(), 'seg_id' => (int) $staticSegment->getOriginId(), 'batch' => array_map(function ($email) {
         return ['email' => $email];
     }, $emails), 'delete_member' => $deleteMember]);
     $this->handleResponse($response, function ($response, LoggerInterface $logger) use($staticSegment) {
         $logger->info(sprintf('Segment #%s [origin_id=%s] Members: [%s] add, [%s] error', $staticSegment->getId(), $staticSegment->getOriginId(), $response['success_count'], $response['error_count']));
     });
     $emailsWithErrors = $this->getArrayData($response, 'errors');
     /** @var StaticSegmentMember[]|ArrayCollection $items */
     $items = new ArrayCollection($items);
     $items->filter(function (StaticSegmentMember $segmentMember) use($emailsWithErrors) {
         return !in_array($segmentMember->getMember()->getEmail(), $emailsWithErrors, true);
     });
     foreach ($items as $item) {
         $item->setState($itemState);
         $this->logger->debug(sprintf('Member with id "%s" and email "%s" got "%s" state', $item->getMember()->getOriginId(), $item->getMember()->getEmail(), $itemState));
         $itemsToWrite[] = $item;
     }
     return $itemsToWrite;
 }
Example #7
0
 /**
  * @param string $service
  * @return Hash|false
  */
 public function getTokenForService($service)
 {
     $token = $this->tokens->filter(function (Token $token) use($service) {
         return $token->getService() == $service;
     })->first();
     return $token ? $token->getToken() : false;
 }
Example #8
0
 /**
  * @return ArrayCollection
  */
 public function getEditors()
 {
     $editors = $this->users->filter(function (User $user) {
         return $user->isEditor();
     });
     return $editors;
 }
 /**
  * @param array $filters
  * @param int   $limit
  * @param int   $offset
  *
  * @return array
  */
 public function findBy(array $filters, $limit = null, $offset = 0)
 {
     $result = $this->result->filter(function ($item) use($filters) {
         // filter all non valid conditions
         foreach ($filters as $key => $value) {
             if (!array_key_exists($key, $item) || $item[$key] != $value) {
                 return false;
             }
         }
         return true;
     });
     if (empty($limit)) {
         return $result->toArray();
     }
     return $result->slice($offset, $limit);
 }
Example #10
0
 /**
  * @param Permission|string $permission
  *
  * @return Permission|null
  */
 protected function getPermission($permission)
 {
     $name = $permission instanceof Permission ? $permission->getName() : $permission;
     return $this->permissions->filter(function (Permission $current) use($name) {
         return $current->getName() == $name;
     })->first();
 }
Example #11
0
 /**
  * @return Group
  */
 public function getPreliminaryGroup()
 {
     $gos = $this->grouporder->filter(function (GroupOrder $grouporder) {
         return $grouporder->getGroup()->getClassification() == Group::$PRE;
     });
     return $gos->count() == 1 ? $gos->first()->getGroup() : null;
 }
 public function filter(Closure $p)
 {
     if (null === $this->entries) {
         $this->__load___();
     }
     return $this->entries->filter($p);
 }
 /**
  * @param SubscribersList $subscribersList
  * @param array|ArrayCollection $items
  * @return array
  */
 protected function batchSubscribe(SubscribersList $subscribersList, array $items)
 {
     $itemsToWrite = [];
     $emails = array_map(function (Member $member) {
         return ['email' => ['email' => $member->getEmail()], 'merge_vars' => $member->getMergeVarValues()];
     }, $items);
     $response = $this->transport->batchSubscribe(['id' => $subscribersList->getOriginId(), 'batch' => $emails, 'double_optin' => false, 'update_existing' => true]);
     $this->handleResponse($response, function ($response, LoggerInterface $logger) use($subscribersList) {
         $logger->info(sprintf('List #%s [origin_id=%s]: [%s] add, [%s] update, [%s] error', $subscribersList->getId(), $subscribersList->getOriginId(), $response['add_count'], $response['update_count'], $response['error_count']));
     });
     $emailsAdded = $this->getArrayData($response, 'adds');
     $emailsUpdated = $this->getArrayData($response, 'updates');
     $items = new ArrayCollection($items);
     foreach (array_merge($emailsAdded, $emailsUpdated) as $emailData) {
         /** @var Member $member */
         $member = $items->filter(function (Member $member) use($emailData) {
             return $member->getEmail() === $emailData['email'];
         })->first();
         if ($member) {
             $member->setEuid($emailData['euid'])->setLeid($emailData['leid'])->setStatus(Member::STATUS_SUBSCRIBED);
             $itemsToWrite[] = $member;
             $this->logger->debug(sprintf('Member with data "%s" successfully processed', json_encode($emailData)));
         } else {
             $this->logger->warning(sprintf('A member with "%s" email was not found', $emailData['email']));
         }
     }
     return $itemsToWrite;
 }
 /**
  * @internal
  * @param string $caseFilter
  * @return ArrayCollection
  */
 protected function filterCases($caseFilter)
 {
     $this->initCases();
     return $this->cases->filter(function ($item) use($caseFilter) {
         return $item instanceof $caseFilter;
     });
 }
 /**
  * @dataProvider fieldsDataProvider
  * @param $entityIsUser
  */
 public function testGetTemplateVariables($entityIsUser)
 {
     $configId1Mock = $this->getMockForAbstractClass('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\ConfigIdInterface');
     $configId1Mock->expects($this->once())->method('getClassName')->will($this->returnValue(get_class($this->user)));
     $configId2Mock = $this->getMockForAbstractClass('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\ConfigIdInterface');
     $configId2Mock->expects($this->once())->method('getClassName')->will($this->returnValue(self::TEST_ENTITY_NAME));
     $configId3Mock = $this->getMockForAbstractClass('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\ConfigIdInterface');
     $configId3Mock->expects($this->once())->method('getClassName')->will($this->returnValue(self::TEST_NOT_NEEDED_ENTITY_NAME));
     $configurableEntities = array($configId1Mock, $configId2Mock, $configId3Mock);
     $this->configProvider->expects($this->once())->method('getIds')->will($this->returnValue($configurableEntities));
     $field1Id = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\FieldConfigId')->disableOriginalConstructor()->getMock();
     $field1Id->expects($this->any())->method('getFieldName')->will($this->returnValue('someCode'));
     $field1 = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface')->disableOriginalConstructor()->getMockForAbstractClass();
     $field2 = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigInterface')->disableOriginalConstructor()->getMockForAbstractClass();
     $field1->expects($this->any())->method('is')->with('available_in_template')->will($this->returnValue(true));
     $field1->expects($this->any())->method('getId')->will($this->returnValue($field1Id));
     $field2->expects($this->any())->method('is')->with('available_in_template')->will($this->returnValue(false));
     // fields for entity
     $fieldsCollection = new ArrayCollection();
     $this->configProvider->expects($this->at(1))->method('filter')->will($this->returnCallback(function ($callback) use($fieldsCollection) {
         return $fieldsCollection->filter($callback)->toArray();
     }));
     $fieldsCollection[] = $field1;
     $fieldsCollection[] = $field2;
     if (!$entityIsUser) {
         $field3Id = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\Id\\FieldConfigId')->disableOriginalConstructor()->getMock();
         $field3Id->expects($this->any())->method('getFieldName')->will($this->returnValue('someAnotherCode'));
         $field3 = clone $field1;
         $field3->expects($this->atLeastOnce())->method('is')->with('available_in_template')->will($this->returnValue(true));
         $field3->expects($this->atLeastOnce())->method('getId')->will($this->returnValue($field3Id));
         $this->configProvider->expects($this->at(2))->method('filter')->will($this->returnCallback(function ($callback) use($fieldsCollection, $field3) {
             $fieldsCollection[] = $field3;
             return $fieldsCollection->filter($callback)->toArray();
         }));
         $result = $this->provider->getTemplateVariables(self::TEST_ENTITY_NAME);
     } else {
         $result = $this->provider->getTemplateVariables(get_class($this->user));
     }
     $this->assertArrayHasKey('user', $result);
     $this->assertArrayHasKey('entity', $result);
     $this->assertInternalType('array', $result['user']);
     $this->assertInternalType('array', $result['entity']);
     if ($entityIsUser) {
         $this->assertEquals($result['user'], $result['entity']);
     }
 }
Example #16
0
 /**
  * Getter for fields without the Backend scope
  *
  * @return Doctrine\Common\Collections\ArrayCollection
  */
 public function getFieldsWithoutBackend()
 {
     return $this->fields->filter(function ($field) {
         if ($field->getFieldScope() == 'frontend') {
             return $field;
         }
     });
 }
Example #17
0
 /**
  * Gets a (previously set) query parameter of the query being constructed.
  *
  * @param mixed $key The key (index or name) of the bound parameter.
  *
  * @return Query\Parameter|null The value of the bound parameter.
  */
 public function getParameter($key)
 {
     $filteredParameters = $this->parameters->filter(function ($parameter) use($key) {
         // Must not be identical because of string to integer conversion
         return $key == $parameter->getName();
     });
     return count($filteredParameters) ? $filteredParameters->first() : null;
 }
Example #18
0
 /**
  * @param bool $includeOffline
  *
  * @return ArrayCollection
  */
 public function getNodeTranslations($includeOffline = false)
 {
     return $this->nodeTranslations->filter(function (NodeTranslation $entry) use($includeOffline) {
         if ($includeOffline || $entry->isOnline()) {
             return true;
         }
         return false;
     });
 }
 /**
  * Retrieves Attachment
  * @param $attachmentId
  * @return Attachment
  */
 public function getAttachment($attachmentId)
 {
     $attachment = $this->attachments->filter(function ($elm) use($attachmentId) {
         /**
          * @var $elm Attachment
          */
         return $elm->getId() == $attachmentId;
     })->first();
     return $attachment;
 }
Example #20
0
 /**
  * Remove person
  *
  * @param  Person|EmbeddedPerson $person
  * @return boolean               TRUE if this embedded person contained the specified person, FLASE otherwise.
  */
 public function removePerson($person)
 {
     $embeddedPerson = $this->getEmbeddedPerson($person);
     $aux = $this->people->filter(function ($i) use($embeddedPerson) {
         return $i->getId() !== $embeddedPerson->getId();
     });
     $hasRemoved = count($aux) !== count($this->people);
     $this->people = $aux;
     return $hasRemoved;
 }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function getActivatedAt()
 {
     $completed = $this->activations->filter(function (Activation $activation) {
         return $activation->isCompleted();
     });
     if ($completed->isEmpty()) {
         return null;
     }
     return $completed->first()->getCompletedAt();
 }
Example #22
0
 /**
  * Apply menu filters to Menu.
  *
  * @param ArrayCollection $menuNodes Menu nodes
  * @param string          $menuCode  Menu code
  * @param string          $stage     Stage
  *
  * @return ArrayCollection Filtered collection
  */
 private function applyFiltersToMenuNodes(ArrayCollection $menuNodes, $menuCode, $stage)
 {
     return $menuNodes->filter(function (NodeInterface $menuNode) use($menuCode, $stage) {
         if ($this->applyFiltersToMenuNode($menuNode, $menuCode, $stage)) {
             $menuNode->setSubnodes($this->applyFiltersToMenuNodes($menuNode->getSubnodes(), $menuCode, $stage));
             return true;
         }
         return false;
     });
 }
Example #23
0
 /**
  * Get email recipients
  *
  * @param null|string $recipientType null to get all recipients,
  *                                   or 'to', 'cc' or 'bcc' if you need specific type of recipients
  * @return EmailRecipient[]
  */
 public function getRecipients($recipientType = null)
 {
     if ($recipientType === null) {
         return $this->recipients;
     }
     return $this->recipients->filter(function ($recipient) use($recipientType) {
         /** @var EmailRecipient $recipient */
         return $recipient->getType() === $recipientType;
     });
 }
 /**
  * @param AttorneyAbstract $attorney
  * @return ArrayCollection
  */
 public function findAttorney(AttorneyAbstract $attorney)
 {
     $this->initAttorneys();
     return $this->attorneys->filter(function ($item) use($attorney) {
         if ('' !== $attorney->getDobString()) {
             return $item->getTitle() === $attorney->getTitle() && $item->getFirstname() === $attorney->getFirstname() && $item->getMiddleName() === $attorney->getMiddlename() && $item->getSurname() === $attorney->getSurname() && $item->getDobString() === $attorney->getDobString();
         } else {
             return $item->getTitle() === $attorney->getTitle() && $item->getFirstname() === $attorney->getFirstname() && $item->getMiddleName() === $attorney->getMiddlename() && $item->getSurname() === $attorney->getSurname();
         }
     });
 }
 /**
  * @param string $siteId
  *
  * @return Collection
  */
 public function getSubFoldersBySiteId($siteId)
 {
     return $this->subFolders->filter(function (FolderInterface $folder) use($siteId) {
         foreach ($folder->getSites() as $folderSite) {
             if ($folderSite['siteId'] === $siteId) {
                 return true;
             }
         }
         return count($folder->getSites()) === 0;
     });
 }
 /**
  * Test if a collection of contracts are valid
  *
  * Valid contracts are <b>signed</b>, <b>not cancelled</b>, and
  * <b>co-signed</b> if necessary.
  *
  * @param  ArrayCollection $signatures
  * @return bool
  */
 public static function areValid(ArrayCollection $signatures)
 {
     $isActiveFilter = self::createIsActiveFilter();
     $partitioned = $signatures->filter($isActiveFilter)->partition(function ($key, $signature) {
         // Signature does not require a co-signature
         if (!$signature->requires_cosigned) {
             return true;
         }
         return $signature->is_cosigned;
     });
     return count($partitioned[0]) > 0;
 }
 /**
  * @dataProvider newEntityFieldsProvider
  * @param ArrayCollection $fieldsCollection
  * @param $shouldClearCache
  */
 public function testNewEntityConfig(ArrayCollection $fieldsCollection, $shouldClearCache)
 {
     $cmMock = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Config\\ConfigManager')->disableOriginalConstructor()->getMock();
     $cpMock = $this->getMockBuilder('Oro\\Bundle\\EntityConfigBundle\\Provider\\ConfigProvider')->disableOriginalConstructor()->getMock();
     $cpMock->expects($this->once())->method('filter')->will($this->returnCallback(function ($callback) use($fieldsCollection) {
         return $fieldsCollection->filter($callback);
     }));
     $cmMock->expects($this->once())->method('getProvider')->with('email')->will($this->returnValue($cpMock));
     $event = new EntityConfigEvent('Test\\Class', $cmMock);
     $this->cache->expects($this->exactly((int) $shouldClearCache))->method('delete');
     $this->subscriber->newEntityConfig($event);
 }
Example #28
0
 /**
  * Get media.
  *
  * @param bool $includeDeleted
  *
  * @return ArrayCollection
  */
 public function getMedia($includeDeleted = false)
 {
     if ($includeDeleted) {
         return $this->media;
     }
     return $this->media->filter(function (Media $entry) {
         if ($entry->isDeleted()) {
             return false;
         }
         return true;
     });
 }
 /**
  * Get child folders
  *
  * @param bool $includeDeleted
  *
  * @return ArrayCollection
  */
 public function getChildren($includeDeleted = false)
 {
     if ($includeDeleted) {
         return $this->children;
     }
     return $this->children->filter(function (Folder $entry) {
         if ($entry->isDeleted()) {
             return false;
         }
         return true;
     });
 }
Example #30
0
 /**
  * @param string $type
  *
  * @return \Doctrine\Common\Collections\Collection
  * @throws \Exception
  */
 private function getFieldMappingsOfType($type = self::FIELD_TYPE_COMMON)
 {
     if ($this->fieldMappings === NULL) {
         throw new \Exception("Field mapping needs to be set");
     }
     return $this->fieldMappings->filter(function ($entry) use($type) {
         if ($type === self::FIELD_TYPE_COMMON && !$entry instanceof SearchAssociationFieldMapping || $type === self::FIELD_TYPE_ASSOCIATION && $entry instanceof SearchAssociationFieldMapping) {
             return $entry;
         }
         return false;
     });
 }