EMTypograph::fast_apply()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
/**
4
* Evgeny Muravjev Typograph, http://mdash.ru
5
* Version: 3.4 Gold Master
6
* Release Date: September 20, 2014
7
* Authors: Evgeny Muravjev & Alexander Drutsa  
8
*/
9
10
namespace Fenrizbes\TypographBundle\EMT;
11
12
class EMTypograph extends EMTBase
13
{
14
	public $trets = array(
15
        '\Fenrizbes\TypographBundle\EMT\EMTTretQuote',
16
        '\Fenrizbes\TypographBundle\EMT\EMTTretDash',
17
        '\Fenrizbes\TypographBundle\EMT\EMTTretSymbol',
18
        '\Fenrizbes\TypographBundle\EMT\EMTTretPunctmark',
19
        '\Fenrizbes\TypographBundle\EMT\EMTTretNumber',
20
        '\Fenrizbes\TypographBundle\EMT\EMTTretSpace',
21
        '\Fenrizbes\TypographBundle\EMT\EMTTretAbbr',
22
        '\Fenrizbes\TypographBundle\EMT\EMTTretNobr',
23
        '\Fenrizbes\TypographBundle\EMT\EMTTretDate',
24
        '\Fenrizbes\TypographBundle\EMT\EMTTretOptAlign',
25
        '\Fenrizbes\TypographBundle\EMT\EMTTretEtc',
26
        '\Fenrizbes\TypographBundle\EMT\EMTTretText'
27
    );
28
	
29
	
30
	protected $group_list  = array(
31
		'Quote'     => true,
32
		'Dash'      => true,
33
		'Nobr'      => true,
34
		'Symbol'    => true,
35
		'Punctmark' => true,
36
		'Number'    => true,
37
		'Date'      => true,
38
		'Space'     => true,
39
		'Abbr'      => true,		
40
		'OptAlign'  => true,
41
		'Text'      => true,
42
		'Etc'       => true,		
43
	);
44
	protected $all_options = array(
45
	
46
		'Quote.quotes' => array( 'description' => 'Расстановка «кавычек-елочек» первого уровня', 'selector' => "Quote.*quote" ),
47
		'Quote.quotation' => array( 'description' => 'Внутренние кавычки-лапки', 'selector' => "Quote", 'setting' => 'no_bdquotes', 'reversed' => true ),
48
							
49
		'Dash.to_libo_nibud' => 'direct',
50
		'Dash.iz_za_pod' => 'direct',
51
		'Dash.ka_de_kas' => 'direct',
52
		
53
		'Nobr.super_nbsp' => 'direct',
54
		'Nobr.nbsp_in_the_end' => 'direct',
55
		'Nobr.phone_builder' => 'direct',
56
		'Nobr.ip_address' => 'direct',
57
		'Nobr.spaces_nobr_in_surname_abbr' => 'direct',
58
		'Nobr.nbsp_celcius' => 'direct',		
59
		'Nobr.hyphen_nowrap_in_small_words' => 'direct',
60
		'Nobr.hyphen_nowrap' => 'direct',
61
		'Nobr.nowrap' => array('description' => 'Nobr (по умолчанию) & nowrap', 'disabled' => true, 'selector' => '*', 'setting' => 'nowrap' ),
62
		
63
		'Symbol.tm_replace'     => 'direct',
64
		'Symbol.r_sign_replace' => 'direct',
65
		'Symbol.copy_replace' => 'direct',
66
		'Symbol.apostrophe' => 'direct',
67
		'Symbol.degree_f' => 'direct',
68
		'Symbol.arrows_symbols' => 'direct',
69
		'Symbol.no_inches' => array( 'description' => 'Расстановка дюйма после числа', 'selector' => "Quote", 'setting' => 'no_inches', 'reversed' => true ),
70
		
71
		'Punctmark.auto_comma' => 'direct',
72
		'Punctmark.hellip' => 'direct',
73
		'Punctmark.fix_pmarks' => 'direct',
74
		'Punctmark.fix_excl_quest_marks' => 'direct',
75
		'Punctmark.dot_on_end' => 'direct',
76
		
77
		'Number.minus_between_nums' => 'direct',
78
		'Number.minus_in_numbers_range' => 'direct',
79
		'Number.auto_times_x' => 'direct',
80
		'Number.simple_fraction' => 'direct',
81
		'Number.math_chars' => 'direct',
82
		//'Number.split_number_to_triads' => 'direct',
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
83
		'Number.thinsp_between_number_triads' => 'direct',
84
		'Number.thinsp_between_no_and_number' => 'direct',
85
		'Number.thinsp_between_sect_and_number' => 'direct',
86
		
87
		'Date.years' => 'direct',
88
		'Date.mdash_month_interval' => 'direct',
89
		'Date.nbsp_and_dash_month_interval' => 'direct',
90
		'Date.nobr_year_in_date' => 'direct',
91
		
92
		'Space.many_spaces_to_one' => 'direct',	
93
		'Space.clear_percent' => 'direct',	
94
		'Space.clear_before_after_punct' => array( 'description' => 'Удаление пробелов перед и после знаков препинания в предложении', 'selector' => 'Space.remove_space_before_punctuationmarks'),
95
		'Space.autospace_after' => array( 'description' => 'Расстановка пробелов после знаков препинания', 'selector' => 'Space.autospace_after_*'),
96
		'Space.bracket_fix' => array( 'description' => 'Удаление пробелов внутри скобок, а также расстановка пробела перед скобками', 
97
				'selector' => array('Space.nbsp_before_open_quote', 'Punctmark.fix_brackets')),
98
				
99
		'Abbr.nbsp_money_abbr' => 'direct',		
100
		'Abbr.nobr_vtch_itd_itp' => 'direct',		
101
		'Abbr.nobr_sm_im' => 'direct',		
102
		'Abbr.nobr_acronym' => 'direct',		
103
		'Abbr.nobr_locations' => 'direct',		
104
		'Abbr.nobr_abbreviation' => 'direct',		
105
		'Abbr.ps_pps' => 'direct',		
106
		'Abbr.nbsp_org_abbr' => 'direct',		
107
		'Abbr.nobr_gost' => 'direct',		
108
		'Abbr.nobr_before_unit_volt' => 'direct',		
109
		'Abbr.nbsp_before_unit' => 'direct',		
110
		
111
		'OptAlign.all' => array( 'description' => 'Все настройки оптического выравнивания', 'hide' => true, 'selector' => 'OptAlign.*'),
112
		'OptAlign.oa_oquote' => 'direct',	
113
		'OptAlign.oa_obracket_coma' => 'direct',	
114
		'OptAlign.oa_oquote_extra' => 'direct',	
115
		'OptAlign.layout' => array( 'description' => 'Inline стили или CSS' ),
116
		
117
		'Text.paragraphs' => 'direct',
118
		'Text.auto_links' => 'direct',
119
		'Text.email' => 'direct',
120
		'Text.breakline' => 'direct',
121
		'Text.no_repeat_words' => 'direct',
122
		
123
		
124
		//'Etc.no_nbsp_in_nobr' => 'direct',		
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
		'Etc.unicode_convert' => array('description' => 'Преобразовывать html-сущности в юникод', 'selector' => '*', 'setting' => 'dounicode' , 'disabled' => true),
126
	
127
	);
128
	
129
	/**
130
	 * Получить список имеющихся опций
131
	 *
132
	 * @return array
133
	 *     all    - полный список
134
	 *     group  - сгруппрованный по группам
135
	 */
136
	public function get_options_list()
137
	{
138
		$arr['all'] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$arr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $arr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
139
		$bygroup = array();
140
		foreach($this->all_options as $opt => $op)
141
		{
142
			$arr['all'][$opt] = $this->get_option_info($opt);
143
			$x = explode(".",$opt);
144
			$bygroup[$x[0]][] = $opt;
145
		}
146
		$arr['group'] = array();
147
		foreach($this->group_list as $group => $ginfo)
148
		{
149
			if($ginfo === true)
150
			{
151
				$tret = $this->get_tret($group);
0 ignored issues
show
Documentation introduced by
$group is of type integer|string, but the function expects a object<Fenrizbes\Typogra...undle\EMT\unknown_type>.

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...
152
				if($tret) $info['title'] = $tret->title; else $info['title'] = "Не определено";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
153
			} else {
154
				$info = $ginfo;
155
			}
156
			$info['name'] = $group;
0 ignored issues
show
Bug introduced by
The variable $info does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
157
			$info['options'] = array();
158
			if(is_array($bygroup[$group])) foreach($bygroup[$group] as $opt) $info['options'][] = $opt;
159
			$arr['group'][] = $info;
160
		}
161
		return $arr;
162
	}
163
	
164
	
165
	/**
166
	 * Получить информацию о настройке
167
	 *
168
	 * @param string $key
169
	 * @return array|false
170
	 */
171
	protected function get_option_info($key)
172
	{
173
		if(!isset($this->all_options[$key])) return false;
174
		if(is_array($this->all_options[$key])) return $this->all_options[$key];
175
		
176
		if(($this->all_options[$key] == "direct") || ($this->all_options[$key] == "reverse"))
177
		{
178
			$pa = explode(".", $key);
179
			$tret_pattern = $pa[0];
180
			$tret = $this->get_tret($tret_pattern);
181
			if(!$tret) return false;		
182
			if(!isset($tret->rules[$pa[1]])) return false;
183
			$array = $tret->rules[$pa[1]];
184
			$array['way'] = $this->all_options[$key];
185
			return $array;
186
		}
187
		return false;		
188
	}
189
	
190
	
191
	/**
192
	 * Установка одной метанастройки
193
	 *
194
	 * @param string $name
195
	 * @param mixed $value
196
	 */
197
	public function do_setup($name, $value)
198
	{
199
		if(!isset($this->all_options[$name])) return;
200
		
201
		// эта настрока связана с правилом ядра
202
		if(is_string($this->all_options[$name]))
203
		{
204
			$this->set($name, "active", $value );
205
			return ;
206
		}
207
		if(is_array($this->all_options[$name]))
208
		{
209
			if(isset($this->all_options[$name]['selector']))
210
			{
211
				$settingname = "active";
212
				if(isset($this->all_options[$name]['setting'])) $settingname = $this->all_options[$name]['setting'];
213
				$this->set($this->all_options[$name]['selector'], $settingname, $value);
214
			}
215
		}
216
		
217
		if($name == "OptAlign.layout")
218
		{
219
			if($value == "style") $this->set_tag_layout(EMTLib::LAYOUT_STYLE);
220
			if($value == "class") $this->set_tag_layout(EMTLib::LAYOUT_CLASS);
221
		}
222
		
223
	}
224
	
225
	/**
226
	 * Запустить типограф со стандартными параметрами
227
	 *
228
	 * @param string $text
229
	 * @param array $options
230
	 * @return string
231
	 */
232
	public static function fast_apply($text, $options = null)
233
	{
234
		$obj = new self();
235
		if(is_array($options)) $obj->setup($options);
236
		$obj->set_text($text);
237
		return $obj->apply();
238
	}
239
}