Completed
Push — master ( 9779e6...d1902c )
by WEBEWEB
01:20
created

AbstractDataTablesProvider::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
/*
4
 * This file is part of the jquery-datatables-bundle package.
5
 *
6
 * (c) 2019 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Bundle\JQuery\DataTablesBundle\Provider;
13
14
use DateTime;
15
use Symfony\Component\Routing\Exception\InvalidParameterException;
16
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
17
use Symfony\Component\Routing\Exception\RouteNotFoundException;
18
use Symfony\Component\Routing\RouterInterface;
19
use Symfony\Component\Translation\TranslatorInterface;
20
use WBW\Bundle\BootstrapBundle\Twig\Extension\CSS\ButtonTwigExtension;
21
use WBW\Bundle\BootstrapBundle\Twig\Extension\CSS\ButtonTwigExtensionTrait;
22
use WBW\Bundle\CoreBundle\Renderer\DateTimeRenderer;
23
use WBW\Bundle\CoreBundle\Service\RouterTrait;
24
use WBW\Bundle\CoreBundle\Service\TranslatorTrait;
25
use WBW\Bundle\JQuery\DataTablesBundle\Factory\DataTablesFactory;
26
27
/**
28
 * Abstract DataTables provider.
29
 *
30
 * @author webeweb <https://github.com/webeweb/>
31
 * @package WBW\Bundle\JQuery\DataTablesBundle\Provider
32
 */
33
abstract class AbstractDataTablesProvider implements DataTablesProviderInterface {
34
35
    use ButtonTwigExtensionTrait;
36
    use RouterTrait;
37
    use TranslatorTrait;
38
39
    /**
40
     * Constructor.
41
     *
42
     * @param RouterInterface $router The router.
43
     * @param TranslatorInterface $translator The translator.
44
     * @param ButtonTwigExtension $buttonTwigExtension The button Twig extension.
45
     */
46
    public function __construct(RouterInterface $router, TranslatorInterface $translator, ButtonTwigExtension $buttonTwigExtension) {
47
        $this->setButtonTwigExtension($buttonTwigExtension);
48
        $this->setRouter($router);
49
        $this->setTranslator($translator);
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     */
55
    public function getCSVExporter() {
56
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WBW\Bundle\JQuery\DataTa...tractDataTablesProvider) is incompatible with the return type declared by the interface WBW\Bundle\JQuery\DataTa...terface::getCSVExporter of type WBW\Bundle\JQuery\DataTa...lesCSVExporterInterface.

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...
57
    }
58
59
    /**
60
     * {@inheritDoc}
61
     */
62
    public function getEditor() {
63
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (WBW\Bundle\JQuery\DataTa...tractDataTablesProvider) is incompatible with the return type declared by the interface WBW\Bundle\JQuery\DataTa...derInterface::getEditor of type WBW\Bundle\JQuery\DataTa...taTablesEditorInterface.

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...
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69
    public function getMethod() {
70
        return null;
71
    }
72
73
    /**
74
     * {@inheritDoc}
75
     */
76
    public function getOptions() {
77
78
        $dtOptions = DataTablesFactory::newOptions();
79
        $dtOptions->addOption("responsive", true);
80
        $dtOptions->addOption("searchDelay", 1000);
81
82
        return $dtOptions;
83
    }
84
85
    /**
86
     * Render the DataTables buttons.
87
     *
88
     * @param object $entity The entity.
89
     * @param string $editRoute The edit route.
90
     * @param string $deleteRoute The delete route.
91
     * @param bool $enableDelete Enable delete ?
92
     * @return string Returns the DataTables buttons.
93
     * @throws InvalidParameterException Throws an invalid parameter exception if a parameter is invalid.
94
     * @throws RouteNotFoundException Throws a route not found exception if the route doesn't exist.
95
     * @throws MissingMandatoryParametersException Throws a missing mandatory parameter exception if a mandatory exception is missing.
96
     * @deprecated since 3.4.0 use "WBW\Bundle\JQuery\DataTablesBundle\Provider\AbstractDataTablesProvider::renderRowButtons()" instead
97
     */
98
    protected function renderButtons($entity, $editRoute, $deleteRoute = null, $enableDelete = true) {
99
        if (null === $deleteRoute && true === $enableDelete) {
100
            $deleteRoute = "wbw_jquery_datatables_delete";
101
        }
102
        return $this->renderRowButtons($entity, $editRoute, $deleteRoute, null);
103
    }
104
105
    /**
106
     * Render a date.
107
     *
108
     * @param DateTime $date The date.
109
     * @param string $format The format.
110
     * @return string Returns the rendered date.
111
     */
112
    protected function renderDate(DateTime $date = null, $format = "Y-m-d") {
113
        return DateTimeRenderer::renderDateTime($date, $format);
114
    }
115
116
    /**
117
     * Render a date/time.
118
     *
119
     * @param DateTime $date The date/time.
120
     * @param string $format The format.
121
     * @return string Returns the rendered date/time.
122
     */
123
    protected function renderDateTime(DateTime $date = null, $format = DateTimeRenderer::DATETIME_FORMAT) {
124
        return DateTimeRenderer::renderDateTime($date, $format);
125
    }
126
127
    /**
128
     * Render a float.
129
     *
130
     * @param float $number The number.
131
     * @param int $decimals The decimals.
132
     * @param string $decPoint The decimal point.
133
     * @param string $thousandsSep The thousands separator.
134
     * @return string Returns the rendered number.
135
     */
136
    protected function renderFloat($number, $decimals = 2, $decPoint = ".", $thousandsSep = ",") {
137
        if (null === $number) {
138
            return "";
139
        }
140
        return number_format($number, $decimals, $decPoint, $thousandsSep);
141
    }
142
143
    /**
144
     * Render the DataTables row buttons.
145
     *
146
     * @param object $entity The entity.
147
     * @param string|null $editRoute The edit route.
148
     * @param string|null $deleteRoute The delete route.
149
     * @param string|null $showRoute The show route.
150
     * @return string Returns the DataTables row buttons.
151
     * @throws InvalidParameterException Throws an invalid parameter exception if a parameter is invalid.
152
     * @throws RouteNotFoundException Throws a route not found exception if the route doesn't exist.
153
     * @throws MissingMandatoryParametersException Throws a missing mandatory parameter exception if a mandatory exception is missing.
154
     */
155
    protected function renderRowButtons($entity, $editRoute = null, $deleteRoute = null, $showRoute = null) {
156
157
        $output = [];
158
159
        $titles   = [];
160
        $titles[] = $this->getTranslator()->trans("label.edit", [], "WBWJQueryDataTablesBundle");
161
        $titles[] = $this->getTranslator()->trans("label.delete", [], "WBWJQueryDataTablesBundle");
162
        $titles[] = $this->getTranslator()->trans("label.show", [], "WBWJQueryDataTablesBundle");
163
164
        $buttons   = [];
165
        $buttons[] = $this->getButtonTwigExtension()->bootstrapButtonDefaultFunction(["icon" => "fa:pen", "title" => $titles[0], "size" => "xs"]);
166
        $buttons[] = $this->getButtonTwigExtension()->bootstrapButtonDangerFunction(["icon" => "fa:trash", "title" => $titles[1], "size" => "xs"]);
167
        $buttons[] = $this->getButtonTwigExtension()->bootstrapButtonInfoFunction(["icon" => "fa:eye", "title" => $titles[2], "size" => "xs"]);
168
169
        $urls = [];
170
171
        if (null !== $editRoute) {
172
173
            $urls[]   = $this->getRouter()->generate($editRoute, ["id" => $entity->getId()]);
174
            $output[] = $this->getButtonTwigExtension()->bootstrapButtonLinkFilter($buttons[0], $urls[0]);
175
        }
176
177
        if (null !== $deleteRoute) {
178
179
            $args = "wbw_jquery_datatables_delete" === $deleteRoute ? ["name" => $this->getName()] : [];
180
181
            $urls[]   = $this->getRouter()->generate($deleteRoute, array_merge($args, ["id" => $entity->getId()]));
182
            $output[] = $this->getButtonTwigExtension()->bootstrapButtonLinkFilter($buttons[1], $urls[1]);
183
        }
184
185
        if (null !== $showRoute) {
186
187
            $urls[]   = $this->getRouter()->generate($showRoute, ["id" => $entity->getId()]);
188
            $output[] = $this->getButtonTwigExtension()->bootstrapButtonLinkFilter($buttons[2], $urls[2]);
189
        }
190
191
        return implode(" ", $output);
192
    }
193
194
    /**
195
     * Wrap a content.
196
     *
197
     * @param string|null $prefix The prefix
198
     * @param string $content The content.
199
     * @param string|null $suffix The suffix.
200
     * @return string Returns the wrapped content.
201
     */
202
    protected function wrapContent($prefix, $content, $suffix) {
203
204
        $output = [];
205
206
        if (null !== $prefix) {
207
            $output[] = $prefix;
208
        }
209
        $output[] = $content;
210
        if (null !== $suffix) {
211
            $output[] = $suffix;
212
        }
213
214
        return implode("", $output);
215
    }
216
}
217