Completed
Push — master ( 6d39a6...93f6e0 )
by Aydin
13:49 queued 07:20
created

ConcernedAboutSeparation::check()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 18
rs 9.2
cc 4
eloc 10
nc 6
nop 1
1
<?php
2
3
namespace PhpSchool\LearnYouPhp\Exercise;
4
5
use Faker\Generator;
6
use PhpParser\Parser;
7
use PhpSchool\PhpWorkshop\Exercise\AbstractExercise;
8
use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface;
9
use PhpSchool\PhpWorkshop\Exercise\TemporaryDirectoryTrait;
10
use PhpSchool\PhpWorkshop\ExerciseCheck\SelfCheck;
11
use PhpSchool\PhpWorkshop\ExerciseCheck\StdOutExerciseCheck;
12
use PhpSchool\PhpWorkshop\Result\Failure;
13
use PhpSchool\PhpWorkshop\Result\ResultInterface;
14
use PhpSchool\PhpWorkshop\Result\Success;
15
use PhpSchool\PhpWorkshop\Solution\DirectorySolution;
16
use PhpSchool\PhpWorkshop\Solution\SolutionInterface;
17
use Symfony\Component\Filesystem\Filesystem;
18
use PhpParser\Node\Expr\Include_;
19
20
/**
21
 * Class ConcernedAboutSeparation
22
 * @package PhpSchool\LearnYouPhp\Exercise
23
 * @author Aydin Hassan <[email protected]>
24
 */
25
class ConcernedAboutSeparation extends AbstractExercise implements
26
    ExerciseInterface,
27
    StdOutExerciseCheck,
28
    SelfCheck
29
{
30
    use TemporaryDirectoryTrait;
31
    
32
    /**
33
     * @var Filesystem
34
     */
35
    private $filesystem;
36
37
    /**
38
     * @var Generator
39
     */
40
    private $faker;
41
    
42
    /**
43
     * @var Parser
44
     */
45
    private $parser;
46
47
    /**
48
     * @param Filesystem $filesystem
49
     * @param Generator $faker
50
     * @param Parser $parser
51
     */
52
    public function __construct(Filesystem $filesystem, Generator $faker, Parser $parser)
53
    {
54
        $this->filesystem   = $filesystem;
55
        $this->faker        = $faker;
56
        $this->parser       = $parser;
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    public function getName()
63
    {
64
        return 'Concerned about Separation?';
65
    }
66
67
    /**
68
     * @return string
69
     */
70
    public function getDescription()
71
    {
72
        return 'Separate code and utilise files and classes';
73
    }
74
75
    /**
76
     * @return array
77
     */
78 View Code Duplication
    public function getArgs()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
79
    {
80
        $folder = $this->getTemporaryPath();
81
82
        $files = [
83
            "learnyouphp.dat",
84
            "learnyouphp.txt",
85
            "learnyouphp.sql",
86
            "api.html",
87
            "README.md",
88
            "CHANGELOG.md",
89
            "LICENCE.md",
90
            "md",
91
            "data.json",
92
            "data.dat",
93
            "words.dat",
94
            "w00t.dat",
95
            "w00t.txt",
96
            "wrrrrongdat",
97
            "dat",
98
        ];
99
100
        $this->filesystem->mkdir($folder);
101
        array_walk($files, function ($file) use ($folder) {
102
            $this->filesystem->dumpFile(sprintf('%s/%s', $folder, $file), '');
103
        });
104
105
        $ext = '';
106
        while ($ext === '') {
107
            $index = array_rand($files);
108
            $ext = pathinfo($files[$index], PATHINFO_EXTENSION);
109
        }
110
111
        return [$folder, $ext];
112
    }
113
114
    /**
115
     * @return SolutionInterface
116
     */
117
    public function getSolution()
118
    {
119
        return DirectorySolution::fromDirectory(__DIR__ . '/../../exercises/concerned-about-separation/solution');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \PhpSchool\PhpWor...-separation/solution'); (PhpSchool\PhpWorkshop\Solution\DirectorySolution) is incompatible with the return type of the parent method PhpSchool\PhpWorkshop\Ex...ctExercise::getSolution of type PhpSchool\PhpWorkshop\Solution\SingleFileSolution.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
120
    }
121
122
    /**
123
     * @return null
124
     */
125
    public function tearDown()
126
    {
127
        $this->filesystem->remove($this->getTemporaryPath());
128
    }
129
130
    /**
131
     * @param string $fileName
132
     * @return ResultInterface
133
     */
134
    public function check($fileName)
135
    {
136
        $statements = $this->parser->parse(file_get_contents($fileName));
137
        
138
        $include = null;
139
        foreach ($statements as $statement) {
0 ignored issues
show
Bug introduced by
The expression $statements of type array<integer,object<PhpParser\Node>>|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
140
            if ($statement instanceof Include_) {
141
                $include = $statement;
142
                break;
143
            }
144
        }
145
        
146
        if (null === $include) {
147
            return Failure::fromNameAndReason($this->getName(), 'No require statement found');
148
        }
149
        
150
        return new Success($this->getName());
151
    }
152
}
153