Completed
Push — develop ( db8caa...fa5032 )
by
unknown
15:04 queued 07:24
created

FormEditor::setLanguage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 * @author    [email protected]
9
 */
10
11
namespace Core\Form\View\Helper;
12
13
use Zend\Form\ElementInterface;
14
use Zend\Form\View\Helper\FormTextarea;
15
16
class FormEditor extends FormTextarea
17
{
18
    /**
19
     * @var string
20
     */
21
    protected $theme = 'modern';
22
23
    /**
24
     * Default configuration of the form editor
25
     *
26
     * @see https://www.tinymce.com/docs/configure/integration-and-setup/
27
     * @var array
28
     */
29
    protected $options = [
30
        'selector' => 'div.tinymce_modern',
31
        'inline' => true,
32
        'theme' => 'modern',
33
        'toolbar' => 'undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | link | bullist | removeformat',
34
        'menubar' => false,
35
        'advlist_bullet_styles' => 'square disc',
36
        'block_formats' => 'Headings=h4;',
37
        'removed_menuitems' =>  'newdocument',
38
        'plugings' => [
39
             'autolink lists advlist',
40
             'visualblocks code fullscreen',
41
             'contextmenu paste link',
42
        ],
43
    ];
44
45
    /**
46
     * Language of tinyMCE
47
     *
48
     * @var string
49
     */
50
    protected $language="de";
51
52
    /**
53
     * @var
54
     */
55
    protected $translator;
56
57
    /**
58
     * @param ElementInterface $element
59
     *
60
     * @return string
61
     */
62
    public function render(ElementInterface $element)
63
    {
64
        $name   = $element->getName();
65
        if (empty($name) && $name !== 0) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $name (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
66
            throw new \DomainException(
67
                sprintf(
68
                    '%s requires that the element has an assigned name; none discovered',
69
                    __METHOD__
70
                )
71
            );
72
        }
73
74
        $renderer = $this->getView();
75
76
        /* @var \Zend\View\Helper\HeadScript  $headscript */
77
        $headscript = $renderer->plugin('headscript');
78
        $basepath = $renderer->plugin('basepath');
79
80
        $headscript->appendFile($basepath('js/tinymce/tinymce.jquery.min.js'));
81
        $headscript->prependFile($basepath('js/jquery.min.js'));
82
83
        $headscript->offsetSetScript(
84
            '1000_tinymce_' . $this->getTheme(),
85
            '
86
            $(document).ready(function() {
87
            tinyMCE.init({' . $this->additionalOptions() . ',
88
                 setup:  function(editor) {
89
                    setPlaceHolder = function(editor, show) {
90
                        placeHolder = $("#placeholder-" + editor.id);
91
                        if (placeHolder.length == 1) {
92
                            if (show && editor.getContent() == "") {
93
                                placeHolder.show();
94
                            }
95
                            else {
96
                                placeHolder.hide();
97
                            }
98
                         }
99
                    },
100
                    editor.on("focus", function(e) {
101
                        setPlaceHolder(editor, false);
102
                    });
103
                    editor.on("blur", function(e) {
104
                        setPlaceHolder(editor, true);
105
                        if (editor.isDirty()) {
106
                            //console.log("blur event", e);
107
                            editor.save();
108
                            var container = e.target.bodyElement;
109
                            $(container).parents("html").addClass("yk-changed");
110
                            var form = $(container).parents("form");
111
                            //console.log("form", form, container);
112
                            form.submit();
113
                            $(form).on("yk.forms.done", function(){
114
                                console.log("done");
115
                                //$(container).parents("html").removeClass("yk-changed");
116
                            });
117
                        }
118
                    });
119
                }
120
            });
121
            });'
122
        );
123
124
        $attributes         = $element->getAttributes();
125
        $attributes['name'] = $name;
126
        $attributes['id']   = $name;
127
        $content            = $element->getValue();
128
        if (!isset($content)) {
129
            $content = '';
130
        }
131
        if (is_string($content)) {
132
133
            $class = array_key_exists('class', $attributes)?$attributes['class']:'';
134
            $class .= (empty($class)?:' ') . ' tinymce_' . $this->getTheme();
135
            $attributes['class'] = $class;
136
            $placeHolder = '';
137
            $elementOptions = $element->getOptions();
138
            if (array_key_exists('placeholder', $elementOptions) && !empty($elementOptions['placeholder'])) {
139
                $placeHolder = '<div id="placeholder-' . $name . '" style="border: 0 none; position: relative; top: 0ex; left: 10px; color: #aaa; height: 0px; overflow: visible;' .
140
                               (empty($content)?'':'display:none;') .
141
                               '">' . $this->translator->translate($elementOptions['placeholder']) . '</div>';
142
            }
143
            return
144
                $placeHolder
145
                . sprintf(
146
                    '<div %s >%s</div>',
147
                    $this->createAttributesString($attributes),
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by $element->getAttributes() on line 124 can also be of type object<Traversable>; however, Zend\Form\View\Helper\Ab...reateAttributesString() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
148
                    $content
149
                );
150
151
        } else {
152
            return (string) $content;
153
        }
154
    }
155
156
    /**
157
     * Gets the name of the theme
158
     *
159
     * @return string
160
     */
161
    protected function getTheme()
162
    {
163
        return $this->theme;
164
    }
165
166
    protected function additionalOptions()
167
    {
168
        $str = json_encode($this->options, ~JSON_HEX_QUOT & ~JSON_FORCE_OBJECT  );
169
        $str = preg_replace('/"([a-zA-Z_]+[a-zA-Z0-9_]*)":/','$1:',$str);
170
        return  trim($str,'{}');
171
    }
172
173
    /**
174
     * Translations of "Job title" and "Subtitle" are directly made in the tinymce language files
175
     *
176
     * @param $language
177
     */
178
    public function setLanguage($language) {
179
        $this->language=$language;
180
    }
181
182
    /**
183
     * Sets the language path for tinyMCE language files
184
     *
185
     * @param $languagePath
186
     */
187
    public function setLanguagePath($languagePath) {
188
        $this->languagePath=$languagePath;
0 ignored issues
show
Bug introduced by
The property languagePath does not seem to exist. Did you mean language?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
189
    }
190
191
    /**
192
     * Set a formular editor option
193
     *
194
     * @param $name
195
     * @param $value
196
     */
197
    public function setOption($name,$value){
198
        if (array_key_exists($name, $this->options)) {
199
            $this->options[$name] = $value;
200
        }elseif ('language' == $name or 'language_url' == $name ) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
201
            $this->options[$name] = $value;
202
203
        }else{
204
            throw new \InvalidArgumentException('Unknown Option ' . $name . ' in ' .  __FILE__ . ' Line ' . __LINE__ );
205
        }
206
    }
207
208
    /**
209
     * Set formular editor options
210
     *
211
     * @param $options
212
     */
213
    public function setOptions($options)
214
    {
215
        foreach($options as $key => $val) {
216
            $this->setOption($key, $val);
217
        }
218
    }
219
}
220