ContactController::sendEmail()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 1
1
<?php
2
/**
3
 * Copyright (c) 2011-2012 Andreas Heigl<[email protected]>
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a copy
6
 * of this software and associated documentation files (the "Software"), to deal
7
 * in the Software without restriction, including without limitation the rights
8
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the Software is
10
 * furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included in
13
 * all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 *
23
 * @category  ContactForm
24
 * @package   HeiglContact
25
 * @author    Andreas Heigl<[email protected]>
26
 * @copyright 2011-2012 Andreas Heigl
27
 * @license   http://www.opesource.org/licenses/mit-license.php MIT-License
28
 * @version   0.0
29
 * @since     06.03.2012
30
 * @link      http://github.com/heiglandreas/php.ug
31
 */
32
33
namespace Org_Heigl\Contact\Controller;
34
35
36
use Zend\Mvc\Controller\AbstractActionController;
37
use Zend\Mail\Transport\TransportInterface;
38
use Org_Heigl\Contact\Form\ContactForm;
39
use Zend\Mail\Message as Message;
40
use Zend\View\Model\ViewModel;
41
42
/**
43
 * The Contact-Form Controller
44
 *
45
 * @category  ContactForm
46
 * @package   OrgHeiglContact
47
 * @author    Andreas Heigl<[email protected]>
48
 * @copyright 2011-2012 Andreas Heigl
49
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
50
 * @version   0.0
51
 * @since     06.03.2012
52
 * @link      http://github.com/heiglandreas/OrgHeiglContact
53
 */
54
class ContactController extends AbstractActionController
55
{
56
    /**
57
     * THe storage of the form-object
58
     *
59
     * @var ContactForm $form
60
     */
61
    protected $form;
62
63
    /**
64
     * Storage of the message
65
     *
66
     * @var Message $message
67
     */
68
    protected $message = null;
69
70
    /**
71
     * Storage of the default transport
72
     *
73
     * @var Transport $transport
74
     */
75
    protected $transport = null;
76
77
    /**
78
     * Create the Controller-Instance
79
     * 
80
     * @param ContactForm $form
81
     */
82
    public function __construct(ContactForm $form = null)
83
    {
84
        if (null !== $form) {
85
             $this->setContactForm($form);
86
        }
87
    }
88
89
    /**
90
     * Set the default message
91
     *
92
     * @param Message $message the message to set as default
93
     *
94
     * @return ContactController
95
     */
96
    public function setMessage(Message $message)
97
    {
98
        $this->message = $message;
99
        return $this;
100
    }
101
102
    /**
103
     * Set the default transport
104
     *
105
     * @param Transport $transport The transport to set as default
106
     *
107
     * @return ContactController
108
     */
109
    public function setTransport(TransportInterface $transport)
110
    {
111
        $this->transport = $transport;
0 ignored issues
show
Documentation Bug introduced by
It seems like $transport of type object<Zend\Mail\Transport\TransportInterface> is incompatible with the declared type object<Org_Heigl\Contact\Controller\Transport> of property $transport.

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...
112
        return $this;
113
    }
114
115
    /**
116
     * Set the given form as contact-form
117
     *
118
     * @param ContactForm $form
0 ignored issues
show
Bug introduced by
There is no parameter named $form. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
119
     *
120
     * @return ContactController
121
     */
122
    public function setContactForm(ContactForm $contactForm)
123
    {
124
        $this->form = $contactForm;
125
        $this->form->init();
126
        return $this;
127
    }
128
129
    /**
130
     * Display a contact-form
131
     *
132
     * @return void
133
     */
134
    public function indexAction()
135
    {
136
        return array('form' => $this->form);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array('form' => $this->form); (array<string,Org_Heigl\Contact\Form\ContactForm>) is incompatible with the return type of the parent method Zend\Mvc\Controller\Abst...Controller::indexAction of type Zend\View\Model\ViewModel.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
137
    }
138
139
    /**
140
     * Process the form
141
     *
142
     * @return void
143
     */
144
    public function processAction()
145
    {
146
        if (!$this->request->isPost()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
147
            return $this->redirect()->toRoute('contact');
148
        }
149
        $post = $this->request->getPost();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method getPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
150
        $form = $this->form;
151
        $form->setData($post);
152
        if (!$form->isValid()) {
153
            $view = new ViewModel(array(
154
                        'error' => true,
155
                        'form'  => $form
156
            ));
157
            $view->setTemplate('org_heigl/contact/contact/index');
158
            return $view;
159
        }
160
161
        // send email...
162
        $this->sendEmail($form->getData());
163
164
        return $this->redirect()->toRoute('contact/thank-you');
165
    }
166
167
    /**
168
     * Send the email
169
     *
170
     * @param array $params The parameters to include in the email
0 ignored issues
show
Bug introduced by
There is no parameter named $params. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
171
     *
172
     * @return boolean
173
     */
174
    protected function sendEmail($values)
175
    {
176
        $from    = $values['from'];
177
        $subject = '[Contact Form] ' . $values['subject'];
178
        $body    = $values['body'];
179
180
        $this->message->addFrom($from)
181
                      ->addReplyTo($from)
182
                      ->setSubject($subject)
183
                      ->setBody($body);
184
        $this->transport->send($this->message);
185
    }
186
187
    /**
188
     * Display a thank-you message
189
     *
190
     * @return void
191
     */
192
    public function thankYouAction()
193
    {
194
        $headers = $this->request->getHeaders();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method getHeaders() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
195
        if (!$headers->has('Referer')
196
            || !preg_match('#/contact$#',
197
        $headers->get('Referer')->getFieldValue())
198
        ) {
199
            return $this->redirect()->toRoute('contact');
200
        }
201
202
        return array();
203
204
    }
205
}
206