Completed
Push — develop ( 09456b...2094a2 )
by Mathias
21s queued 16s
created

FileController::factory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
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
 */
9
10
/** FileController.php */
11
namespace Core\Controller;
12
13
use Core\EventManager\EventManager;
14
use Core\Listener\Events\FileEvent;
15
use Core\Repository\RepositoryService;
16
use Interop\Container\ContainerInterface;
17
use Organizations\Entity\OrganizationImage;
18
use Zend\Mvc\Controller\AbstractActionController;
19
use Zend\View\Model\JsonModel;
20
use Zend\Mvc\MvcEvent;
21
use Core\Entity\PermissionsInterface;
22
23
/**
24
 * Class FileController
25
 *
26
 * @method \Acl\Controller\Plugin\Acl acl()
27
 * @package Core\Controller
28
 */
29
class FileController extends AbstractActionController
30
{
31
	/**
32
	 * @var RepositoryService
33
	 */
34
	private $repositories;
35
	
36
	/**
37
	 * @var EventManager
38
	 */
39
	private $coreFileEvents;
40
	
41
	public function __construct(
42
		RepositoryService $repositories,
43
		EventManager $eventManager
44
	)
45
	{
46
		$this->repositories = $repositories;
47
		$this->coreFileEvents = $eventManager;
48
	}
49
	
50
	
51
	protected function attachDefaultListeners()
52
    {
53
        parent::attachDefaultListeners();
54
        $events = $this->getEventManager();
55
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'), 10);
56
    }
57
58
    public function preDispatch(MvcEvent $e)
59
    {
60
        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...
61
            $routeMatch = $e->getRouteMatch();
62
            $routeMatch->setParam('action', 'delete');
63
        }
64
    }
65
66
    /**
67
     * @return null|object
68
     */
69
    protected function getFile()
70
    {
71
        $fileStoreName = $this->params('filestore');
72
        list($module, $entityName) = explode('.', $fileStoreName);
73
        $response      = $this->getResponse();
74
75
        try {
76
            $repository = $this->repositories->get($module . '/' . $entityName);
77
        } catch (\Exception $e) {
78
            $response->setStatusCode(404);
79
            $this->getEvent()->setParam('exception', $e);
80
            return null;
81
        }
82
        $fileId = $this->params('fileId', 0);
83
        if (preg_match('/^(.*)\..*$/', $fileId, $baseFileName)) {
84
            $fileId = $baseFileName[1];
85
        }
86
        $file       = $repository->find($fileId);
87
                
88
        if (!$file) {
89
            $response->setStatusCode(404);
90
        }
91
        return $file;
92
    }
93
94
    /**
95
     * @return \Zend\Http\PhpEnvironment\Response
96
     */
97
    public function indexAction()
98
    {
99
        /* @var \Zend\Http\PhpEnvironment\Response $response */
100
        $response = $this->getResponse();
101
        /* @var \Core\Entity\FileEntity $file */
102
        $file     = $this->getFile();
103
        
104
        if (!$file) {
105
            return $response;
106
        }
107
        
108
        $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...
109
110
        $headers=$response->getHeaders();
111
112
        $headers->addHeaderline('Content-Type', $file->getType())
113
            ->addHeaderline('Content-Length', $file->getLength());
114
115
        if ($file instanceof OrganizationImage) {
116
            $expireDate = new \DateTime();
117
            $expireDate->add(new \DateInterval('P1Y'));
118
119
//            $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...
120
//                ->addHeaderLine('ETag', $file->getId())
121
//                ->addHeaderline('Cache-Control', 'public')
122
//                ->addHeaderline('Pragma', 'cache');
123
        }
124
125
        $response->sendHeaders();
126
        
127
        $resource = $file->getResource();
128
        
129
        while (!feof($resource)) {
130
            echo fread($resource, 1024);
131
        }
132
        return $response;
133
    }
134
    
135
    public function deleteAction()
136
    {
137
        $file = $this->getFile();
138
        if (!$file) {
139
            $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...
140
            $message = ($ex = $this->getEvent()->getParam('exception')) ? $ex->getMessage() : 'File not found.';
141
            return new JsonModel(
142
                array(
143
                    'result' => false,
144
                    'message' => $message
145
                )
146
            );
147
        }
148
        
149
        $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...
150
151
152
        /* @var \Core\EventManager\EventManager $events */
153
        $events = $this->coreFileEvents;
154
        $event = $events->getEvent(FileEvent::EVENT_DELETE, $this, ['file' => $file]);
155
        $results = $events->triggerEventUntil(function($r) { return true === $r; }, $event);
156
157
        if (true !== $results->last()) {
158
            $this->repositories->remove($file);
159
        }
160
161
        return new JsonModel(
162
            array(
163
            'result' => true
164
            )
165
        );
166
    }
167
}
168