Completed
Push — master ( 0001a8...55fdf1 )
by Johannes
02:44
created

ImageRenderer::getUrlTranslation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 * Lichtenwallner  (https://lichtenwallner.at)
4
 *
5
 * @see https://github.com/jolicht/markdown-cms for the canonical source repository
6
 * @license https://github.com/jolicht/markdown-cms/blob/master/LICENSE MIT
7
 * @copyright Copyright (c) Johannes Lichtenwallner
8
 */
9
declare(strict_types = 1);
10
namespace Jolicht\MarkdownCms\Markdown\Renderer;
11
12
use League\CommonMark\ElementRendererInterface;
13
use League\CommonMark\HtmlElement;
14
use League\CommonMark\Inline\Renderer\InlineRendererInterface;
15
use League\CommonMark\Inline\Element\AbstractInline;
16
17
class ImageRenderer implements InlineRendererInterface
18
{
19
    /**
20
     * Url Translation
21
     *
22
     * @var array
23
     */
24
    private $urlTranslation;
25
26
    /**
27
     * Constructor
28
     *
29
     * @param array $urlTranslation
30
     */
31
    public function __construct(array $urlTranslation)
32
    {
33
        $this->urlTranslation = $urlTranslation;
34
    }
35
36
    /**
37
     * Get url translation
38
     *
39
     * @return array
40
     */
41
    public function getUrlTranslation() : array
42
    {
43
        return $this->urlTranslation;
44
    }
45
46
    /**
47
     * Render image
48
     *
49
     * {@inheritDoc}
50
     * @see \League\CommonMark\Inline\Renderer\InlineRendererInterface::render()
51
     */
52
    public function render(AbstractInline $inline, ElementRendererInterface $htmlRenderer)
53
    {
54
        $altContent = $inline->firstChild()->getContent();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class League\CommonMark\Node\Node as the method getContent() does only exist in the following sub-classes of League\CommonMark\Node\Node: League\CommonMark\Inline...AbstractStringContainer, League\CommonMark\Inline\Element\Code, League\CommonMark\Inline\Element\HtmlInline, League\CommonMark\Inline\Element\Text. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
55
        $attributes = [
56
            'src' => strtr($inline->getUrl(), $this->getUrlTranslation()),
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class League\CommonMark\Inline\Element\AbstractInline as the method getUrl() does only exist in the following sub-classes of League\CommonMark\Inline\Element\AbstractInline: League\CommonMark\Inline...ent\AbstractWebResource, League\CommonMark\Inline\Element\Image, League\CommonMark\Inline\Element\Link. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
57
            'alt' => $altContent,
58
        ];
59
60
        $posJsonOpen = strpos($altContent, '{');
61
        $posJsonClose = strpos($altContent, '}');
62
        if ((false !== $posJsonOpen) and (false !== $posJsonClose)) {
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...
63
            $json = substr($altContent, $posJsonOpen, $posJsonClose);
64
            $data = json_decode($json, true);
65
            if (is_array($data)) {
66
                $attributes = array_merge($attributes, $data);
67
            }
68
            $attributes['alt'] = substr($altContent, 0, $posJsonOpen);
69
        }
70
71
        if (!isset($attributes['layout'])) {
72
            $attributes['layout'] = 'responsive';
73
        }
74
75
        return new HtmlElement('amp-img', $attributes);
76
    }
77
}