@param Campaign $campaign

@return $this
11293
public function setCampaign(Campaign $campaign = null)
    {
        if ($campaign) {
            $this->campaign   = $campaign;
            $this->campaignId = $campaign->getId();
        }

        return $this;
    }
772035
public function logout($campaign_id = NULL) {
    $response = new AjaxResponse();

    // Logout member - clear Campaign ID from SESSION.
    MemberCampaign::logout($campaign_id);

    $logoutTitle = $this->t('Thank you!');
    $logoutMessage = $this->t('You were successfully logged out!');

    $response->addCommand(new OpenModalDialogCommand($logoutTitle, $logoutMessage, ['width' => 800]));

    // Close dialog and redirect ot Campaign main page.
    $response->addCommand(new InvokeCommand('#drupal-modal', 'closeDialog', ['<campaign-front>']));

    return $response;
  }
894901
private static function createCampaign(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        Budget $budget
    ) {
        $campaignService = $adWordsServices->get($session, CampaignService::class);

        // Create campaign with some properties set.
        $campaign = new Campaign();
        $campaign->setName('Interplanetary Cruise #' . uniqid());
        $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

        // Recommendation: Set the campaign to PAUSED when creating it to prevent
        // the ads from immediately serving. Set to ENABLED once you've added
        // targeting and the ads are ready to serve.
        $campaign->setStatus(CampaignStatus::PAUSED);

        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();
        $biddingStrategyConfiguration->setBiddingStrategyType(
            BiddingStrategyType::MANUAL_CPC
        );
        $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

        // Only the budgetId should be sent, all other fields will be ignored by
        // CampaignService.
        $campaignBudget = new Budget();
        $campaignBudget->setBudgetId($budget->getBudgetId());
        $campaign->setBudget($campaignBudget);

        // Required: Set the campaign's Dynamic Search Ads settings.
        $dynamicSearchAdsSetting = new DynamicSearchAdsSetting();
        // Required: Set the domain name and language.
        $dynamicSearchAdsSetting->setDomainName('example.com');
        $dynamicSearchAdsSetting->setLanguageCode('en');

        // Set the campaign settings.
        $campaign->setSettings([$dynamicSearchAdsSetting]);

        // Optional: Set the start date.
        $campaign->setStartDate(date('Ymd', strtotime('+1 day')));
        // Optional: Set the end date.
        $campaign->setEndDate(date('Ymd', strtotime('+1 year')));

        // Create a campaign operation.
        $operation = new CampaignOperation();
        $operation->setOperand($campaign);
        $operation->setOperator(Operator::ADD);

        // Create the campaign on the server and print out some information.
        $result = $campaignService->mutate([$operation]);
        $campaign = $result->getValue()[0];
        printf(
            "Campaign with name '%s' and ID %d was added.\n",
            $campaign->getName(),
            $campaign->getId()
        );

        return $campaign;
    }
673231
public function create($campaign)
    {
        $this->getLogger()->debug('Getting Resource Owner');
        $this->ownerId = $this->getEntityProvider()->getMe()->getId();
        $this->campaign = $campaign;

        // Rewrite parameter mismatch
        $array = $this->toArray();
        $array['name'] = $array['campaign'];
        $this->getLogger()->info('Creating Campaign ' . $this->campaign);
        $response = $this->doPost($this->url, $array);

        $this->getLogger()->debug('Passing the response to Hydrate');
        return $this->hydrate($response);
    }
1258536
public function setStrategy($strategy)
    {
        foreach ($this->routes as $route)
            $route->setStrategy($strategy);
        return $this;
    }
867843
public function campaign()
    {
        if ($this->campaign === null) {
            $this->campaign = $this->generateCampaign();
        }

        return $this->campaign;
    }
737103
public function preUp(Schema $schema)
    {
        /** @var ManagerRegistry $doctrine */
        $doctrine = $this->container->get('doctrine');
        $em = $doctrine->getManager();

        // Get all Campaigns.
        $campaigns = $em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
            ->findAll();

        if($campaigns){
            try {
                $em->getConnection()->beginTransaction();

                /** @var Campaign $campaign */
                foreach($campaigns as $campaign){
                    /** @var Action $firstAction */
                    $firstAction = $em->getRepository('CampaignChain\CoreBundle\Entity\Campaign')
                        ->getFirstAction($campaign);
                    if($firstAction && $firstAction->getStartDate() < $campaign->getStartDate()){
                        $campaign->setStartDate($firstAction->getStartDate());
                        $em->persist($campaign);

                        $this->write(
                            'Changed start date of campaign "'.
                            $campaign->getName().'" ('.$campaign->getId().') '.
                            'to date "'.
                            $campaign->getStartDate()->format(\DateTime::ISO8601)
                        );
                    } else {
                        $this->write(
                            'No changes to campaign "'.
                            $campaign->getName().'" ('.$campaign->getId().').'
                        );
                    }
                }

                $em->flush();

                $em->getConnection()->commit();
            } catch (\Exception $e) {
                $em->getConnection()->rollback();
                $this->write($e->getMessage());
            }
        }
    }
1337363
public function add($candidate)
    {
        $hash = $this->objectHash($candidate);

        if (isset($this->candidateIds[$hash])) {
            return $this;
        }

        $function = $this->shouldCallReversed() ? 'array_unshift' : 'array_push';

        $function($this->candidates, $this->checkAndReturn($candidate));

        $this->candidateIds[$hash] = true;

        return $this;
    }
716921
public static function processCampaignWinnersBatch($campaign, $branches, $activities, $places, $isVisitsGoal, &$context) {
    if (empty($context['sandbox'])) {
      $context['sandbox']['progress'] = 0;

      $context['sandbox']['campaign'] = $campaign;
      $context['sandbox']['activities'] = $activities;
      $context['sandbox']['branches'] = array_keys($branches);
      $context['sandbox']['places'] = $places;

      $context['sandbox']['max'] = count($branches);
    }

    $branchId = $context['sandbox']['branches'][$context['sandbox']['progress']];
    $campaign = $context['sandbox']['campaign'];
    $activities = $context['sandbox']['activities'];
    $places = $context['sandbox']['places'];

    // Get all member campaigns for this branch.
    $memberCampaignsInfo = self::getInfoByBranch($campaign, $branchId, $activities);

    $alreadyWinners = [];

    $activityWinners = [];
    // Assign places.
    foreach ($places as $place) {
      // Calculate winners per activity.
      foreach ($memberCampaignsInfo as $category => $data) {
        if (empty($data)) {
          break;
        }

        $memberCampaignItem = self::getRandomWinner($data, $alreadyWinners);

        // Create Winner entities.
        if (!empty($memberCampaignItem)) {
          $activityWinners[] = [
            'member_campaign' => $memberCampaignItem['member_campaign'],
            'activity' => $category,
            'place' => $place,
          ];
        }
      }
    }

    // Calculate winners by Visits goal.
    $goalWinners = [];
    if ($isVisitsGoal) {
      /** @var \Drupal\openy_campaign\CampaignMenuService $campaignMenuService */
      $campaignMenuService = \Drupal::service('openy_campaign.campaign_menu_handler');
      $goalWinnersIds = $campaignMenuService->getVisitsGoalWinners($campaign, $branchId, $alreadyWinners);
      // Create Winner entity. If winner defined by Visits goal without activity - set Activity = 0.
      foreach ($places as $place) {
        $goalWinnerId = array_shift($goalWinnersIds);
        $goalWinners[] = [
          'member_campaign' => $goalWinnerId,
          'activity' => 0,
          'place' => $place,
        ];
      }
    }

    $winners = array_merge($goalWinners, $activityWinners);

    foreach ($winners as $item) {
      $winner = Winner::create($item);
      $winner->save();

      $context['results'][] = $item['member_campaign'];
    }

    $context['sandbox']['progress']++;

    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
  }
1301319
private function getPublishedCampaigns($campaignId = null)
    {
        if (!$this->publishedCampaigns) {
            foreach ($this->campaignModel->getPublishedCampaigns(true) as $campaign) {
                $this->publishedCampaigns[$campaign['id']] = $campaign['name'];
            }
        }

        if ($campaignId) {
            return isset($this->publishedCampaigns[$campaignId]) ? $this->publishedCampaigns[$campaignId] : null;
        } else {
            return $this->publishedCampaigns;
        }
    }
3510
private static function getPlatformRestrictionsForCampaignFeed(
        $campaignFeed
    ) {
        $platformRestrictions = ExtensionSettingPlatform::NONE;

        if ($campaignFeed->getMatchingFunction()->getOperator() === FunctionOperator::AND_VALUE) {
            foreach ($campaignFeed->getMatchingFunction()->getLhsOperand() as $argument) {
                if ($argument instanceof FunctionOperand) {
                    if ($argument->getValue()->getOperator() === FunctionOperator::EQUALS
                        && $argument->getValue()->getLhsOperand()[0] instanceof RequestContextOperand) {
                        $requestContextOperand = $argument->getValue()->getLhsOperand()[0];
                        if ($requestContextOperand->getContextType()
                            === RequestContextOperandContextType::DEVICE_PLATFORM) {
                            $platformRestrictions = strtoupper(
                                $argument->getValue()->getRhsOperand()[0]->getStringValue()
                            );
                        }
                    }
                }
            }
        }

        return $platformRestrictions;
    }
976437
public function addContactToCampaign()
    {
        if ($this->contact->getId()) {
            // Add the contact directly to the campaign without duplicate checking.
            // Passing manuallyAdded as true is important, prevents cron from immediately removing the contacts.
            $this->addContactsToCampaign($this->campaign, [$this->contact], true);
        }

        return $this;
    }
854855
public function addOperation(\CampaignChain\CoreBundle\Entity\Operation $operations)
    {
        $this->operations[] = $operations;

        return $this;
    }
678431
private function parseCampaign()
    {
        if (null == $this->campaign) {
            // Check Campaign existence and published status.
            $this->campaign = $this->campaignModel->getEntity($this->campaignId);
            if (!$this->campaign) {
                throw new ContactSourceException(
                    'The campaignId specified does not exist.',
                    Codes::HTTP_GONE,
                    null,
                    Stat::TYPE_INVALID,
                    'campaignId'
                );
            } elseif (
                false === $this->campaign->getIsPublished()
                && !$this->contactSource->getInternal()
            ) {
                throw new ContactSourceException(
                    'The campaignId specified has been unpublished (deactivated).',
                    Codes::HTTP_GONE,
                    null,
                    Stat::TYPE_INVALID,
                    'campaignId'
                );
            }
            $this->addTrace('contactSourceCampaignId', (int) $this->campaignId);
        }

        return $this;
    }
849955
public function cancel($campaignId)
    {
        $endpoint = $this->endpoint . '/' . $campaignId . '/actions/cancel';

        $response = $this->restClient->post($endpoint);

        return $response['body'];
    }
372759
public function hasExecutableActivities(Campaign $campaign)
    {
        $activities = $this->em->getRepository('CampaignChainCoreBundle:Activity')
            ->findBy(array(
                'campaign' => $campaign,
                'mustValidate' => true
            ));

        if(count($activities)){
            foreach ($activities as $activity){
                $isExecutable = $this->activityService->isExecutableByCampaign($activity);

                if(!$isExecutable['status']){
                    return $isExecutable;
                }
            }
        }

        return array(
            'status' => true,
        );
    }
1094752
public function withAction(string $action): self
    {
        $this->action = AuditActionEnum::ensureValid($action);
        return $this;
    }