Generate Summary Activities CSV.

@param \Drupal\node\NodeInterface|int $node

@return \Symfony\Component\HttpFoundation\Response
509135
public function generateSummaryActivitiesCsv($node) {
    $summary = $this->getSummary($node);

    $header = [
      $this->t('Category'),
      $this->t('Subcategory'),
      $this->t('Category Amount'),
      $this->t('Subcategory Amount'),
    ];

    $records = [];

    foreach ($summary['activities']['categories'] as $activity) {
      /** @var \Drupal\taxonomy\Entity\Term $term */
      $term = $activity['term'];

      $records[] = [$term->getName(), '', $activity['amount'], ''];

      foreach ($activity['subcategories'] as $subcategory) {
        /** @var \Drupal\taxonomy\Entity\Term $subTerm */
        $subTerm = $subcategory['term'];

        $records[] = ['', $subTerm->getName(), '', $subcategory['amount']];
      }
    }

    $records[] = ['', '', '', ''];
    $records[] = [$this->t('Total'), '', '', $summary['activities']['totalActivities']];

    $fileName = 'summary_activities_' . date('Y-m-d') . '.csv';

    return $this->createCsvResponse($fileName, $header, $records);
  }
972762
public function convertTableNodeToQueries(TableNode $node)
    {
        // Get the title row.
        $columns = $node->getRow(0);

        // Get all rows and extract the heading.
        $rows = $node->getRows();
        unset($rows[0]);

        if (! $rows) {
            throw new \Exception('No data provided to loop through.');
        }

        $queries = [];

        // Loop through the rest of the rows and form up the queries.
        foreach ($rows as $row) {
            $query = '';
            foreach ($row as $index => $value) {
                $query .= sprintf('%s:%s,', $columns[$index], $value);
            }
            $queries[] = trim($query, ',');
        }

        return $queries;
    }
1183429
public function updateMetadata(Node $node)
    {
        $this->updateFileTimes($node);
        $this->updateOwnership($node);

        return $node;
    }
1040663
public function generate($node)
    {
        $callable = $this->generator;
        $generatedPathAsUtf8 = $callable($node);

        return $generatedPathAsUtf8 ? $this->translateToUrlEncodedPath($generatedPathAsUtf8) : false;
    }
290470
private function makeFileReportsFromFiles(\SimpleXMLElement $node, $fileReports)
    {
        foreach ($node as $file) {
            // iterate files in the package
            $countStatement = intval($file->metrics['statements']);
            $countCoveredStatements = intval($file->metrics['coveredstatements']);
            if ($countStatement == 0) {
                $fileTotal = 0;
            } else {
                $fileTotal = round($this->safeDivision($countCoveredStatements, $countStatement) * 100);
            }
            $fileName = $this->getRelativePath($file['name']);
            $lineCoverage = $this->getLineCoverage($file);
            $fileReport = new FileReport($fileTotal, $fileName, $lineCoverage);
            array_push($fileReports, $fileReport);
        }
        return $fileReports;
    }
185292
public function enterNode(Node $node)
    {
        if ($node instanceof Dir) {
            return new FuncCall(new Name('getcwd'), [], $node->getAttributes());
        } elseif ($node instanceof File) {
            return new String_('', $node->getAttributes());
        }
    }
851899
protected function getDisplayText(Node $node) {
    if ($this->isRootTypeNode($node->getOID())) {
      $mapper = $node->getMapper();
      return $mapper->getTypeDisplayName($this->getMessage());
    }
    else {
      return strip_tags(preg_replace("/[\r\n']/", " ", NodeUtil::getDisplayValue($node)));
    }
  }
1297975
public function importFormAction(ResourceNode $node)
    {
        $form = $this->formFactory->create(new ImportResourcesType());

        return array('form' => $form->createView(), 'directory' => $node);
    }
776383
public function updateFileTimes(Node $node)
    {
        $time = time();
        $node->setAccessTime($time);
        $node->setModificationTime($time);
        $node->setChangeTime($time);

        return $node;
    }
1132013
public static function buildTagStampForNode2($node)
    {

        $cleanNode = self::cleanNodeFromAttributes($node);  //! not working

        $newdoc = new DOMDocument();

        $cloned = $cleanNode->cloneNode(TRUE);
        if (!$cloned)
        {
            return;
        }
        $newdoc->appendChild($newdoc->importNode($cloned, TRUE));
        $html = $newdoc->saveXML();
        preg_match_all('#<([a-zA-Z0-9]+)#i', $html, $matches);

        $tagsArr = $matches[1];
        $tagsToRemove = array('script', 'style', 'head', 'link', 'meta', 'sup', 'sub', 'br');
        $tagsArr = array_diff($tagsArr, $tagsToRemove);

        $tagStamp = join('|', $tagsArr);
        $htmlTagsOptimizer = array(
            '.div,', '.table,', '.td,', '.tr,', '.th,', '.a,', '.span,', '.b,', '.i,', '.noindex,', '.img,', '.h1,', '.h2,', '.h3,', '.h4,', '.h5,'
        );
        $tagStamp = trim(str_replace($htmlTagsOptimizer, array_keys($htmlTagsOptimizer), $tagStamp));

        return $tagStamp;
    }
169340
public function generateTree($nodes)
    {
        $superRoot = count(array_filter($nodes, function (ReadNodeInterface $node) {
            return '-' == $node->getParentId();
        }))? '-': 'root';

        $list = array();
        $list[$superRoot] = array();
        foreach ($nodes as $node) {
            if ($superRoot !== $node->getParentId() && $this->parentInList($node->getParentId(), $nodes)) {
                $list[$node->getParentId()][] = $node;
                continue;
            }
            $list[$superRoot][] = $node;
        }

        $tree = $this->createTree($list[$superRoot], $list);

        return $tree;
    }
1271682
public function enterNode(PhpParser\Node $node)
    {
        $attrs = $node->getAttributes();

        if ($cs = $node->getComments()) {
            $new_comments = [];

            foreach ($cs as $c) {
                if ($c instanceof PhpParser\Comment\Doc) {
                    $new_comments[] = new PhpParser\Comment\Doc(
                        $c->getText(),
                        $c->getLine() + $this->line_offset,
                        $c->getFilePos() + $this->file_offset
                    );
                } else {
                    $new_comments[] = new PhpParser\Comment(
                        $c->getText(),
                        $c->getLine() + $this->line_offset,
                        $c->getFilePos() + $this->file_offset
                    );
                }
            }

            $node->setAttribute('comments', $new_comments);
        }

        /** @psalm-suppress MixedOperand */
        $node->setAttribute('startFilePos', $attrs['startFilePos'] + $this->file_offset);
        /** @psalm-suppress MixedOperand */
        $node->setAttribute('endFilePos', $attrs['endFilePos'] + $this->file_offset);
        /** @psalm-suppress MixedOperand */
        $node->setAttribute('startLine', $attrs['startLine'] + $this->line_offset);
    }
1090364
public void buildSummary(XMLNode node, Content profileContentTree) {
        Content summaryContentTree = profileWriter.getSummaryHeader();
        buildChildren(node, summaryContentTree);
        profileContentTree.addContent(profileWriter.getSummaryTree(summaryContentTree));
    }
137635
protected function generateText($node)
    {
        $buffer = '';
        
        $value = explode("\n", $node['value']);
        $last = count($value) - 1;
        
        foreach ($value as $i => $line) {
            $line = str_replace("'", '\\\'', $line);
            
            if ($i === $last) {
                $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LAST, $line));
                continue;
            }

            $buffer .= $this->prettyPrint(sprintf(self::BLOCK_TEXT_LINE, $line));
        }
        
        return $buffer;
    }
120811
public function enterNode(Node $node)
    {
        if ($node instanceof UseUse) {
            $this->imports[] = $node->name->toString();
        }

        return $node;
    }
9496
public function generateLiveScorecard(Node $node) {
    if ($node->bundle() != 'campaign') {
      return FALSE;
    }

    // Prepare dates of campaign.
    $campaignTimezone = new \DateTime($node->get('field_campaign_timezone')->getString());
    $campaignTimezone = $campaignTimezone->getTimezone();

    // All time of campaign.
    $localeCampaignStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_start_date')->getString());
    $localeCampaignStart->convertTimezone($campaignTimezone);

    $localeCampaignEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_end_date')->getString());
    $localeCampaignEnd->convertTimezone($campaignTimezone);

    // Time of early registration.
    $localeRegistrationStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_start_date')->getString());
    $localeRegistrationStart->convertTimezone($campaignTimezone);

    $localeRegistrationEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_end_date')->getString());
    $localeRegistrationEnd->convertTimezone($campaignTimezone);

    $result['dates']['registration_start'] = $localeRegistrationStart->getDate()->format('m/d');
    $result['dates']['registration_end'] = $localeRegistrationEnd->getDate()->format('m/d');
    $result['dates']['campaign_start'] = $localeCampaignStart->getDate()->format('m/d');
    $result['dates']['campaign_end'] = $localeCampaignEnd->getDate()->format('m/d');

    // Current dates. + labels with dates.
    $localTime = OpenYLocaleDate::createDateFromFormat(date('c'));
    $localTime->convertTimezone($campaignTimezone);

    if ($localTime > $localeRegistrationEnd) {
      $actual_early_date = $localeRegistrationEnd->getDate()->format('m/d') . ' at ' . $localeRegistrationEnd->getDate()->format('h:ia');
    }
    else {
      $actual_early_date = $localTime->getDate()->format('m/d');
    }

    if ($localTime > $localeCampaignEnd) {
      $actual_campaign_date = $localeCampaignEnd->getDate()->format('m/d') . ' at ' . $localeCampaignEnd->getDate()->format('h:ia');
    }
    else {
      $actual_campaign_date = $localTime->getDate()->format('m/d');
    }

    $result['dates']['actual_date'] = $localTime->getDate()->format('m/d');
    $result['dates']['actual_early_date'] = $actual_early_date;
    $result['dates']['actual_campaign_date'] = $actual_campaign_date;

    // Get branches for current campaign.
    $branches = $this->getCampaignBranches($node);

    if (!empty($branches['branches'])) {

      $branchIds = [];
      foreach ($branches['branches'] as $branch) {
        $branchIds[] = $branch->branch;
      }

      $targets = $branches['targets'];
      $branchList = $branches['branches'];
      // Calculate registered members by branch, Early registration and During all campain.
      $earlyActualMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeRegistrationEnd->getTimestamp());
      $challengeRegistrationOfMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeCampaignEnd->getTimestamp());

      // Prepare render array.
      $result['registration']['early'] = [];
      $result['registration']['challenge'] = [];
      $result['utilization'] = [];

      $register_goal = $node->get('field_campaign_registration_goal')->getValue();
      $utilization_goal = $node->get('field_campaign_utilization_goal')->getValue();
      $registerGoal = !empty($register_goal) ? $register_goal[0]['value'] : 5;
      $utilizationGoal = !empty($utilization_goal) ? $utilization_goal[0]['value'] : 45;

      $result['goals']['registration_goal'] = $registerGoal;
      $result['goals']['utilization_goal'] = $utilizationGoal;

      $util_by_branch = $this->getCampaignUtilizationActivitiesByBranches($node);

      foreach ($branchList as $id => $branch) {

        $result['branches'][$id]['nid'] = $branch->personify_branch;
        $result['branches'][$id]['title'] = $branch->title;
        $target = $targets[$id];
        $result['branches'][$id]['target'] = $target;

        // Early registration calculation.
        $goal = number_format($target * $registerGoal / 100);

        $result['registration']['early'][$id]['registration_goal'] = $goal;

        $actual = !empty($earlyActualMembers[$id]->count_id) ? $earlyActualMembers[$id]->count_id : 0;
        $result['registration']['early'][$id]['actual'] = $actual;

        $of_members = number_format($actual / $targets[$id] * 100, 1);
        $result['registration']['early'][$id]['of_members'] = $of_members;

        $of_goal = $goal ? number_format($actual / $goal * 100, 1) : 0;
        $result['registration']['early'][$id]['of_goal'] = $of_goal;
        if (!array_key_exists('total', $result)) {
          $result['total'] = [];
        }
        // Total Early registration calculation.
        if (!array_key_exists('target', $result['total'])){
          $result['total']['target'] = 0;
        }
        $result['total']['target'] += $target;
        if (!array_key_exists('registration_goal', $result['total'])){
          $result['total']['registration_goal'] = 0;
        }
        $result['total']['registration_goal'] += $goal;
        if (!array_key_exists('actual', $result['total'])){
          $result['total']['actual'] = 0;
        }
        $result['total']['actual'] += $actual;
        if (!array_key_exists('of_members', $result['total'])){
          $result['total']['of_members'] = 0;
        }
        $result['total']['of_members'] += $of_members;
        if (!array_key_exists('of_goal', $result['total'])){
          $result['total']['of_goal'] = 0;
        }
        $result['total']['of_goal'] += $of_goal;

        // Challenge registration calculation.
        $result['registration']['challenge'][$id]['registration_goal'] = $goal;

        $reg_actual = !empty($challengeRegistrationOfMembers[$id]->count_id) ? $challengeRegistrationOfMembers[$id]->count_id : 0;
        $result['registration']['challenge'][$id]['actual'] = $reg_actual;

        $reg_of_member = number_format($reg_actual / $target * 100, 1);
        $result['registration']['challenge'][$id]['of_members'] = $reg_of_member;

        $reg_of_goal = $goal ? number_format($reg_actual / $goal * 100, 1) : 0;
        $result['registration']['challenge'][$id]['of_goal'] = $reg_of_goal;
        if (!array_key_exists('reg_registration_goal', $result['total'])){
          $result['total']['reg_registration_goal'] = 0;
        }
        $result['total']['reg_registration_goal'] += $goal;
        if (!array_key_exists('reg_actual', $result['total'])){
          $result['total']['reg_actual'] = 0;
        }
        $result['total']['reg_actual'] += $reg_actual;
        if (!array_key_exists('reg_of_members', $result['total'])){
          $result['total']['reg_of_members'] = 0;
        }
        $result['total']['reg_of_members'] += $reg_of_member;
        if (!array_key_exists('reg_of_goal', $result['total'])){
          $result['total']['reg_of_goal'] = 0;
        }
        $result['total']['reg_of_goal'] += $reg_of_goal;

        // Utilization calculation.
        if ($actual >= $goal) {
          $util_goal = number_format($actual * $utilizationGoal / 100);
        }
        else {
          $util_goal = number_format($goal * $utilizationGoal / 100);
        }

        $result['utilization'][$id]['goal'] = $util_goal;

        $util_actual = isset($util_by_branch[$id]) ? $util_by_branch[$id] : 0;
        $result['utilization'][$id]['actual'] = $util_actual;

        if (!empty($reg_actual)) {
          $util_of_member = number_format($util_actual / $reg_actual * 100, 1);
        }
        else {
          $util_of_member = 0;
        }

        $result['utilization'][$id]['of_members'] = $util_of_member;

        $util_of_goal = $util_goal ? number_format($util_actual / $util_goal * 100, 1) : 0;

        $result['utilization'][$id]['of_goal'] = $util_of_goal;

        // Utilization total.
        if (!array_key_exists('util_registration_goal', $result['total'])){
          $result['total']['util_registration_goal'] = 0;
        }
        $result['total']['util_registration_goal'] += $util_goal;
        // Doesn't include results for members without branch ($id = 0 or '').
        if (!array_key_exists('util_actual', $result['total'])){
          $result['total']['util_actual'] = 0;
        }
        if (!array_key_exists('util_of_members', $result['total'])){
          $result['total']['util_of_members'] = 0;
        }
        $result['total']['util_of_members'] += $util_of_member;
        if (!array_key_exists('util_of_goal', $result['total'])){
          $result['total']['util_of_goal'] = 0;
        }
        $result['total']['util_of_goal'] += $util_of_goal;

      }

      $result['total']['of_members'] = number_format($result['total']['of_members'] / count($targets), 1);
      $result['total']['of_goal'] = number_format($result['total']['of_goal'] / count($targets), 1);
      $result['total']['reg_of_members'] = number_format($result['total']['reg_of_members'] / count($targets), 1);
      $result['total']['reg_of_goal'] = number_format($result['total']['reg_of_goal'] / count($targets), 1);
      $result['total']['util_of_members'] = number_format($result['total']['util_of_members'] / count($targets), 1);
      $result['total']['util_of_goal'] = number_format($result['total']['util_of_goal'] / count($targets), 1);
    }
    else {
      $result['empty'] = t('Campaign @campaign has no active branches. Please edit current campaign', ['@campaign' => $node->label()]);
    }
    $build = [
      '#theme' => 'openy_campaign_scorecard',
      '#result' => $result
    ];

    return $build;
  }
329953
private function getNodeTextContent(Node $node)
    {
        if ($node instanceof Text) {
            return $node->getContent();
        }

        if ($node instanceof AbstractInlineContainer) {
            $text = '';
            foreach ($node->children() as $child) {
                $text .= $this->getNodeTextContent($child);
            }

            return $text;
        }

        return '';
    }