Completed
Push — feature-output-formats ( 634caa...8e593c )
by Arnaud
02:16
created

Section::generate()   C

Complexity

Conditions 10
Paths 24

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 6.9624
c 0
b 0
f 0
cc 10
nc 24
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Page\Collection as PagesCollection;
12
use Cecil\Collection\Page\Page;
13
use Cecil\Page\Type;
14
15
/**
16
 * Class Section.
17
 */
18
class Section extends AbstractGenerator implements GeneratorInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function generate(PagesCollection $pagesCollection, \Closure $messageCallback)
24
    {
25
        $generatedPages = new PagesCollection('sections');
0 ignored issues
show
Unused Code introduced by
$generatedPages is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
26
        $sectionsList = [];
27
28
        // identify sections
29
        /* @var $page Page */
30
        foreach ($pagesCollection as $page) {
31
            if ($page->getSection()) {
32
                // ie: ['blog'][0]['blog/post-1']
33
                $sectionsList[$page->getSection()][] = $page->getId();
34
            }
35
        }
36
37
        // sections collections
38
        $sections = [];
39
        foreach ($sectionsList as $sectionName => $pagesList) {
40
            if (!array_key_exists($sectionName, $sections)) {
41
                $sections[$sectionName] = new PagesCollection($sectionName);
42
                foreach ($pagesList as $pageId) {
43
                    $sections[$sectionName]->add($pagesCollection->get($pageId));
0 ignored issues
show
Bug introduced by
It seems like $pagesCollection->get($pageId) targeting Cecil\Collection\Collection::get() can also be of type boolean; however, Cecil\Collection\Collection::add() does only seem to accept object<Cecil\Collection\ItemInterface>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
44
                }
45
            }
46
        }
47
48
        // DEBUG
49
        //print_r($sections2);
50
        //print_r($section3);
51
        foreach ($section3 as $section => $collection) {
0 ignored issues
show
Bug introduced by
The variable $section3 does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
52
            //echo $section."\n";
53
            $collection->sortByDate();
54
            //echo $collection->getId()."\n";
55
            //echo $collection;
56
            print_r($collection);
57
        }
58
        die();
59
60
        // adds section pages to collection
61
        if (count($sections) > 0) {
0 ignored issues
show
Unused Code introduced by
if (count($sections) > 0...nuWeight += 10; } } 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...
62
            $menuWeight = 100;
63
            foreach ($sections as $section => $pages) {
64
                $pageId = Page::slugify($section);
65
                if (!$pagesCollection->has($pageId)) {
66
                    usort($pages, 'Cecil\Util::sortByDate');
67
                    $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...
68
                        ->setId($pageId)
69
                        ->setPathname($pageId)
70
                        ->setVariable('title', ucfirst($section))
71
                        ->setType(Type::SECTION)
72
                        ->setVariable('pages', $pages)
73
                        ->setVariable('date', reset($pages)->getVariable('date'))
74
                        ->setVariable('menu', [
75
                            'main' => ['weight' => $menuWeight],
76
                        ]);
77
                    $generatedPages->add($page);
78
                }
79
                $menuWeight += 10;
80
            }
81
        }
82
83
        return $generatedPages;
84
    }
85
}
86