Completed
Pull Request — develop (#359)
by Mathias
23:51
created

FileController::deleteAction()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 19
nc 3
nop 0
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** FileController.php */
11
namespace Core\Controller;
12
13
use Core\Listener\Events\FileEvent;
14
use Organizations\Entity\OrganizationImage;
15
use Zend\Mvc\Controller\AbstractActionController;
16
use Zend\View\Model\JsonModel;
17
use Zend\Mvc\MvcEvent;
18
use Core\Entity\PermissionsInterface;
19
20
/**
21
 * Class FileController
22
 *
23
 * @method \Acl\Controller\Plugin\Acl acl()
24
 * @package Core\Controller
25
 */
26
class FileController extends AbstractActionController
27
{
28 View Code Duplication
    protected function attachDefaultListeners()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
29
    {
30
        parent::attachDefaultListeners();
31
        $events = $this->getEventManager();
32
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
33
34
        $serviceLocator  = $this->serviceLocator;
35
        $defaultServices = $serviceLocator->get('DefaultListeners');
36
        $events->attach($defaultServices);
0 ignored issues
show
Documentation introduced by
$defaultServices is of type object|array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
37
    }
38
39
    public function preDispatch(MvcEvent $e)
40
    {
41
        if ('delete' == $this->params()->fromQuery('do') && $this->getRequest()->isXmlHttpRequest()) {
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 isXmlHttpRequest() 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...
42
            $routeMatch = $e->getRouteMatch();
43
            $routeMatch->setParam('action', 'delete');
44
        }
45
    }
46
47
    protected function getFile()
48
    {
49
        $fileStoreName = $this->params('filestore');
50
        list($module, $entityName) = explode('.', $fileStoreName);
51
        $response      = $this->getResponse();
52
53
        try {
54
            $repository = $this->serviceLocator->get('repositories')->get($module . '/' . $entityName);
55
        } catch (\Exception $e) {
56
            $response->setStatusCode(404);
57
            $this->getEvent()->setParam('exception', $e);
58
            return;
59
        }
60
        $fileId = $this->params('fileId', 0);
61
        if (preg_match('/^(.*)\..*$/', $fileId, $baseFileName)) {
62
            $fileId = $baseFileName[1];
63
        }
64
        $file       = $repository->find($fileId);
65
                
66
        if (!$file) {
67
            $response->setStatusCode(404);
68
        }
69
        return $file;
70
    }
71
72
    /**
73
     * @return \Zend\Http\PhpEnvironment\Response
74
     */
75
    public function indexAction()
76
    {
77
        /* @var \Zend\Http\PhpEnvironment\Response $response */
78
        $response = $this->getResponse();
79
        /* @var \Core\Entity\FileEntity $file */
80
        $file     = $this->getFile();
81
        
82
        if (!$file) {
83
            return $response;
84
        }
85
        
86
        $this->acl($file);
0 ignored issues
show
Unused Code introduced by
The call to FileController::acl() has too many arguments starting with $file.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
87
88
        $headers=$response->getHeaders();
89
90
        $headers->addHeaderline('Content-Type', $file->getType())
91
            ->addHeaderline('Content-Length', $file->getLength());
92
93
        if ($file instanceof OrganizationImage) {
94
            $expireDate = new \DateTime();
95
            $expireDate->add(new \DateInterval('P1Y'));
96
97
//            $headers->addHeaderline('Expires', $expireDate->format(\DateTime::W3C))
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
98
//                ->addHeaderLine('ETag', $file->getId())
99
//                ->addHeaderline('Cache-Control', 'public')
100
//                ->addHeaderline('Pragma', 'cache');
101
        }
102
103
        $response->sendHeaders();
104
        
105
        $resource = $file->getResource();
106
        
107
        while (!feof($resource)) {
108
            echo fread($resource, 1024);
109
        }
110
        return $response;
111
    }
112
    
113
    public function deleteAction()
114
    {
115
        $file = $this->getFile();
116
        if (!$file) {
117
            $this->response->setStatusCode(500);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\ResponseInterface as the method setStatusCode() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Response, Zend\Http\Response, Zend\Http\Response\Stream.

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...
118
            return new JsonModel(
119
                array(
120
                'result' => false,
121
                'message' => ($ex = $this->getEvent()->getParam('exception'))
122
                             ? $ex->getMessage()
123
                             : 'File not found.'
124
                )
125
            );
126
        }
127
        
128
        $this->acl($file, PermissionsInterface::PERMISSION_CHANGE);
0 ignored issues
show
Unused Code introduced by
The call to FileController::acl() has too many arguments starting with $file.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
129
130
131
        /* @var \Core\EventManager\EventManager $events */
132
        $events = $this->serviceLocator->get('Core/File/Events');
133
        $event = $events->getEvent(FileEvent::EVENT_DELETE, $this, ['file' => $file]);
134
        $results = $events->triggerEventUntil(function($r) { return true === $r; }, $event);
135
136
        if (true !== $results->last()) {
137
            $this->serviceLocator->get('repositories')->remove($file);
138
        }
139
140
        return new JsonModel(
141
            array(
142
            'result' => true
143
            )
144
        );
145
    }
146
}
147