| Conditions | 7 |
| Paths | 6 |
| Total Lines | 54 |
| Code Lines | 39 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 1 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 74 | public function add() |
||
| 75 | { |
||
| 76 | $submitted = $this->request->getData('upload.0.file'); |
||
| 77 | if ( |
||
| 78 | !($submitted instanceof UploadedFileInterface) |
||
| 79 | || $submitted->getError() !== UPLOAD_ERR_OK |
||
| 80 | ) { |
||
| 81 | throw new GenericApiException(__d('image_uploader', 'add.failure')); |
||
| 82 | } |
||
| 83 | |||
| 84 | $userId = (int)$this->getRequest()->getData('userId'); |
||
| 85 | /** @var \App\Model\Entity\User $user */ |
||
| 86 | $user = $this->Users->get($userId); |
||
| 87 | $permission = $this->CurrentUser->permission( |
||
| 88 | 'saito.plugin.uploader.add', |
||
| 89 | (new ResourceAI())->onRole($user->getRole())->onOwner($user->getId()) |
||
| 90 | ); |
||
| 91 | if (!$permission) { |
||
| 92 | throw new SaitoForbiddenException( |
||
| 93 | sprintf('Attempt to add uploads for "%s".', $userId), |
||
| 94 | ['CurrentUser' => $this->CurrentUser] |
||
| 95 | ); |
||
| 96 | } |
||
| 97 | |||
| 98 | $filename = $submitted->getClientFilename(); |
||
| 99 | $parts = explode('.', $filename); |
||
| 100 | if (count($parts) < 2) { |
||
| 101 | throw new GenericApiException(__d('image_uploader', 'add.failure.noext')); |
||
| 102 | } |
||
| 103 | $ext = array_pop($parts); |
||
| 104 | $name = $this->CurrentUser->getId() . |
||
| 105 | '_' . |
||
| 106 | substr(Security::hash($filename, 'sha256'), 32) . |
||
| 107 | '.' . |
||
| 108 | $ext; |
||
| 109 | $filepath = $submitted->getStream()->getMetadata('uri'); |
||
| 110 | $data = [ |
||
| 111 | 'tmp_name' => $filepath, |
||
| 112 | 'name' => $name, |
||
| 113 | 'title' => $filename, |
||
| 114 | 'type' => MimeType::get($filepath, $name), |
||
| 115 | 'size' => filesize($filepath), |
||
| 116 | 'user_id' => $userId, |
||
| 117 | ]; |
||
| 118 | $document = $this->Uploads->newEntity($data); |
||
| 119 | |||
| 120 | $entity = $this->Uploads->save($document); |
||
| 121 | if (!$entity) { |
||
| 122 | $errors = $document->getErrors(); |
||
| 123 | $msg = $errors ? current(current($errors)) : null; |
||
| 124 | throw new GenericApiException($msg); |
||
| 125 | } |
||
| 126 | |||
| 127 | $this->set('image', $document); |
||
| 128 | } |
||
| 162 |