Completed
Push — master ( 447585...6badc9 )
by Ryan
08:12
created

Image   F

Complexity

Total Complexity 151

Size/Duplication

Total Lines 1161
Duplicated Lines 5.94 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 151
c 4
b 0
f 1
lcom 1
cbo 12
dl 69
loc 1161
rs 3.0857

54 Methods

Rating   Name   Duplication   Size   Complexity  
B make() 0 23 4
A path() 0 6 1
A macro() 0 4 1
A url() 0 4 1
A img() 0 4 1
A picture() 0 21 3
A source() 0 12 3
A encode() 0 4 2
A __construct() 21 21 1
A image() 0 16 3
A data() 0 4 1
A output() 0 4 1
A rename() 0 4 1
A quality() 0 4 1
A width() 0 4 2
A height() 0 4 2
A setQuality() 0 6 1
B getCachePath() 0 18 5
C shouldPublish() 9 29 12
C publish() 0 49 14
A attr() 0 6 1
A srcset() 0 11 2
A srcsets() 7 21 4
B sources() 7 29 6
C agents() 7 26 14
C setImage() 18 51 10
C makeImage() 0 24 8
D dumpImage() 0 28 10
A getImage() 0 4 1
A getFilename() 0 4 1
A setFilename() 0 10 2
A getAlterations() 0 4 1
A setAlterations() 0 6 1
A addAlteration() 0 6 1
A getAttributes() 0 4 1
A setAttributes() 0 6 1
A addAttribute() 0 6 1
A getSrcsets() 0 4 1
A setSrcsets() 0 6 1
A getSources() 0 4 1
A setSources() 0 6 1
A getQuality() 0 8 3
A setOutput() 0 6 1
A getExtension() 0 4 1
A setExtension() 0 6 1
A getAllowedMethods() 0 4 1
A addPath() 0 6 1
A getWidth() 0 4 1
A setWidth() 0 6 1
A getHeight() 0 4 1
A setHeight() 0 6 1
B guessResizeArguments() 0 14 5
A __toString() 0 4 1
A __call() 0 19 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Image often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Image, and based on these observations, apply Extract Interface, too.

1
<?php namespace Anomaly\Streams\Platform\Image;
2
3
use Anomaly\FilesModule\File\Contract\FileInterface;
4
use Anomaly\FilesModule\File\FilePresenter;
5
use Anomaly\Streams\Platform\Addon\FieldType\FieldType;
6
use Anomaly\Streams\Platform\Application\Application;
7
use Anomaly\Streams\Platform\Routing\UrlGenerator;
8
use Closure;
9
use Collective\Html\HtmlBuilder;
10
use Illuminate\Contracts\Config\Repository;
11
use Illuminate\Filesystem\Filesystem;
12
use Intervention\Image\Constraint;
13
use Intervention\Image\ImageManager;
14
use League\Flysystem\File;
15
use League\Flysystem\MountManager;
16
use Mobile_Detect;
17
use Robbo\Presenter\Presenter;
18
19
/**
20
 * Class Image
21
 *
22
 * @link    http://anomaly.is/streams-platform
23
 * @author  AnomalyLabs, Inc. <[email protected]>
24
 * @author  Ryan Thompson <[email protected]>
25
 * @package Anomaly\Streams\Platform\Image
26
 */
27
class Image
28
{
29
30
    /**
31
     * The publish flag.
32
     *
33
     * @var bool
34
     */
35
    protected $publish = false;
36
37
    /**
38
     * The publishable base directory.
39
     *
40
     * @var null
41
     */
42
    protected $directory = null;
43
44
    /**
45
     * The image object.
46
     *
47
     * @var null|string
48
     */
49
    protected $image = null;
50
51
    /**
52
     * The file extension.
53
     *
54
     * @var null|string
55
     */
56
    protected $extension = null;
57
58
    /**
59
     * The desired filename.
60
     *
61
     * @var null|string
62
     */
63
    protected $filename = null;
64
65
    /**
66
     * The default output method.
67
     *
68
     * @var string
69
     */
70
    protected $output = 'url';
71
72
    /**
73
     * The image attributes.
74
     *
75
     * @var array
76
     */
77
    protected $attributes = [];
78
79
    /**
80
     * Applied alterations.
81
     *
82
     * @var array
83
     */
84
    protected $alterations = [];
85
86
    /**
87
     * Image srcsets.
88
     *
89
     * @var array
90
     */
91
    protected $srcsets = [];
92
93
    /**
94
     * Image sources.
95
     *
96
     * @var array
97
     */
98
    protected $sources = [];
99
100
    /**
101
     * Allowed methods.
102
     *
103
     * @var array
104
     */
105
    protected $allowedMethods = [
106
        'blur',
107
        'brightness',
108
        'colorize',
109
        'contrast',
110
        'crop',
111
        'encode',
112
        'fit',
113
        'flip',
114
        'gamma',
115
        'greyscale',
116
        'heighten',
117
        'insert',
118
        'invert',
119
        'limitColors',
120
        'pixelate',
121
        'opacity',
122
        'resize',
123
        'rotate',
124
        'amount',
125
        'widen',
126
        'orientate'
127
    ];
128
129
    /**
130
     * The quality of the output.
131
     *
132
     * @var null|int
133
     */
134
    protected $quality = null;
135
136
    /**
137
     * The image width.
138
     *
139
     * @var null|int
140
     */
141
    protected $width = null;
142
143
    /**
144
     * The image height.
145
     *
146
     * @var null|int
147
     */
148
    protected $height = null;
149
150
    /**
151
     * The URL generator.
152
     *
153
     * @var UrlGenerator
154
     */
155
    protected $url;
156
157
    /**
158
     * The HTML builder.
159
     *
160
     * @var HtmlBuilder
161
     */
162
    protected $html;
163
164
    /**
165
     * Image path hints by namespace.
166
     *
167
     * @var ImagePaths
168
     */
169
    protected $paths;
170
171
    /**
172
     * The image macros.
173
     *
174
     * @var ImageMacros
175
     */
176
    protected $macros;
177
178
    /**
179
     * The file system.
180
     *
181
     * @var Filesystem
182
     */
183
    protected $files;
184
185
    /**
186
     * The user agent utility.
187
     *
188
     * @var Mobile_Detect
189
     */
190
    protected $agent;
191
192
    /**
193
     * The config repository.
194
     *
195
     * @var Repository
196
     */
197
    protected $config;
198
199
    /**
200
     * The image manager.
201
     *
202
     * @var ImageManager
203
     */
204
    protected $manager;
205
206
    /**
207
     * The stream application.
208
     *
209
     * @var Application
210
     */
211
    protected $application;
212
213
    /**
214
     * Create a new Image instance.
215
     *
216
     * @param UrlGenerator  $url
217
     * @param HtmlBuilder   $html
218
     * @param Filesystem    $files
219
     * @param Mobile_Detect $agent
220
     * @param Repository    $config
221
     * @param ImageManager  $manager
222
     * @param Application   $application
223
     * @param ImagePaths    $paths
224
     * @param ImageMacros   $macros
225
     */
226 View Code Duplication
    public function __construct(
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...
227
        UrlGenerator $url,
228
        HtmlBuilder $html,
229
        Filesystem $files,
230
        Mobile_Detect $agent,
231
        Repository $config,
232
        ImageManager $manager,
233
        Application $application,
234
        ImagePaths $paths,
235
        ImageMacros $macros
236
    ) {
237
        $this->url         = $url;
238
        $this->html        = $html;
239
        $this->files       = $files;
240
        $this->agent       = $agent;
241
        $this->paths       = $paths;
242
        $this->config      = $config;
243
        $this->macros      = $macros;
244
        $this->manager     = $manager;
245
        $this->application = $application;
246
    }
247
248
    /**
249
     * Make a new image instance.
250
     *
251
     * @param mixed $image
252
     * @param null  $output
253
     * @return $this
254
     */
255
    public function make($image, $output = null)
256
    {
257
        if ($image instanceof Image) {
258
            return $image;
259
        }
260
261
        if ($output) {
262
            $this->setOutput($output);
263
        }
264
265
        $clone = clone($this);
266
267
        $clone->setAlterations([]);
268
        $clone->setSources([]);
269
        $clone->setSrcsets([]);
270
        $clone->setImage(null);
271
272
        try {
273
            return $clone->setImage($image);
274
        } catch (\Exception $e) {
275
            return $this;
276
        }
277
    }
278
279
    /**
280
     * Return the path to an image.
281
     *
282
     * @return string
283
     */
284
    public function path()
285
    {
286
        $path = $this->getCachePath();
287
288
        return $path;
289
    }
290
291
    /**
292
     * Run a macro on the image.
293
     *
294
     * @param $macro
295
     * @return Image
296
     * @throws \Exception
297
     */
298
    public function macro($macro)
299
    {
300
        return $this->macros->run($macro, $this);
301
    }
302
303
    /**
304
     * Return the URL to an image.
305
     *
306
     * @param array $parameters
307
     * @param null  $secure
308
     * @return string
309
     */
310
    public function url(array $parameters = [], $secure = null)
311
    {
312
        return $this->url->asset($this->path(), $parameters, $secure);
313
    }
314
315
    /**
316
     * Return the image tag to an image.
317
     *
318
     * @param null  $alt
319
     * @param array $attributes
320
     * @return string
321
     */
322
    public function image($alt = null, array $attributes = [])
323
    {
324
        if (!$alt) {
325
            $alt = array_get($this->getAttributes(), 'alt');
326
        }
327
328
        $attributes = array_merge($this->getAttributes(), $attributes);
329
330
        if ($srcset = $this->srcset()) {
331
            $attributes['srcset'] = $srcset;
332
        }
333
334
        $attributes['alt'] = $alt;
335
336
        return '<img src="' . $this->path() . '"' . $this->html->attributes($attributes) . '>';
337
    }
338
339
    /**
340
     * Return the image tag to an image.
341
     *
342
     * @param null  $alt
343
     * @param array $attributes
344
     * @return string
345
     */
346
    public function img($alt = null, array $attributes = [])
347
    {
348
        return $this->image($alt, $attributes);
349
    }
350
351
    /**
352
     * Return a picture tag.
353
     *
354
     * @return string
355
     */
356
    public function picture(array $attributes = [])
357
    {
358
        $sources = [];
359
360
        $attributes = array_merge($this->getAttributes(), $attributes);
361
362
        /* @var Image $image */
363
        foreach ($this->getSources() as $media => $image) {
364
            if ($media != 'fallback') {
365
                $sources[] = $image->source();
366
            } else {
367
                $sources[] = $image->image();
368
            }
369
        }
370
371
        $sources = implode("\n", $sources);
372
373
        $attributes = $this->html->attributes($attributes);
374
375
        return "<picture {$attributes}>\n{$sources}\n</picture>";
376
    }
377
378
    /**
379
     * Return a source tag.
380
     *
381
     * @return string
382
     */
383
    public function source()
384
    {
385
        $this->addAttribute('srcset', $this->srcset() ?: $this->path() . ' 2x, ' . $this->path() . ' 1x');
386
387
        $attributes = $this->html->attributes($this->getAttributes());
388
389
        if ($srcset = $this->srcset()) {
390
            $attributes['srcset'] = $srcset;
391
        }
392
393
        return "<source {$attributes}>";
394
    }
395
396
    /**
397
     * Return the image response.
398
     *
399
     * @param null $format
400
     * @param int  $quality
401
     * @return String
402
     */
403
    public function encode($format = null, $quality = null)
404
    {
405
        return $this->manager->make($this->getCachePath())->encode($format, $quality ?: $this->getQuality());
406
    }
407
408
    /**
409
     * Return the image contents.
410
     *
411
     * @return string
412
     */
413
    public function data()
414
    {
415
        return $this->dumpImage();
416
    }
417
418
    /**
419
     * Return the output.
420
     *
421
     * @return string
422
     */
423
    public function output()
424
    {
425
        return $this->{$this->output}();
426
    }
427
428
    /**
429
     * Set the filename.
430
     *
431
     * @param $filename
432
     * @return $this
433
     */
434
    public function rename($filename = null)
435
    {
436
        return $this->setFilename($filename);
437
    }
438
439
    /**
440
     * Set the quality.
441
     *
442
     * @param $quality
443
     * @return $this
444
     */
445
    public function quality($quality)
446
    {
447
        return $this->setQuality($quality);
448
    }
449
450
    /**
451
     * Set the width attribute.
452
     *
453
     * @param null $width
454
     * @return Image
455
     */
456
    public function width($width = null)
457
    {
458
        return $this->addAttribute('width', $width ?: $this->getWidth());
459
    }
460
461
    /**
462
     * Set the height attribute.
463
     *
464
     * @param null $height
465
     * @return Image
466
     */
467
    public function height($height = null)
468
    {
469
        return $this->addAttribute('height', $height ?: $this->getHeight());
470
    }
471
472
    /**
473
     * Set the quality.
474
     *
475
     * @param $quality
476
     * @return $this
477
     */
478
    public function setQuality($quality)
479
    {
480
        $this->quality = (int)$quality;
481
482
        return $this;
483
    }
484
485
    /**
486
     * Get the cache path of the image.
487
     *
488
     * @return string
489
     */
490
    protected function getCachePath()
491
    {
492
        if (starts_with($this->getImage(), ['http://', 'https://', '//'])) {
493
            return $this->getImage();
494
        }
495
496
        $path = $this->paths->outputPath($this);
497
498
        try {
499
            if ($this->shouldPublish($path)) {
500
                $this->publish($path);
501
            }
502
        } catch (\Exception $e) {
503
            return $this->config->get('app.debug', false) ? $e->getMessage() : null;
504
        }
505
506
        return $this->paths->prefix() . $path;
507
    }
508
509
    /**
510
     * Determine if the image needs to be published
511
     *
512
     * @param $path
513
     * @return bool
514
     */
515
    private function shouldPublish($path)
516
    {
517
        $path = ltrim($path, '/');
518
519
        if (!$this->files->exists($path)) {
520
            return true;
521
        }
522
523 View Code Duplication
        if (is_string($this->image) && !str_is('*://*', $this->image) && filemtime($path) < filemtime($this->image)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
524
            return true;
525
        }
526
527 View Code Duplication
        if (is_string($this->image) && str_is('*://*', $this->image) && filemtime($path) < app(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
528
                'League\Flysystem\MountManager'
529
            )->getTimestamp($this->image)
530
        ) {
531
            return true;
532
        }
533
534
        if ($this->image instanceof File && filemtime($path) < $this->image->getTimestamp()) {
535
            return true;
536
        }
537
538
        if ($this->image instanceof FileInterface && filemtime($path) < $this->image->lastModified()->format('U')) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\Contract\FileInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
539
            return true;
540
        }
541
542
        return false;
543
    }
544
545
    /**
546
     * Publish an image to the publish directory.
547
     *
548
     * @param $path
549
     */
550
    protected function publish($path)
551
    {
552
        $path = ltrim($path, '/');
553
554
        $this->files->makeDirectory((new \SplFileInfo($path))->getPath(), 0777, true, true);
555
556
        if ($this->files->extension($path) == 'svg') {
557
558
            $this->files->put($path, $this->dumpImage());
559
560
            return;
561
        }
562
563
        if (!$image = $this->makeImage()) {
564
            return;
565
        }
566
567
        if (function_exists('exif_read_data') && $image->exif('Orientation') && $image->exif('Orientation') > 1) {
568
            $this->addAlteration('orientate');
569
        }
570
571
        if (!$this->getAlterations() && $content = $this->dumpImage()) {
572
573
            $this->files->put($this->directory . $path, $content);
574
575
            return;
576
        }
577
578
        if (is_callable('exif_read_data') && in_array('orientate', $this->getAlterations())) {
579
            $this->setAlterations(array_unique(array_merge(['orientate'], $this->getAlterations())));
580
        }
581
582
        foreach ($this->getAlterations() as $method => $arguments) {
583
584
            if ($method == 'resize') {
585
                $this->guessResizeArguments($arguments);
586
            }
587
588
            if (in_array($method, $this->getAllowedMethods())) {
589
                if (is_array($arguments)) {
590
                    call_user_func_array([$image, $method], $arguments);
591
                } else {
592
                    call_user_func([$image, $method], $arguments);
593
                }
594
            }
595
        }
596
597
        $image->save($this->directory . $path, $this->getQuality());
598
    }
599
600
    /**
601
     * Set an attribute value.
602
     *
603
     * @param $attribute
604
     * @param $value
605
     * @return $this
606
     */
607
    public function attr($attribute, $value)
608
    {
609
        array_set($this->attributes, $attribute, $value);
610
611
        return $this;
612
    }
613
614
    /**
615
     * Return the image srcsets by set.
616
     *
617
     * @return array
618
     */
619
    public function srcset()
620
    {
621
        $sources = [];
622
623
        /* @var Image $image */
624
        foreach ($this->getSrcsets() as $descriptor => $image) {
625
            $sources[] = $image->path() . ' ' . $descriptor;
626
        }
627
628
        return implode(', ', $sources);
629
    }
630
631
    /**
632
     * Set the srcsets/alterations.
633
     *
634
     * @param array $srcsets
635
     */
636
    public function srcsets(array $srcsets)
637
    {
638
        foreach ($srcsets as $descriptor => &$alterations) {
639
640
            $image = $this->make(array_pull($alterations, 'image', $this->getImage()))->setOutput('url');
641
642 View Code Duplication
            foreach ($alterations as $method => $arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
643
                if (is_array($arguments)) {
644
                    call_user_func_array([$image, $method], $arguments);
645
                } else {
646
                    call_user_func([$image, $method], $arguments);
647
                }
648
            }
649
650
            $alterations = $image;
651
        }
652
653
        $this->setSrcsets($srcsets);
654
655
        return $this;
656
    }
657
658
    /**
659
     * Set the sources/alterations.
660
     *
661
     * @param array $sources
662
     * @param bool  $merge
663
     * @return $this
664
     */
665
    public function sources(array $sources, $merge = true)
666
    {
667
        foreach ($sources as $media => &$alterations) {
668
669
            if ($merge) {
670
                $alterations = array_merge($this->getAlterations(), $alterations);
671
            }
672
673
            $image = $this->make(array_pull($alterations, 'image', $this->getImage()))->setOutput('source');
674
675
            if ($media != 'fallback') {
676
                call_user_func([$image, 'media'], $media);
677
            }
678
679 View Code Duplication
            foreach ($alterations as $method => $arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
680
                if (is_array($arguments)) {
681
                    call_user_func_array([$image, $method], $arguments);
682
                } else {
683
                    call_user_func([$image, $method], $arguments);
684
                }
685
            }
686
687
            $alterations = $image;
688
        }
689
690
        $this->setSources($sources);
691
692
        return $this;
693
    }
694
695
    /**
696
     * Alter the image based on the user agents.
697
     *
698
     * @param array $agents
699
     * @param bool  $exit
700
     * @return $this
701
     */
702
    public function agents(array $agents, $exit = false)
703
    {
704
        foreach ($agents as $agent => $alterations) {
705
            if (
706
                $this->agent->is($agent)
707
                || ($agent == 'phone' && $this->agent->isPhone())
708
                || ($agent == 'mobile' && $this->agent->isMobile())
709
                || ($agent == 'tablet' && $this->agent->isTablet())
710
                || ($agent == 'desktop' && $this->agent->isDesktop())
711
            ) {
712 View Code Duplication
                foreach ($alterations as $method => $arguments) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
713
                    if (is_array($arguments)) {
714
                        call_user_func_array([$this, $method], $arguments);
715
                    } else {
716
                        call_user_func([$this, $method], $arguments);
717
                    }
718
                }
719
720
                if ($exit) {
721
                    return $this;
722
                }
723
            }
724
        }
725
726
        return $this;
727
    }
728
729
    /**
730
     * Set the image.
731
     *
732
     * @param  $image
733
     * @return $this
734
     */
735
    public function setImage($image)
736
    {
737
        if ($image instanceof Presenter) {
738
            $image = $image->getObject();
739
        }
740
741
        if ($image instanceof FieldType) {
742
            $image = $image->getValue();
743
        }
744
745
        // Replace path prefixes.
746
        if (is_string($image) && str_contains($image, '::')) {
747
748
            $image = $this->paths->realPath($image);
749
750
            $this->setExtension(pathinfo($image, PATHINFO_EXTENSION));
751
752
            $size = getimagesize($image);
753
754
            $this->setWidth(array_get($size, 0));
755
            $this->setHeight(array_get($size, 1));
756
        }
757
758
        if (is_string($image) && str_is('*://*', $image) && !starts_with($image, ['http', 'https'])) {
759
            $this->setExtension(pathinfo($image, PATHINFO_EXTENSION));
760
        }
761
762 View Code Duplication
        if ($image instanceof FileInterface) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\Contract\FileInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
763
764
            /* @var FileInterface $image */
765
            $this->setExtension($image->getExtension());
766
767
            $this->setWidth($image->getWidth());
768
            $this->setHeight($image->getHeight());
769
        }
770
771 View Code Duplication
        if ($image instanceof FilePresenter) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\FilePresenter does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
772
773
            /* @var FilePresenter|FileInterface $image */
774
            $image = $image->getObject();
775
776
            $this->setExtension($image->getExtension());
777
778
            $this->setWidth($image->getWidth());
779
            $this->setHeight($image->getHeight());
780
        }
781
782
        $this->image = $image;
783
784
        return $this;
785
    }
786
787
    /**
788
     * Make an image instance.
789
     *
790
     * @return \Intervention\Image\Image
791
     */
792
    protected function makeImage()
793
    {
794
        if ($this->image instanceof FileInterface) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\Contract\FileInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
795
            return $this->manager->make(app(MountManager::class)->read($this->image->location()));
796
        }
797
798
        if (is_string($this->image) && str_is('*://*', $this->image)) {
799
            return $this->manager->make(app(MountManager::class)->read($this->image));
800
        }
801
802
        if ($this->image instanceof File) {
803
            return $this->manager->make($this->image->read());
804
        }
805
806
        if (is_string($this->image) && file_exists($this->image)) {
807
            return $this->manager->make($this->image);
808
        }
809
810
        if ($this->image instanceof Image) {
811
            return $this->image;
812
        }
813
814
        return null;
815
    }
816
817
    /**
818
     * Dump an image instance's data.
819
     *
820
     * @return string
821
     */
822
    protected function dumpImage()
823
    {
824
        if ($this->image instanceof FileInterface) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\Contract\FileInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
825
            return app('League\Flysystem\MountManager')->read($this->image->location());
826
        }
827
828
        if (is_string($this->image) && str_is('*://*', $this->image)) {
829
            return app('League\Flysystem\MountManager')->read($this->image);
830
        }
831
832
        if ($this->image instanceof File) {
833
            return $this->image->read();
834
        }
835
836
        if (is_string($this->image) && file_exists($this->image)) {
837
            return file_get_contents($this->image);
838
        }
839
840
        if ($this->image instanceof Image) {
841
            return $this->image->encode();
842
        }
843
844
        if (is_string($this->image) && file_exists($this->image)) {
845
            return file_get_contents($this->image);
846
        }
847
848
        return null;
849
    }
850
851
    /**
852
     * Get the image instance.
853
     *
854
     * @return \Intervention\Image\Image
855
     */
856
    public function getImage()
857
    {
858
        return $this->image;
859
    }
860
861
    /**
862
     * Get the file name.
863
     *
864
     * @return null|string
865
     */
866
    public function getFilename()
867
    {
868
        return $this->filename;
869
    }
870
871
    /**
872
     * Set the file name.
873
     *
874
     * @param $filename
875
     * @return $this
876
     */
877
    public function setFilename($filename = null)
878
    {
879
        if (!$filename) {
880
            $filename = $this->getImageFilename();
0 ignored issues
show
Documentation Bug introduced by
The method getImageFilename does not exist on object<Anomaly\Streams\Platform\Image\Image>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
881
        }
882
883
        $this->filename = $filename;
884
885
        return $this;
886
    }
887
888
    /**
889
     * Get the alterations.
890
     *
891
     * @return array
892
     */
893
    public function getAlterations()
894
    {
895
        return $this->alterations;
896
    }
897
898
    /**
899
     * Set the alterations.
900
     *
901
     * @param array $alterations
902
     * @return $this
903
     */
904
    public function setAlterations(array $alterations)
905
    {
906
        $this->alterations = $alterations;
907
908
        return $this;
909
    }
910
911
    /**
912
     * Add an alteration.
913
     *
914
     * @param  $method
915
     * @param  $arguments
916
     * @return $this
917
     */
918
    public function addAlteration($method, $arguments = [])
919
    {
920
        $this->alterations[$method] = $arguments;
921
922
        return $this;
923
    }
924
925
    /**
926
     * Get the attributes.
927
     *
928
     * @return array
929
     */
930
    public function getAttributes()
931
    {
932
        return $this->attributes;
933
    }
934
935
    /**
936
     * Set the attributes.
937
     *
938
     * @param array $attributes
939
     * @return $this
940
     */
941
    public function setAttributes(array $attributes)
942
    {
943
        $this->attributes = $attributes;
944
945
        return $this;
946
    }
947
948
    /**
949
     * Add an attribute.
950
     *
951
     * @param  $attribute
952
     * @param  $value
953
     * @return $this
954
     */
955
    protected function addAttribute($attribute, $value)
956
    {
957
        $this->attributes[$attribute] = $value;
958
959
        return $this;
960
    }
961
962
    /**
963
     * Get the srcsets.
964
     *
965
     * @return array
966
     */
967
    public function getSrcsets()
968
    {
969
        return $this->srcsets;
970
    }
971
972
    /**
973
     * Set the srcsets.
974
     *
975
     * @param array $srcsets
976
     * @return $this
977
     */
978
    public function setSrcsets(array $srcsets)
979
    {
980
        $this->srcsets = $srcsets;
981
982
        return $this;
983
    }
984
985
    /**
986
     * Get the sources.
987
     *
988
     * @return array
989
     */
990
    public function getSources()
991
    {
992
        return $this->sources;
993
    }
994
995
    /**
996
     * Set the sources.
997
     *
998
     * @param array $sources
999
     * @return $this
1000
     */
1001
    public function setSources(array $sources)
1002
    {
1003
        $this->sources = $sources;
1004
1005
        return $this;
1006
    }
1007
1008
    /**
1009
     * Get the quality.
1010
     *
1011
     * @param null $default
1012
     * @return int
1013
     */
1014
    public function getQuality($default = null)
1015
    {
1016
        if (!$default) {
1017
            $this->config->get('streams::images.quality', 80);
1018
        }
1019
1020
        return $this->quality ?: $default;
1021
    }
1022
1023
    /**
1024
     * Set the output mode.
1025
     *
1026
     * @param $output
1027
     * @return $this
1028
     */
1029
    public function setOutput($output)
1030
    {
1031
        $this->output = $output;
1032
1033
        return $this;
1034
    }
1035
1036
    /**
1037
     * Get the extension.
1038
     *
1039
     * @return null|string
1040
     */
1041
    public function getExtension()
1042
    {
1043
        return $this->extension;
1044
    }
1045
1046
    /**
1047
     * Set the extension.
1048
     *
1049
     * @param $extension
1050
     * @return $this
1051
     */
1052
    public function setExtension($extension)
1053
    {
1054
        $this->extension = $extension;
1055
1056
        return $this;
1057
    }
1058
1059
    /**
1060
     * Get the allowed methods.
1061
     *
1062
     * @return array
1063
     */
1064
    public function getAllowedMethods()
1065
    {
1066
        return $this->allowedMethods;
1067
    }
1068
1069
    /**
1070
     * Add a path by it's namespace hint.
1071
     *
1072
     * @param $namespace
1073
     * @param $path
1074
     * @return $this
1075
     */
1076
    public function addPath($namespace, $path)
1077
    {
1078
        $this->paths->addPath($namespace, $path);
1079
1080
        return $this;
1081
    }
1082
1083
    /**
1084
     * Get the width.
1085
     *
1086
     * @return int|null
1087
     */
1088
    public function getWidth()
1089
    {
1090
        return $this->width;
1091
    }
1092
1093
    /**
1094
     * Set the width.
1095
     *
1096
     * @param $width
1097
     * @return $this
1098
     */
1099
    public function setWidth($width)
1100
    {
1101
        $this->width = $width;
1102
1103
        return $this;
1104
    }
1105
1106
    /**
1107
     * Get the height.
1108
     *
1109
     * @return int|null
1110
     */
1111
    public function getHeight()
1112
    {
1113
        return $this->height;
1114
    }
1115
1116
    /**
1117
     * Set the height.
1118
     *
1119
     * @param $height
1120
     * @return $this
1121
     */
1122
    public function setHeight($height)
1123
    {
1124
        $this->height = $height;
1125
1126
        return $this;
1127
    }
1128
1129
    /**
1130
     * Guess the resize callback value
1131
     * from a boolean.
1132
     *
1133
     * @param array $arguments
1134
     */
1135
    protected function guessResizeArguments(array &$arguments)
1136
    {
1137
        $arguments = array_pad($arguments, 3, null);
1138
1139
        if (end($arguments) instanceof \Closure) {
1140
            return;
1141
        }
1142
1143
        if (array_pop($arguments) !== false && (is_null($arguments[0]) || is_null($arguments[1]))) {
1144
            $arguments[] = function (Constraint $constraint) {
1145
                $constraint->aspectRatio();
1146
            };
1147
        }
1148
    }
1149
1150
    /**
1151
     * Return the output.
1152
     *
1153
     * @return string
1154
     */
1155
    public function __toString()
1156
    {
1157
        return (string)$this->output();
1158
    }
1159
1160
    /**
1161
     * If the method does not exist then
1162
     * add an attribute and return.
1163
     *
1164
     * @param $name
1165
     * @param $arguments
1166
     * @return $this|mixed
1167
     */
1168
    function __call($name, $arguments)
1169
    {
1170
        if (in_array($name, $this->getAllowedMethods())) {
1171
            return $this->addAlteration($name, $arguments);
1172
        }
1173
1174
        if ($this->macros->isMacro($macro = snake_case($name))) {
1175
            return $this->macro($macro);
1176
        }
1177
1178
        if (!method_exists($this, $name)) {
1179
1180
            array_set($this->attributes, $name, array_shift($arguments));
1181
1182
            return $this;
1183
        }
1184
1185
        return call_user_func_array([$this, $name], $arguments);
1186
    }
1187
}
1188