Completed
Push — develop ( 23ca22...2abfdd )
by
unknown
16:23 queued 09:00
created

FileController::getFile()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
rs 8.6845
cc 4
eloc 17
nc 5
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 Organizations\Entity\OrganizationImage;
14
use Zend\Mvc\Controller\AbstractActionController;
15
use Auth\Exception\UnauthorizedImageAccessException;
16
use Auth\Exception\UnauthorizedAccessException;
17
use Zend\View\Model\JsonModel;
18
use Zend\Mvc\MvcEvent;
19
use Core\Entity\PermissionsInterface;
20
21
/**
22
 * Class FileController
23
 *
24
 * @method \Acl\Controller\Plugin\Acl acl()
25
 * @package Core\Controller
26
 */
27
class FileController extends AbstractActionController
28
{
29 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...
30
    {
31
        parent::attachDefaultListeners();
32
        $events = $this->getEventManager();
33
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
34
35
        $serviceLocator  = $this->getServiceLocator();
36
        $defaultServices = $serviceLocator->get('DefaultListeners');
37
        $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...
38
    }
39
40
    public function preDispatch(MvcEvent $e)
41
    {
42
        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...
43
            $routeMatch = $e->getRouteMatch();
44
            $routeMatch->setParam('action', 'delete');
45
        }
46
    }
47
48
    protected function getFile()
49
    {
50
        $fileStoreName = $this->params('filestore');
51
        list($module, $entityName) = explode('.', $fileStoreName);
52
        $response      = $this->getResponse();
53
        
54
        try {
55
            $repository = $this->getServiceLocator()->get('repositories')->get($module . '/' . $entityName);
56
        } catch (\Exception $e) {
57
            $response->setStatusCode(404);
58
            $this->getEvent()->setParam('exception', $e);
59
            return;
60
        }
61
        $fileId = $this->params('fileId', 0);
62
        if (preg_match('/^(.*)\..*$/', $fileId, $baseFileName)) {
63
            $fileId = $baseFileName[1];
64
        }
65
        $file       = $repository->find($fileId);
66
                
67
        if (!$file) {
68
            $response->setStatusCode(404);
69
        }
70
        return $file;
71
    }
72
73
    /**
74
     * @return \Zend\Http\PhpEnvironment\Response
75
     */
76
    public function indexAction()
77
    {
78
        /* @var \Zend\Http\PhpEnvironment\Response $response */
79
        $response = $this->getResponse();
80
        /* @var \Core\Entity\FileEntity $file */
81
        $file     = $this->getFile();
82
        
83
        if (!$file) {
84
            return $response;
85
        }
86
        
87
        $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...
88
89
        $headers=$response->getHeaders();
90
91
        $headers->addHeaderline('Content-Type', $file->getType())
92
            ->addHeaderline('Content-Length', $file->getLength());
93
94
        if ($file instanceof OrganizationImage) {
95
            $expireDate = new \DateTime();
96
            $expireDate->add(new \DateInterval('P1Y'));
97
98
            $headers->addHeaderline('Expires', $expireDate->format(\DateTime::W3C))
99
                      ->addHeaderLine('ETag', $file->getId())
100
                      ->addHeaderline('Cache-Control', 'public')
101
                      ->addHeaderline('Pragma', 'cache');
102
        }
103
104
        $response->sendHeaders();
105
        
106
        $resource = $file->getResource();
107
        
108
        while (!feof($resource)) {
109
            echo fread($resource, 1024);
110
        }
111
        return $response;
112
    }
113
    
114
    public function deleteAction()
115
    {
116
        $file = $this->getFile();
117
        if (!$file) {
118
            $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...
119
            return new JsonModel(
120
                array(
121
                'result' => false,
122
                'message' => ($ex = $this->getEvent()->getParam('exception'))
123
                             ? $ex->getMessage()
124
                             : 'File not found.'
125
                )
126
            );
127
        }
128
        
129
        $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...
130
        $this->getServiceLocator()->get('repositories')->remove($file);
131
        return new JsonModel(
132
            array(
133
            'result' => true
134
            )
135
        );
136
    }
137
}
138