Completed
Push — collection-taxonomy ( 3d16b8 )
by Arnaud
02:04
created

Taxonomy::initTaxonomiesCollection()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Generator;
10
11
use Cecil\Collection\Collection as PageCollection;
12
use Cecil\Collection\Page\Page;
13
use Cecil\Collection\Taxonomy\Collection as TaxonomyCollection;
14
use Cecil\Collection\Taxonomy\Term as Term;
15
use Cecil\Collection\Taxonomy\Vocabulary as Vocabulary;
16
use Cecil\Exception\Exception;
17
use Cecil\Page\NodeType;
18
19
/**
20
 * Class Taxonomy.
21
 */
22
class Taxonomy extends AbstractGenerator implements GeneratorInterface
23
{
24
    /* @var TaxonomyCollection */
25
    protected $taxonomies;
26
    /* @var PageCollection */
27
    protected $pageCollection;
28
    /* @var PageCollection */
29
    protected $generatedPages;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function generate(PageCollection $pageCollection, \Closure $messageCallback)
35
    {
36
        $this->pageCollection = $pageCollection;
37
        $this->generatedPages = new PageCollection('generator-taxonomy');
38
39
        if ($this->config->get('site.taxonomies') && !$this->config->get('site.taxonomies.disabled')) {
40
            $this->initTaxonomiesCollection();
41
            $this->collectTermsFromPages();
42
            $this->createNodePages();
43
        }
44
45
        return $this->generatedPages;
46
    }
47
48
    /**
49
     * Create a collection from the vocabularies configuration.
50
     */
51
    protected function initTaxonomiesCollection()
52
    {
53
        // create an empty "taxonomies" collection
54
        $this->taxonomies = new TaxonomyCollection('taxonomies');
55
56
        // adds each vocabulary collection to the "taxonomies" collection
57
        foreach ($this->config->get('site.taxonomies') as $vocabulary) {
58
            if ($vocabulary != 'disable') {
59
                $this->taxonomies->add(new Vocabulary($vocabulary));
60
            }
61
        }
62
    }
63
64
    /**
65
     * Collects taxonomies's terms from pages frontmatter.
66
     */
67
    protected function collectTermsFromPages()
68
    {
69
        /* @var $page Page */
70
        foreach ($this->pageCollection as $page) {
71
            foreach (array_keys($this->config->get('site.taxonomies')) as $plural) {
72
                if ($page->hasVariable($plural)) {
73
                    // converts a list to an array if necessary
74
                    if (!is_array($page->getVariable($plural))) {
75
                        $page->setVariable($plural, [$page->getVariable($plural)]);
76
                    }
77
                    // adds each term to the vocabulary collection
78
                    foreach ($page->getVariable($plural) as $term) {
79
                        $this->taxonomies->get($plural)
80
                            ->add(new Term($term));
81
82
print_r($this->taxonomies->get($plural)); die();
83
84
                        // adds page to the term collection
85
                        $this->taxonomies
0 ignored issues
show
Unused Code introduced by
$this->taxonomies->get($...get($term)->add($page); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
86
                            ->get($plural)
87
                            ->get($term)
88
                            ->add($page);
89
                    }
90
                }
91
            }
92
        }
93
    }
94
95
    /**
96
     * Creates node pages.
97
     */
98
    protected function createNodePages()
99
    {
100
        /* @var $terms Vocabulary */
101
        foreach ($this->taxonomies as $plural => $terms) {
102
            if (count($terms) > 0) {
103
                /*
104
                 * Creates $plural/$term pages (list of pages)
105
                 * ex: /tags/tag-1/
106
                 */
107
                /* @var $pages PageCollection */
108
                foreach ($terms as $term => $pages) {
109
                    if (!$this->pageCollection->has($term)) {
110
                        $pages = $pages->sortByDate()->toArray();
111
                        $page = (new Page())
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cecil\Collection\Item as the method setPathname() does only exist in the following sub-classes of Cecil\Collection\Item: Cecil\Collection\Page\Page. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
112
                            ->setId(Page::urlize(sprintf('%s/%s/', $plural, $term)))
113
                            ->setPathname(Page::urlize(sprintf('%s/%s', $plural, $term)))
114
                            ->setTitle(ucfirst($term))
115
                            ->setNodeType(NodeType::TAXONOMY)
116
                            ->setVariable('pages', $pages)
117
                            ->setVariable('date', $date = reset($pages)->getDate())
118
                            ->setVariable('singular', $this->config->get('site.taxonomies')[$plural])
119
                            ->setVariable('pagination', ['pages' => $pages]);
120
                        $this->generatedPages->add($page);
121
                    }
122
                }
123
                /*
124
                 * Creates $plural pages (list of terms)
125
                 * ex: /tags/
126
                 */
127
                $page = (new Page())
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cecil\Collection\Item as the method setPathname() does only exist in the following sub-classes of Cecil\Collection\Item: Cecil\Collection\Page\Page. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
128
                    ->setId(Page::urlize($plural))
129
                    ->setPathname(strtolower($plural))
130
                    ->setTitle($plural)
131
                    ->setNodeType(NodeType::TERMS)
132
                    ->setVariable('plural', $plural)
133
                    ->setVariable('singular', $this->config->get('site.taxonomies')[$plural])
134
                    ->setVariable('terms', $terms)
135
                    ->setVariable('date', $date);
0 ignored issues
show
Bug introduced by
The variable $date does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
136
137
                // add page only if a template exist
138
                try {
139
                    $this->generatedPages->add($page);
140
                } catch (Exception $e) {
141
                    echo $e->getMessage()."\n";
142
                    // do not add page
143
                    unset($page);
144
                }
145
            }
146
        }
147
    }
148
}
149