TextToSpeechAbstract::convert()   C
last analyzed

Complexity

Conditions 8
Paths 8

Size

Total Lines 45
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 45
rs 5.3846
cc 8
eloc 31
nc 8
nop 0
1
<?php
2
/**
3
 *
4
 * PHP version 5.5
5
 *
6
 * @package TTS
7
 * @author  Sergey V.Kuzin <[email protected]>
8
 * @license MIT
9
 */
10
11
namespace TTS;
12
13
14
use Psr\Log\LoggerInterface;
15
use Psr\Log\NullLogger;
16
17
abstract class TextToSpeechAbstract
18
{
19
    const VOTE_FEMALE = 'female';
20
    const VOTE_MALE = 'male';
21
22
    protected $driver = null;
23
24
    protected $vote = null;
25
26
    protected $speaker = '';
27
28
    /** @var string */
29
    protected $cacheDir = null;
30
31
    protected $isCached = false;
32
33
    protected $results = [];
34
35
    protected $debug = false;
36
37
    /**
38
     * @var string[]
39
     */
40
    protected $lines = [];
41
42
    /**
43
     * @var LoggerInterface
44
     */
45
    protected $logger;
46
47
    /**
48
     * @param LoggerInterface $cache
0 ignored issues
show
Bug introduced by
There is no parameter named $cache. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
49
     * @param string[] $options
50
     */
51
    public function __construct(LoggerInterface $logger = null, array $options = [])
52
    {
53
        if (null === $logger) {
54
            $this->logger = new NullLogger();
55
        } else {
56
            $this->logger = $logger;
57
        }
58
59
        if (isset($options['cacheDir'])) {
60
            $this->cacheDir = $options['cacheDir'];
61
            $this->isCached = true;
62
        }
63
64
        if (isset($options['debug'])) {
65
            $this->debug = (bool)$options['debug'];
66
            $this->isCached = true;
67
        }
68
    }
69
70
    /**
71
     * @param string $text
72
     * @return $this
73
     */
74 View Code Duplication
    public function addText($text)
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...
75
    {
76
        $text = trim(str_replace(["\r", "\n", '"', "'", '«', '»'], ' ', $text));
77
        $text = preg_replace('/([ ]{2,})/', ' ', $text);
78
        $text = mb_strtolower($text);
79
80
        $this->lines[] = $text;
81
82
        return $this;
83
    }
84
85
    /**
86
     * @return $this
87
     */
88
    public function process()
89
    {
90
        $this->convert();
91
92
        return $this;
93
    }
94
95
    public function convert()
96
    {
97
        if (0 === count($this->lines)) {
98
            throw new \LogicException('нет текста');
99
        }
100
101
        foreach ($this->lines as $line) {
102
            $result = new Result();
103
            $result->setSource($line);
104
            $result->setCacheKey($this->calcCacheKey($line));
105
106
            $fileName = '';
0 ignored issues
show
Unused Code introduced by
$fileName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
107
            if ($this->isCached) {
108
                $pathParts = [];
109
                $pathParts[] = $this->cacheDir;
110
                $pathParts[] = $this->driver;
111
                $pathParts[] = $this->vote;
112
                $pathParts[] = $this->speaker;
113
114
                $pathParts = array_merge($pathParts, str_split(substr($result->getCacheKey(), 0, 4), 2));
115
116
                $fileName = implode('/', $pathParts);
117
118
                if (!file_exists($fileName) || !is_dir($fileName)) {
119
                    mkdir($fileName, 0755, true);
120
                }
121
122
                 $fileName .= '/' . $result->getCacheKey() . '.mp3';
123
            } else {
124
                $fileName = tempnam(sys_get_temp_dir(), 'tts-') . '.mp3';
125
            }
126
            $result->setFile($fileName);
127
            $result->export();
128
            if ($this->isCached && file_exists($fileName)) {
129
                $result->setCached(true);
130
                $this->results[] = $result;
131
            } else {
132
                $this->synthesize($line, $fileName);
133
                $this->results[] = $result;
134
            }
135
        }
136
137
        $this->lines = [];
138
        return $this;
139
    }
140
141
    public function getResult()
142
    {
143
        return $this->results;
144
    }
145
146
    private function calcCacheKey($text)
147
    {
148
        return sha1($text);
149
    }
150
151
    /**
152
     * Синтезирует фразу $text
153
     *
154
     * @param string $text Текст для преоброзование
155
     * @param string $outFile Имя файла с полным путём
156
     *
157
     * @return bool true если успешно
158
     */
159
    abstract protected function synthesize($text, $outFile);
160
}
161