HasImage::addImage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 7
nc 2
nop 3
1
<?php
2
namespace CbCaio\ImgAttacher\Traits;
3
4
use CbCaio\ImgAttacher\Models\AttacherImage;
5
use Symfony\Component\HttpFoundation\File\UploadedFile;
6
7
trait HasImage
8
{
9
    /**
10
     * @return \Illuminate\Database\Eloquent\Relations\MorphOne
11
     */
12
    public function image()
13
    {
14
        return $this->morphOne(config('img-attacher.model'), 'owner');
0 ignored issues
show
Bug introduced by
It seems like morphOne() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
15
    }
16
17
    /**
18
     * @param UploadedFile $imageFile
19
     * @param string       $processing_style_routine
20
     * @param string       $filename
21
     * @return \Illuminate\Database\Eloquent\Model
22
     */
23
    public function addImage(UploadedFile $imageFile, $processing_style_routine = NULL, $filename = NULL)
24
    {
25
        $this->hasImage()
26
            ? $attacherImage = $this->getImage()
27
            : $attacherImage = $this->createAttacherImageModel();
28
29
        $attacherImage->setAttributesFromFile($imageFile, $filename);
30
        $attacherImage->setProcessingStyleRoutine($processing_style_routine);
31
32
        return $this->image()->save($attacherImage);
33
    }
34
35
    /**
36
     * @return bool
37
     */
38
    public function deleteImage()
39
    {
40
        if ($this->hasImage())
41
        {
42
            $this->getImage()->delete();
43
44
            return TRUE;
45
        } else
46
        {
47
            return FALSE;
48
        }
49
    }
50
51
    /**
52
     * @return AttacherImage
53
     */
54
    public function getImage()
55
    {
56
        $image = $this->image()->getResults();
57
58
        return empty($image) ? NULL : $image;
59
    }
60
61
    /**
62
     * @return bool
63
     */
64
    public function hasImage()
65
    {
66
        return !is_null($this->getImage());
67
    }
68
69
    /**
70
     * @return AttacherImage
71
     */
72
    protected function createAttacherImageModel()
73
    {
74
        return $this->image()->getRelated()->newInstance();
75
    }
76
}