LanguagesPresenter::beforeRender()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AdminModule;
4
5
use Nette\Application\UI;
6
7
/**
8
 * Languages and translations presenter.
9
 * @author Tomáš Voslař <tomas.voslar at webcook.cz>
10
 * @package WebCMS2
11
 */
12
class LanguagesPresenter extends BasePresenter
13
{
14
    /* @var Language */
15
    private $lang;
16
17
    /* @var \Webcook\Translator\ITranslator */
18
    private $translatorService;
19
20 2
    protected function beforeRender()
21
    {
22 2
        parent::beforeRender();
23 2
    }
24
25 2
    protected function startup()
26
    {
27 2
        parent::startup();
28 2
    }
29
30 1
    public function renderDefault()
31
    {
32 1
        $this->reloadContent();
33 1
    }
34
35 1
    protected function createComponentLanguageForm()
36
    {
37 1
        $locales = \WebCMS\Locales::getSystemLocales();
38 1
        $translationFiles = \WebCMS\Helpers\SystemHelper::getTranslationFiles();
39 1
        $files = array('Pick a file');
40
41 1
        foreach ($translationFiles as $f) {
42
            $files[$f] = $f;
43 1
        }
44
45 1
        $form = $this->createForm();
46 1
        $form->addText('name', 'Name')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
47 1
        $form->addText('abbr', 'Abbreviation')->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
48 1
        $form->addSelect('locale', 'Locale')->setItems($locales)->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
49 1
        $form->addCheckbox('defaultFrontend', 'Default fe');
50 1
        $form->addCheckbox('defaultBackend', 'Default be');
51 1
        $form->addSelect('import', 'Import translation', $files)->setAttribute('class', 'form-control');
0 ignored issues
show
Documentation introduced by
'form-control' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
52 1
        $form->addSubmit('save', 'Save')->setAttribute('class', 'btn btn-success');
0 ignored issues
show
Documentation introduced by
'btn btn-success' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
53
54 1
        $form->onSuccess[] = callback($this, 'languageFormSubmitted');
55
56 1
        if ($this->lang) {
57 1
            $form->setDefaults($this->lang->toArray());
58 1
        }
59
60 1
        return $form;
61
    }
62
63 2
    public function languageFormSubmitted(UI\Form $form)
64
    {
65 1
        $values = $form->getValues();
66
67
        $this->lang->setName($values->name);
68
        $this->lang->setAbbr($values->abbr);
69
        $this->lang->setLocale($values->locale);
70
        $this->lang->setDefaultFrontend($values->defaultFrontend);
71
        $this->lang->setDefaultBackend($values->defaultBackend);
72
73
        $this->em->persist($this->lang);
74
        $this->em->flush();
75
76
        if ($values->import) {
77
            $file = \WebCMS\Helpers\SystemHelper::WEBCMS_PATH.'AdminModule/static/translations/'.$values->import;
78
79 2
            $content = file_get_contents($file);
80 2
            $this->importLanguage($content, $this->lang);
81 2
        }
82
83
        // only one item can be default
84 2 View Code Duplication
        if ($values->defaultFrontend) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
85 2
            $qb = $this->em->createQueryBuilder();
86 2
            $qb->update('WebCMS\Entity\Language', 'l')
87
            ->set('l.defaultFrontend', 0)
88
            ->where('l.id <> ?1')
89
            ->setParameter(1, $this->lang->getId())
90
            ->getQuery()
91
            ->execute();
92
            $this->em->flush();
93
        }
94
95 View Code Duplication
        if ($values->defaultBackend) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
96
            $qb = $this->em->createQueryBuilder();
97
            $qb->update('WebCMS\Entity\Language', 'l')
98
            ->set('l.defaultBackend', 0)
99
            ->where('l.id <> ?1')
100
            ->setParameter(1, $this->lang->getId())
101
            ->getQuery()
102
            ->execute();
103
            $this->em->flush();
104
        }
105
106
        $this->flashMessage('Language has been added.', 'success');
107
108
        if (!$this->isAjax()) {
109
            $this->redirect('Languages:default');
110
        } else {
111
            $this->invalidateControl();
112
            $this->forward('Languages:default');
113
        }
114
    }
115
116 1
    protected function createComponentGrid($name)
117
    {
118 1
        $grid = $this->createGrid($this, $name, "Language");
119
120 1
        $grid->addColumnText('name', 'Name')->setSortable();
121 1
        $grid->addColumnText('abbr', 'Abbreviation')->setSortable();
122 1
        $grid->addColumnText('defaultFrontend', 'Default fe')->setReplacement(array(
123 1
            '1' => 'Yes',
124 1
            NULL => 'No',
125 1
        ));
126 1
        $grid->addColumnText('defaultBackend', 'Default be')->setReplacement(array(
127 1
            '1' => 'Yes',
128 1
            NULL => 'No',
129 1
        ));
130
131 1
        $grid->addActionHref("exportLanguage", 'Export')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary')));
132 1
        $grid->addActionHref("updateLanguage", 'Edit')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-primary', 'ajax'), 'data-toggle' => 'modal', 'data-target' => '#myModal', 'data-remote' => 'false'));
133 1
        $grid->addActionHref("deleteLanguage", 'Delete')->getElementPrototype()->addAttributes(array('class' => array('btn', 'btn-danger'), 'data-confirm' => 'Are you sure you want to delete the item?'));
134
135 1
        return $grid;
136
    }
137
138
    /**
139
     * Export language into JSON file and terminate response for download it.
140
     * @param Int $id
141
     */
142 2
    public function actionExportLanguage($id)
143
    {
144
        $language = $this->em->find("WebCMS\Entity\Language", $id);
145
146
        $export = array(
147 2
            'name' => $language->getName(),
148
            'abbr' => $language->getAbbr(),
149
            'translations' => array(),
150
        );
151
152
        foreach ($language->getTranslations() as $translation) {
153
            if ($translation->getBackend()) {
154
                $export['translations'][] = array(
155
                'key' => $translation->getKey(),
156
                'translation' => $translation->getTranslation(),
157
                'backend' => $translation->getBackend(),
158
            );
159
            }
160
        }
161
162
        $export = json_encode($export);
163 1
        $filename = $language->getAbbr().'.json';
164
165
        $response = $this->getHttpResponse();
166
        $response->setHeader('Content-Description', 'File Transfer');
167
        $response->setContentType('text/plain', 'UTF-8');
168
        $response->setHeader('Content-Disposition', 'attachment; filename='.$filename);
169
        $response->setHeader('Content-Transfer-Encoding', 'binary');
170
        $response->setHeader('Expires', 0);
171
        $response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
172
        $response->setHeader('Pragma', 'public');
173
        $response->setHeader('Content-Length', strlen($export));
174
175
        ob_clean();
176
        flush();
177
        echo $export;
178
179
        $this->terminate();
180
    }
181
182
    /**
183
     * @param string $fileData
184
     */
185 1
    public function importLanguage($fileData, $language)
186
    {
187
        $data = json_decode($fileData, true);
188
189
        $name = $language->getName();
190 1
        if (empty($name)) {
191
            $language->setName($data['name']);
192
        }
193
194
        $translations = array();
195
        foreach ($data['translations'] as $translation) {
196
            $t = new \WebCMS\Entity\Translation();
197
            $t->setLanguage($language);
198
            $t->setKey($translation['key']);
199
            $t->setTranslation($translation['translation']);
200
            $t->setBackend($translation['backend']);
201
            $t->setHash();
202
203
            $exists = $this->translationExists($t);
204
            if (!$exists) {
205
                if (!array_key_exists($t->getHash(), $translations)) {
206
                    $this->em->persist($t);
207
                    $translations[$t->getHash()] = $t;
208
                }
209
            } else {
210
                $exists->setHash();
211
                $exists->setTranslation($translation['translation']);
212
            }
213
        }
214
215
        $this->em->persist($language);
216
        $this->em->flush();
217
218
        // reload actual translations
219
        $default = $this->em->getRepository('WebCMS\Entity\Language')->findOneBy(array(
220 1
            'defaultBackend' => 1,
221
        ));
222
223
        $translation = new \WebCMS\Translation\Translation($this->em, $default, 1);
224
        $this->translation = $translation->getTranslations();
225
226
        $this->translator = new \WebCMS\Translation\Translator($this->translation);
227
    }
228
229
    /**
230
     * @param \WebCMS\Entity\Translation $translation
231
     */
232 View Code Duplication
    private function translationExists($translation)
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...
233
    {
234
        $exists = $this->em->getRepository('WebCMS\Entity\Translation')->findOneBy(array(
235
            'hash' => $translation->getHash(),
236
        ));
237
238
        if (is_object($exists)) {
239
            return $exists;
240
        } else {
241
            return FALSE;
242
        }
243
    }
244
245 1
    public function actionUpdateLanguage($id)
246
    {
247 1
        if ($id) {
248 1
            $this->lang = $this->em->find("WebCMS\Entity\Language", $id);
249 1
        } else {
250
            $this->lang = new \WebCMS\Entity\Language();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WebCMS\Entity\Language() of type object<WebCMS\Entity\Language> is incompatible with the declared type object<AdminModule\Language> of property $lang.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
251
        }
252 1
    }
253
254 View Code Duplication
    public function actionDeleteLanguage($id)
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...
255
    {
256
        $this->lang = $this->em->find("WebCMS\Entity\Language", $id);
257
        $this->em->remove($this->lang);
258
        $this->em->flush();
259
260
        $this->flashMessage('Language has been removed.', 'success');
261
        $this->forward('Languages:default');
262
    }
263
264 1
    public function renderUpdateLanguage($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
265
    {
266 1
        $this->reloadModalContent();
267 1
        $this->template->language = $this->lang;
0 ignored issues
show
Documentation introduced by
The property $template is declared private in Nette\Application\UI\Control. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Bug introduced by
Accessing language on the interface Nette\Templating\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
268 1
    }
269
}
270