Completed
Push — ezp24853-enhance_rest_when_fai... ( 1cf498...fc8bde )
by
unknown
25:05
created

ContentFieldValidationException::visit()   C

Complexity

Conditions 12
Paths 6

Size

Total Lines 72
Code Lines 47

Duplication

Lines 37
Ratio 51.39 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 47
c 1
b 0
f 0
nc 6
nop 3
dl 37
loc 72
rs 5.519

How to fix   Long Method    Complexity   

Long Method

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:

1
<?php
2
3
/**
4
 * File containing the ContentFieldValidationException ValueObjectVisitor class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 *
9
 * @version //autogentag//
10
 */
11
namespace eZ\Publish\Core\REST\Server\Output\ValueObjectVisitor;
12
13
use eZ\Publish\API\Repository\Translatable;
14
use eZ\Publish\API\Repository\Values\Translation;
15
use eZ\Publish\Core\REST\Common\Output\Generator;
16
use eZ\Publish\Core\REST\Common\Output\Visitor;
17
use eZ\Publish\Core\REST\Server\Exceptions\ContentFieldValidationException as RESTContentFieldValidationException;
18
19
/**
20
 * ContentFieldValidationException value object visitor.
21
 */
22
class ContentFieldValidationException extends BadRequestException
23
{
24
    /**
25
     * Visit struct returned by controllers.
26
     *
27
     * @param \eZ\Publish\Core\REST\Common\Output\Visitor $visitor
28
     * @param \eZ\Publish\Core\REST\Common\Output\Generator $generator
29
     * @param \Exception $data
30
     */
31
    public function visit(Visitor $visitor, Generator $generator, $data)
32
    {
33
        $generator->startObjectElement('ErrorMessage');
34
35
        $statusCode = $this->getStatus();
36
        $visitor->setStatus($statusCode);
37
        $visitor->setHeader('Content-Type', $generator->getMediaType('ErrorMessage'));
38
39
        $generator->startValueElement('errorCode', $statusCode);
40
        $generator->endValueElement('errorCode');
41
42
        $generator->startValueElement('errorMessage', $this->httpStatusCodes[$statusCode]);
43
        $generator->endValueElement('errorMessage');
44
45
        $errorDetails = ['fields' => []];
46
        if ($data instanceof RESTContentFieldValidationException && $this->translator) {
47
            $errorDescription = $data->getMessage();
48
49
            foreach ($data->getFieldErrors() as $fieldTypeId => $translations) {
50
                foreach ($translations as $languageCode => $validationErrors) {
0 ignored issues
show
Bug introduced by
The expression $translations of type object<eZ\Publish\Core\FieldType\ValidationError> is not traversable.
Loading history...
51
                    if (is_array($validationErrors)) {
52
                        foreach ($validationErrors as $validationError) {
53 View Code Duplication
                            if ($validationError instanceof Translatable) {
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...
54
                                $errorDetails['fields'][$fieldTypeId][] = [
55
                                    'type' => $validationError->getTarget(),
56
                                    'message' => $this->translator->trans(
57
                                        $this->translationToString($validationError->getTranslatableMessage()),
58
                                        $validationError->getTranslatableMessage()->values,
0 ignored issues
show
Documentation introduced by
The property values does not exist on object<eZ\Publish\API\Re...ory\Values\Translation>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
59
                                        'repository_exceptions'
60
                                    ),
61
                                ];
62
                            }
63
                        }
64 View Code Duplication
                    } else if ($validationErrors instanceof Translatable) {
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...
65
                        $errorDetails['fields'][$fieldTypeId][] = [
66
                            'type' => $validationErrors->getTarget(),
67
                            'message' => $this->translator->trans(
68
                                $this->translationToString($validationErrors->getTranslatableMessage()),
69
                                $validationErrors->getTranslatableMessage()->values,
70
                                'repository_exceptions'
71
                            ),
72
                        ];
73
                    } else {
74
                        // TODO: exception, invalid ValidationError
75
                    }
76
                }
77
            }
78 View Code Duplication
        } else if ($data instanceof Translatable && $this->translator) {
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...
79
            $errorDescription = $this->translator->trans($data->getMessageTemplate(), $data->getParameters(), 'repository_exceptions');
80
        } else {
81
            $errorDescription = $data->getMessage();
82
        }
83
84
        $generator->startValueElement('errorDescription', $errorDescription);
85
        $generator->endValueElement('errorDescription');
86
87
        $generator->startValueElement('errorDetails', $errorDetails);
0 ignored issues
show
Documentation introduced by
$errorDetails is of type array<string,array,{"fields":"array"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
88
        $generator->endValueElement('errorDetails');
89
90 View Code Duplication
        if ($this->debug) {
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...
91
            $generator->startValueElement('trace', $data->getTraceAsString());
92
            $generator->endValueElement('trace');
93
94
            $generator->startValueElement('file', $data->getFile());
95
            $generator->endValueElement('file');
96
97
            $generator->startValueElement('line', $data->getLine());
98
            $generator->endValueElement('line');
99
        }
100
101
        $generator->endObjectElement('ErrorMessage');
102
    }
103
104
    /**
105
     * TODO there should be some existing code for this somewhere!
106
     */
107
    private function translationToString(Translation $translation)
108
    {
109
        $result = '';
110
        if ($translation instanceof Translation\Message) {
111
            $result = $translation->message;
0 ignored issues
show
Documentation introduced by
The property $message is declared protected in eZ\Publish\API\Repositor...ues\Translation\Message. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
112
        } else if ($translation instanceof Translation\Plural) {
113
            if ($translation->values[0] == 1) {
0 ignored issues
show
Documentation introduced by
The property $values is declared protected in eZ\Publish\API\Repositor...lues\Translation\Plural. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
114
                $result = $translation->singular;
0 ignored issues
show
Documentation introduced by
The property $singular is declared protected in eZ\Publish\API\Repositor...lues\Translation\Plural. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
115
            } else {
116
                $result = $translation->plural;
0 ignored issues
show
Documentation introduced by
The property $plural is declared protected in eZ\Publish\API\Repositor...lues\Translation\Plural. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
117
            }
118
        }
119
120
        return $result;
121
    }
122
}
123