Completed
Push — develop ( 159e70...e2c9b6 )
by
unknown
08:46
created

HTMLTemplateMessage::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
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\ServiceManager\ServiceLocatorAwareInterface;
16
use Zend\View\Model\ViewModel;
17
use Zend\Stdlib\Response;
18
use Zend\View\Variables as ViewVariables;
19
20
/**
21
 * Class HTMLTemplateMessage.
22
 * uses methods alike ViewModel
23
 * @package Core\Mail
24
 */
25
class HTMLTemplateMessage extends TranslatorAwareMessage implements ServiceLocatorAwareInterface
26
{
27
    protected $serviceLocator;
28
29
    /**
30
     * View variables
31
     * @var array|ArrayAccess&Traversable
32
     */
33
    protected $variables = array();
34
35
    public function __construct(array $options = array())
36
    {
37
        // @TODO make this multipart
38
        parent::__construct($options);
39
        $this->getHeaders()->addHeader(Header\ContentType::fromString('Content-Type: text/html; charset=UTF-8'));
40
        $this->setEncoding('UTF-8');
41
        $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...
42
    }
43
44
    public function getServiceLocator()
45
    {
46
        return $this->serviceLocator;
47
    }
48
49
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
50
    {
51
        $this->serviceLocator = $serviceLocator;
52
        return $this;
53
    }
54
55
56
    /**
57
     * Property overloading: set variable value
58
     *
59
     * @param  string $name
60
     * @param  mixed $value
61
     * @return void
62
     */
63
    public function __set($name, $value)
64
    {
65
        $this->setVariable($name, $value);
66
    }
67
68
    /**
69
     * Property overloading: get variable value
70
     *
71
     * @param  string $name
72
     * @return mixed
73
     */
74
    public function __get($name)
75
    {
76
        if (!$this->__isset($name)) {
77
            return null;
78
        }
79
80
        $variables = $this->getVariables();
81
        return $variables[$name];
82
    }
83
84
    /**
85
     * Property overloading: do we have the requested variable value?
86
     *
87
     * @param  string $name
88
     * @return bool
89
     */
90
    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...
91
    {
92
        $variables = $this->getVariables();
93
        return isset($variables[$name]);
94
    }
95
96
    /**
97
     * Property overloading: unset the requested variable
98
     *
99
     * @param  string $name
100
     * @return void
101
     */
102
    public function __unset($name)
103
    {
104
        if (!$this->__isset($name)) {
105
            return null;
106
        }
107
108
        unset($this->variables[$name]);
109
    }
110
111
    /**
112
     * Get a single view variable
113
     *
114
     * @param  string       $name
115
     * @param  mixed|null   $default (optional) default value if the variable is not present.
116
     * @return mixed
117
     */
118
    public function getVariable($name, $default = null)
119
    {
120
        $name = (string) $name;
121
        if (array_key_exists($name, $this->variables)) {
122
            return $this->variables[$name];
123
        }
124
125
        return $default;
126
    }
127
128
    /**
129
     * Set view variable
130
     *
131
     * @param  string $name
132
     * @param  mixed $value
133
     * @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...
134
     */
135
    public function setVariable($name, $value)
136
    {
137
        $this->variables[(string) $name] = $value;
138
        return $this;
139
    }
140
141
    /**
142
     * Set view variables en masse
143
     *
144
     * Can be an array or a Traversable + ArrayAccess object.
145
     *
146
     * @param  array|ArrayAccess|Traversable $variables
147
     * @param  bool $overwrite Whether or not to overwrite the internal container with $variables
148
     * @throws \InvalidArgumentException
149
     * @return self
150
     */
151
    public function setVariables($variables, $overwrite = false)
152
    {
153
        if (!is_array($variables) && !$variables instanceof Traversable) {
0 ignored issues
show
Bug introduced by
The class Core\Mail\Traversable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
154
            throw \InvalidArgumentException(
155
                sprintf(
156
                    '%s: expects an array, or Traversable argument; received "%s"',
157
                    __METHOD__,
158
                    (is_object($variables) ? get_class($variables) : gettype($variables))
159
                )
160
            );
161
        }
162
163
        if ($overwrite) {
164
            if (is_object($variables) && !$variables instanceof ArrayAccess) {
0 ignored issues
show
Bug introduced by
The class Core\Mail\ArrayAccess does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
165
                $variables = ArrayUtils::iteratorToArray($variables);
166
            }
167
168
            $this->variables = $variables;
169
            return $this;
170
        }
171
172
        foreach ($variables as $key => $value) {
173
            $this->setVariable($key, $value);
174
        }
175
176
        return $this;
177
    }
178
179
    /**
180
     * Get view variables
181
     *
182
     * @return array|ArrayAccess|Traversable
183
     */
184
    public function getVariables()
185
    {
186
        return $this->variables;
187
    }
188
189
    /**
190
     * Clear all variables
191
     *
192
     * Resets the internal variable container to an empty container.
193
     *
194
     * @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...
195
     */
196
    public function clearVariables()
197
    {
198
        $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...
199
        return $this;
200
    }
201
202
    /**
203
     *
204
     *
205
     * @param $template
206
     *
207
     * @return self
208
     */
209
    public function setTemplate($template)
210
    {
211
        $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...
212
        return $this;
213
    }
214
215
    public function getTemplate()
216
    {
217
        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...
218
    }
219
220
    /**
221
     * @example /module/Jobs/src/Jobs/Listener/PortalListener.php
222
     * @return string
223
     * @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
224
     */
225
    public function getBodyText()
226
    {
227
        $viewModel    = new ViewModel();
228
        $response     = new Response();
229
        $body         = parent::getBodyText();
230
        if (!empty($body)) {
231
            throw new \InvalidArgumentException('mail body shall come from Template.');
232
        }
233
234
        /* @var \Core\Mail\MailService $services */
235
        $services = $this->getServiceLocator();
236
        /* @var \Zend\Mvc\View\Http\ViewManager $viewManager */
237
        $viewManager  = $services->getServiceLocator()->get('viewManager');
238
        $resolver = $viewManager->getResolver();
239
240
        /* @var \Zend\ServiceManager\AbstractPluginManager $serviceLocator */
241
        /* @var \Zend\Mvc\MvcEvent $event */
242
        $event = $services->getServiceLocator()->get('application')->getMvcEvent();
243
        $lang = $event->getRouteMatch()->getParam('lang');
244
245
246
        if ($resolver->resolve($this->getTemplate() . '.' . $lang)) {
247
            $viewModel->setTemplate($this->getTemplate() . '.' . $lang);
248
        }else{
249
            $viewModel->setTemplate($this->getTemplate());
250
        }
251
252
        $view         = $viewManager->getView();
253
254
        $viewModel->setVariables($this->getVariables());
255
        $view->setResponse($response);
256
        $view->render($viewModel);
257
        $body = $response->getContent();
258
259
        return $body;
260
    }
261
}
262