Converter::convert()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 23
cts 23
cp 1
rs 8.3626
c 0
b 0
f 0
cc 7
nc 8
nop 3
crap 7
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Converter\Service;
13
14
use Symfony\Component\Config\Resource\FileResource;
15
use Symfony\Component\Translation\Loader\LoaderInterface;
16
use Symfony\Component\Translation\MessageCatalogue;
17
use Symfony\Component\Translation\Writer\TranslationWriter;
18
use Translation\Converter\Loader\TranslationLoader;
19
use Translation\SymfonyStorage\Dumper\XliffDumper;
20
use Translation\SymfonyStorage\FileStorage;
21
22
/**
23
 * Convert any translation format to XLF.
24
 *
25
 * @author Tobias Nyholm <[email protected]>
26
 */
27
class Converter
28
{
29
    /**
30
     * @var \Translation\SymfonyStorage\TranslationLoader
31
     */
32
    private $reader;
33
34
    /**
35
     * @var TranslationWriter
36
     */
37
    private $writer;
38
39
    /**
40
     * @param LoaderInterface $reader
41
     * @param string|string[] $format
42
     */
43 2
    public function __construct(LoaderInterface $reader, $format)
44
    {
45 2
        $this->reader = new TranslationLoader($reader, $format);
46 2
        $this->writer = new TranslationWriter();
47 2
        $this->writer->disableBackup();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\Transl...Writer::disableBackup() has been deprecated with message: since Symfony 4.1

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
48 2
        $this->writer->addDumper('xlf', new XliffDumper());
49
    }
50
51
    /**
52
     * @param string $inputDir
53
     * @param string $outputDir
54
     * @param array  $locales
55 2
     */
56
    public function convert($inputDir, $outputDir, array $locales)
57 2
    {
58 2
        $inputDir = realpath($inputDir);
59 2
        if (false === realpath($outputDir) && false === mkdir($outputDir)) {
60 2
            throw new \Exception('Unable to create output directory.'.$outputDir);
61 2
        }
62 2
        $outputDir = realpath($outputDir);
63 2
64
        $inputStorage = new FileStorage($this->writer, $this->reader, [$inputDir]);
0 ignored issues
show
Documentation introduced by
$this->reader is of type object<Translation\Symfo...rage\TranslationLoader>, but the function expects a object<Symfony\Component...slationReaderInterface>.

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...
65 2
        $outputStorage = new FileStorage($this->writer, $this->reader, [$outputDir], ['xliff_version' => '2.0']);
0 ignored issues
show
Documentation introduced by
$this->reader is of type object<Translation\Symfo...rage\TranslationLoader>, but the function expects a object<Symfony\Component...slationReaderInterface>.

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...
66 2
        foreach ($locales as $locale) {
67 2
            $inputCatalogue = new MessageCatalogue($locale);
68 2
            $outputCatalogue = new MessageCatalogue($locale);
69 2
70 2
            $inputStorage->export($inputCatalogue);
71 2
            foreach ($inputCatalogue->all() as $domain => $messages) {
72
                $outputCatalogue->add($messages, $domain);
73
                foreach ($messages as $id => $message) {
74
                    $outputCatalogue->setMetadata($id, $inputCatalogue->getMetadata($id, $domain), $domain);
75 2
                }
76 2
            }
77
78
            // rewrite the resources to new path.
79 2
            /** @var FileResource $resource */
80
            foreach ($inputCatalogue->getResources() as $resource) {
81
                $path = str_replace($inputDir, $outputDir, $resource->getResource());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Config...ource\ResourceInterface as the method getResource() does only exist in the following implementations of said interface: Symfony\Component\Config...\ClassExistenceResource, Symfony\Component\Config...ource\DirectoryResource, Symfony\Component\Config...e\FileExistenceResource, Symfony\Component\Config\Resource\FileResource, Symfony\Component\Translation\Tests\StaleResource.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
82 2
83
                // rewrite $path extension to be xlf
84 2
                $path = substr($path, 0, strrpos($path, '.')).'.xlf';
85 2
86
                // Make sure file exists
87 2
                file_put_contents($path, '');
88 2
89 2
                $outputCatalogue->addResource(new FileResource($path));
90
            }
91
92
            $outputStorage->import($outputCatalogue);
93
        }
94
    }
95
}
96