Completed
Push — develop ( dfd31d...f6e11d )
by
unknown
17:02
created

HTMLTemplateMessage::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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\Mail;
12
13
use Zend\Mail\Header;
14
use Zend\ServiceManager\ServiceLocatorInterface;
15
use Zend\View\Model\ViewModel;
16
use Zend\Stdlib\Response;
17
use Zend\View\Variables as ViewVariables;
18
use Zend\Stdlib\ArrayUtils;
19
use Core\Mail\MailService;
20
21
/**
22
 * Class HTMLTemplateMessage.
23
 * uses methods alike ViewModel
24
 * @package Core\Mail
25
 */
26
class HTMLTemplateMessage extends TranslatorAwareMessage
27
{
28
    /**
29
     * @var ServiceLocatorInterface
30
     */
31
    protected $serviceManager;
32
33
    /**
34
     * View variables
35
     * @var array|ArrayAccess&Traversable
36
     */
37
    protected $variables = array();
38
39
    /**
40
     * @param ServiceLocatorInterface $serviceManager
41
     * @param array $options
42
     */
43
    public function __construct(ServiceLocatorInterface $serviceManager, array $options = array())
44
    {
45
        // @TODO make this multipart
46
        parent::__construct($options);
47
        $this->serviceManager = $serviceManager;
48
        $this->getHeaders()->addHeader(Header\ContentType::fromString('Content-Type: text/html; charset=UTF-8'));
49
        $this->setEncoding('UTF-8');
50
        $this->variables = new ViewVariables();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Zend\View\Variables() of type object<Zend\View\Variables> is incompatible with the declared type array of property $variables.

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...
51
    }
52
53
    /**
54
     * Property overloading: set variable value
55
     *
56
     * @param  string $name
57
     * @param  mixed $value
58
     * @return void
59
     */
60
    public function __set($name, $value)
61
    {
62
        $this->setVariable($name, $value);
63
    }
64
65
    /**
66
     * Property overloading: get variable value
67
     *
68
     * @param  string $name
69
     * @return mixed
70
     */
71
    public function __get($name)
72
    {
73
        if (!$this->__isset($name)) {
74
            return null;
75
        }
76
77
        $variables = $this->getVariables();
78
        return $variables[$name];
79
    }
80
81
    /**
82
     * Property overloading: do we have the requested variable value?
83
     *
84
     * @param  string $name
85
     * @return bool
86
     */
87
    public function __isset($name)
0 ignored issues
show
Coding Style introduced by
function __isset() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
88
    {
89
        $variables = $this->getVariables();
90
        return isset($variables[$name]);
91
    }
92
93
    /**
94
     * Property overloading: unset the requested variable
95
     *
96
     * @param  string $name
97
     * @return void
98
     */
99
    public function __unset($name)
100
    {
101
        if (!$this->__isset($name)) {
102
            return null;
103
        }
104
105
        unset($this->variables[$name]);
106
    }
107
108
    /**
109
     * Get a single view variable
110
     *
111
     * @param  string       $name
112
     * @param  mixed|null   $default (optional) default value if the variable is not present.
113
     * @return mixed
114
     */
115
    public function getVariable($name, $default = null)
116
    {
117
        $name = (string) $name;
118
        if (array_key_exists($name, $this->variables)) {
119
            return $this->variables[$name];
120
        }
121
122
        return $default;
123
    }
124
125
    /**
126
     * Set view variable
127
     *
128
     * @param  string $name
129
     * @param  mixed $value
130
     * @return ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be HTMLTemplateMessage?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
131
     */
132
    public function setVariable($name, $value)
133
    {
134
        $this->variables[(string) $name] = $value;
135
        return $this;
136
    }
137
138
    /**
139
     * Set view variables en masse
140
     *
141
     * Can be an array or a Traversable + ArrayAccess object.
142
     *
143
     * @param  array|ArrayAccess|Traversable $variables
144
     * @param  bool $overwrite Whether or not to overwrite the internal container with $variables
145
     * @throws \InvalidArgumentException
146
     * @return self
147
     */
148
    public function setVariables($variables, $overwrite = false)
149
    {
150 View Code Duplication
        if (!is_array($variables) && !$variables instanceof \Traversable) {
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...
151
            throw new \InvalidArgumentException(
152
                sprintf(
153
                    '%s: expects an array, or Traversable argument; received "%s"',
154
                    __METHOD__,
155
                    (is_object($variables) ? get_class($variables) : gettype($variables))
156
                )
157
            );
158
        }
159
160
        if ($overwrite) {
161
            if (is_object($variables) && !$variables instanceof \ArrayAccess) {
162
                $variables = ArrayUtils::iteratorToArray($variables);
163
            }
164
165
            $this->variables = $variables;
166
            return $this;
167
        }
168
169
        foreach ($variables as $key => $value) {
170
            $this->setVariable($key, $value);
171
        }
172
173
        return $this;
174
    }
175
176
    /**
177
     * Get view variables
178
     *
179
     * @return array|ArrayAccess|Traversable
180
     */
181
    public function getVariables()
182
    {
183
        return $this->variables;
184
    }
185
186
    /**
187
     * Clear all variables
188
     *
189
     * Resets the internal variable container to an empty container.
190
     *
191
     * @return ViewModel
0 ignored issues
show
Documentation introduced by
Should the return type not be HTMLTemplateMessage?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
192
     */
193
    public function clearVariables()
194
    {
195
        $this->variables = new ViewVariables();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Zend\View\Variables() of type object<Zend\View\Variables> is incompatible with the declared type array of property $variables.

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...
196
        return $this;
197
    }
198
199
    /**
200
     *
201
     *
202
     * @param $template
203
     *
204
     * @return self
205
     */
206
    public function setTemplate($template)
207
    {
208
        $this->template = $template;
0 ignored issues
show
Documentation introduced by
The property template does not exist on object<Core\Mail\HTMLTemplateMessage>. Since you implemented __set, maybe consider adding a @property annotation.

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...
209
        return $this;
210
    }
211
212
    public function getTemplate()
213
    {
214
        return $this->template;
0 ignored issues
show
Documentation introduced by
The property template does not exist on object<Core\Mail\HTMLTemplateMessage>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
215
    }
216
217
    /**
218
     * @example /module/Jobs/src/Jobs/Listener/PortalListener.php
219
     * @return string
220
     * @throws \InvalidArgumentException the mail body must completely be provided by the template, any other attempt is a misconception that may leave the coder in an quagmire
221
     */
222
    public function getBodyText()
223
    {
224
        $viewModel    = new ViewModel();
225
        $response     = new Response();
226
        $body         = parent::getBodyText();
227
        if (!empty($body)) {
228
            throw new \InvalidArgumentException('mail body shall come from Template.');
229
        }
230
231
        /* @var \Zend\Mvc\View\Http\ViewManager $viewManager */
232
        $viewManager  = $this->serviceManager->get('viewManager');
233
        $resolver = $this->serviceManager->get('viewResolver');
234
235
        /* @var \Zend\Mvc\MvcEvent $event */
236
        $event = $this->serviceManager->get('application')->getMvcEvent();
237
        $lang = $event->getRouteMatch()->getParam('lang');
238
239
240
        if ($resolver->resolve($this->getTemplate() . '.' . $lang)) {
241
            $viewModel->setTemplate($this->getTemplate() . '.' . $lang);
242
        }else{
243
            $viewModel->setTemplate($this->getTemplate());
244
        }
245
246
        $view         = $viewManager->getView();
247
248
        $viewModel->setVariables($this->getVariables());
249
        $view->setResponse($response);
250
        $view->render($viewModel);
251
        $body = $response->getContent();
252
253
        return $body;
254
    }
255
    
256
    /**
257
     * @param MailService $mailService
258
     * @return \Core\Mail\HTMLTemplateMessage
259
     */
260
    public static function factory(MailService $mailService)
261
    {
262
        return new static($mailService->getServiceLocator());
263
    }
264
}
265