Completed
Push — develop ( 4bd203...a628f2 )
by
unknown
08:09
created

HTMLTemplateMessage::renderBodyText()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 8.439
c 0
b 0
f 0
cc 5
eloc 22
nc 4
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\Mail;
12
13
use Zend\Mail\Header;
14
use Zend\Mail\Headers;
15
use Zend\ServiceManager\ServiceLocatorInterface;
16
use Zend\View\Model\ViewModel;
17
use Zend\Stdlib\Response;
18
use Zend\View\Variables as ViewVariables;
19
use Zend\Stdlib\ArrayUtils;
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
    protected $renderedBody;
40
41
    /**
42
     * @param ServiceLocatorInterface $serviceManager
43
     * @param array $options
44
     */
45
    public function __construct(ServiceLocatorInterface $serviceManager, array $options = array())
46
    {
47
        // @TODO make this multipart
48
        parent::__construct($options);
49
        $this->serviceManager = $serviceManager;
50
        $this->getHeaders()->addHeader(Header\ContentType::fromString('Content-Type: text/html; charset=UTF-8'));
51
        $this->setEncoding('UTF-8');
52
        $this->variables = new ViewVariables();
53
    }
54
55
    /**
56
     * Property overloading: set variable value
57
     *
58
     * @param  string $name
59
     * @param  mixed $value
60
     * @return void
61
     */
62
    public function __set($name, $value)
63
    {
64
        $this->setVariable($name, $value);
65
    }
66
67
    /**
68
     * Property overloading: get variable value
69
     *
70
     * @param  string $name
71
     * @return mixed
72
     */
73
    public function __get($name)
74
    {
75
        if (!$this->__isset($name)) {
76
            return null;
77
        }
78
79
        $variables = $this->getVariables();
80
        return $variables[$name];
81
    }
82
83
    /**
84
     * Property overloading: do we have the requested variable value?
85
     *
86
     * @param  string $name
87
     * @return bool
88
     */
89
    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...
90
    {
91
        $variables = $this->getVariables();
92
        return isset($variables[$name]);
93
    }
94
95
    /**
96
     * Property overloading: unset the requested variable
97
     *
98
     * @param  string $name
99
     * @return void
100
     */
101
    public function __unset($name)
102
    {
103
        if ($this->__isset($name)) {
104
            unset($this->variables[$name]);
105
        }
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();
196
        return $this;
197
    }
198
199
    /**
200
     *
201
     * @param $template
202
     *
203
     * @return self
204
     */
205
    public function setTemplate($template)
206
    {
207
        $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...
208
        return $this;
209
    }
210
211
    public function getTemplate()
212
    {
213
        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...
214
    }
215
216
    /**
217
     * @example /module/Jobs/src/Jobs/Listener/PortalListener.php
218
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

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...
219
     * @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
220
     */
221
    public function renderBodyText($force = true)
222
    {
223
        if (!$this->renderedBody || $force ) {
224
            $viewModel    = new ViewModel();
225
            $response     = new Response();
226
            $body         = parent::getBodyText();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getBodyText() instead of renderBodyText()). Are you sure this is correct? If so, you might want to change this to $this->getBodyText().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
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
            $viewModel->setVariable('mail', $this);
250
            $view->setResponse($response);
251
            $view->render($viewModel);
252
            $body = $response->getContent();
253
254
            $this->renderedBody = $body;
255
        }
256
    }
257
258
    public function getBodyText()
259
    {
260
        $this->renderBodyText();
261
        return $this->renderedBody;
262
    }
263
    
264
    /**
265
     * @param MailService $mailService
266
     * @return \Core\Mail\HTMLTemplateMessage
267
     */
268
    public static function factory(MailService $mailService)
269
    {
270
        return new static($mailService->getServiceLocator());
271
    }
272
}
273