Completed
Push — master ( 7ee924...bdf75d )
by Philippe
01:35
created

AssetTrait::normalizeLocale()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 1
cts 1
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 3
1
<?php
2
3
namespace Thinktomorrow\AssetLibrary\Traits;
4
5
use Illuminate\Support\Collection;
6
use Thinktomorrow\AssetLibrary\Models\Asset;
7
use Thinktomorrow\Locale\Locale;
8
9
trait AssetTrait
10
{
11 20
    public function assets()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
12
    {
13 20
        return $this->morphToMany(Asset::class, 'entity', 'asset_pivots')->withPivot('type', 'locale');
0 ignored issues
show
Bug introduced by
It seems like morphToMany() 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...
14
    }
15
16 4
    public function hasFile($type = '', $locale = '')
17
    {
18 4
        $filename = $this->getFilename($type, $locale);
19
20 4
        return (bool) $filename and basename($filename) != 'other.png';
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
21
    }
22
23 6
    public function getFilename($type = '', $locale = '')
24
    {
25 6
        return basename($this->getFileUrl($type, '', $locale));
26
    }
27
28 18
    /**
29
     * @param string $locale
0 ignored issues
show
Documentation introduced by
Should the type for parameter $locale not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
30 18
     *
31 2
     * @return string
32
     */
33
    public function getFileUrl($type = '', $size = '', $locale = null)
34 18
    {
35 14
        if ($this->assets->first() === null || $this->assets->first()->pivot === null) {
0 ignored issues
show
Bug introduced by
The property assets does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
36
            return;
37
        }
38 18
39 18
        if (! $locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
40 5
            $locale = Locale::getDefault();
41
        }
42
43 18
        $assets = $this->assets->where('pivot.type', $type);
44 1
        if ($assets->count() > 1) {
45
            $assets = $assets->where('pivot.locale', $locale);
46
        }
47 18
48
        if ($assets->isEmpty()) {
49
            return;
50
        }
51
52
        return $assets->first()->getFileUrl($size);
53
    }
54
55
    /**
56
     * Adds a file to this model, accepts a type and locale to be saved with the file.
57 12
     *
58
     * @param $file
59 12
     * @param $type
60
     * @param string $locale
0 ignored issues
show
Documentation introduced by
Should the type for parameter $locale not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
61 12
     */
62
    public function addFile($file, $type = '', $locale = null)
63 12
    {
64 3
        $locale = $this->normalizeLocale($locale);
65
66 9
        $asset = Asset::upload($file);
67
68 12
        if ($asset instanceof Collection) {
69
            $asset->each->attachToModel($this, $type, $locale);
70
        } else {
71
            $asset->attachToModel($this, $type, $locale);
72 1
        }
73 1
    }
74 1
75
    public function getAllImages()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
76 1
    {
77
        $images = $this->assets->filter(function ($asset) {
78
            return $asset->getExtensionForFilter() == 'image';
79 1
        });
80
81 1
        return $images;
82
    }
83 1
84
    public function getAllFiles($type = null, $locale = '')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
85 1
    {
86
        $locale = $this->normalizeLocale($locale);
87
88 12
        $files = $this->assets->where('pivot.type', $type)->where('pivot.locale', $locale);
89
90 12
        return $files;
91 8
    }
92
93 12
    private function normalizeLocale($locale)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
94
    {
95
        if ($locale == '' || $locale == null) {
96
            $locale = Locale::getDefault();
97
        }
98
        return $locale;
99
    }
100
}
101