Passed
Push — master ( af6f8b...b52801 )
by Observer
01:41
created

NetObject::formatArg()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace VoidEngine;
4
5
use VoidCore;
6
7
class NetObject implements \ArrayAccess
8
{
9
    protected int $selector = 0;
10
    protected ?string $name = null;
11
    // protected bool $isCollection = false;
12
13
    public function __construct ($name, $assembly = false, ...$args)
14
    {
15
        foreach ($args as $id => $arg)
16
            $args[$id] = EngineAdditions::uncoupleSelector ($arg);
17
        
18
        if (is_int ($name) && VoidCore::objectExists ($name))
19
            $this->selector = $name;
20
21
        elseif (is_string ($name))
22
            $this->selector = VoidCore::createObject ($name, $assembly, ...$args);
23
24
        else throw new \Exception ('Incorrect params passed');
25
26
        /*$this->isCollection = $this->getType ()
27
            ->isSubclassOf (VoidCore::typeof ('System.Collectons.Generic.ICollection'));*/
28
    }
29
30
    public function dispose (): void
31
    {
32
        VoidCore::removeObjects ($this->selector);
33
    }
34
35
    # Основные магические методы
36
37
    public function __get (string $name)
38
    {
39
        switch (strtolower ($name))
40
        {
41
            case 'count':
42
            case 'length':
43
                try
44
                {
45
                    return $this->getProperty ('Count');
46
                }
47
48
                catch (\WinformsException $e)
49
                {
50
                    return $this->getProperty ('Length');
51
                }
52
            break;
53
54
            case 'list':
55
                $size = $this->count;
56
                $list = [];
57
                
58
				for ($i = 0; $i < $size; ++$i)
59
                    $list[] = EngineAdditions::coupleSelector (VoidCore::getArrayValue ($this->selector, $i));
60
                
61
                return $list;
62
            break;
63
64
            case 'names':
65
                $size  = $this->count;
66
                $names = [];
67
                
68
                for ($i = 0; $i < $size; ++$i)
69
                    try
70
                    {
71
                        $names[] = VoidCore::getProperty (VoidCore::getArrayValue ($this->selector, [$i, VC_OBJECT]), 'Text');
72
                    }
73
74
                    catch (\WinformsException $e)
75
                    {
76
                        $names[] = VoidCore::getArrayValue ($this->selector, [$i, VC_STRING]);
77
                    }
78
                
79
                return $names;
80
            break;
81
        }
82
83
        if (method_exists ($this, $method = 'get_'. $name))
84
            return $this->$method ();
85
86
        return isset ($this->$name) ?
87
            $this->$name : EngineAdditions::coupleSelector ($this->getProperty ($name));
88
    }
89
90
    public function __set (string $name, $value): void
91
    {
92
        if (substr ($name, -5) == 'Event')
93
            Events::setEvent ($this->selector, substr ($name, 0, -5), $value);
94
95
        elseif (method_exists ($this, $method = 'set_'. $name))
96
            $this->$method ($value);
97
        
98
        else $this->setProperty ($name, $this->formatArg ($value));
99
    }
100
101
    public function __call (string $name, array $args)
102
    {
103
        return EngineAdditions::coupleSelector ($this->callMethod ($name, array_map ([$this, 'formatArg'], $args)));
104
    }
105
106
    protected function formatArg ($item)
107
    {
108
        $item = EngineAdditions::uncoupleSelector ($item);
109
110
        if (is_array ($item))
111
            $item = EngineAdditions::uncoupleSelector (dnArray (VoidCore::callMethod (VoidCore::callMethod ([current ($item), VC_OBJECT], 'GetType')), 'ToString', $item));
0 ignored issues
show
Unused Code introduced by
The call to VoidEngine\dnArray() has too many arguments starting with $item. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

111
            $item = EngineAdditions::uncoupleSelector (/** @scrutinizer ignore-call */ dnArray (VoidCore::callMethod (VoidCore::callMethod ([current ($item), VC_OBJECT], 'GetType')), 'ToString', $item));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
'ToString' of type string is incompatible with the type array expected by parameter $items of VoidEngine\dnArray(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

111
            $item = EngineAdditions::uncoupleSelector (dnArray (VoidCore::callMethod (VoidCore::callMethod ([current ($item), VC_OBJECT], 'GetType')), /** @scrutinizer ignore-type */ 'ToString', $item));
Loading history...
112
113
        return $item;
114
    }
115
116
    # Управление VoidCore
117
118
    protected function getProperty ($name)
119
    {
120
        return VoidCore::getProperty ($this->selector, $name);
121
    }
122
123
    protected function setProperty (string $name, $value): void
124
    {
125
        VoidCore::setProperty ($this->selector, $name, $value);
126
    }
127
128
    protected function callMethod (string $name, array $args = [])
129
    {
130
        return VoidCore::callMethod ($this->selector, $name, ...$args);
131
    }
132
133
    # ArrayAccess
134
135
    public function offsetSet ($index, $value)
136
	{
137
        try
138
        {
139
            $index === null ?
140
                $this->callMethod ('Add', EngineAdditions::uncoupleSelector ($value)) :
0 ignored issues
show
Bug introduced by
It seems like VoidEngine\EngineAdditio...ncoupleSelector($value) can also be of type integer; however, parameter $args of VoidEngine\NetObject::callMethod() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

140
                $this->callMethod ('Add', /** @scrutinizer ignore-type */ EngineAdditions::uncoupleSelector ($value)) :
Loading history...
141
                $this->callMethod ('Insert', $index, EngineAdditions::uncoupleSelector ($value));
0 ignored issues
show
Unused Code introduced by
The call to VoidEngine\NetObject::callMethod() has too many arguments starting with VoidEngine\EngineAdditio...ncoupleSelector($value). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
                $this->/** @scrutinizer ignore-call */ 
142
                       callMethod ('Insert', $index, EngineAdditions::uncoupleSelector ($value));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
142
        }
143
144
        catch (\Throwable $e)
145
        {
146
            $index === null ?
147
                VoidCore::setArrayValue ($this->selector, $this->count, EngineAdditions::uncoupleSelector ($value)) :
148
                VoidCore::setArrayValue ($this->selector, $index, EngineAdditions::uncoupleSelector ($value));
149
        }
150
    }
151
	
152
	public function offsetGet ($index)
153
	{
154
		return EngineAdditions::coupleSelector (VoidCore::getArrayValue ($this->selector, $index), $this->selector);
0 ignored issues
show
Unused Code introduced by
The call to VoidEngine\EngineAdditions::coupleSelector() has too many arguments starting with $this->selector. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

154
		return EngineAdditions::/** @scrutinizer ignore-call */ coupleSelector (VoidCore::getArrayValue ($this->selector, $index), $this->selector);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
155
    }
156
	
157
	public function offsetUnset ($index): void
158
	{
159
		$this->callMethod ('RemoveAt', $index);
160
    }
161
    
162
    public function offsetExists ($index): bool
163
    {
164
        try
165
        {
166
            $this->offsetGet ($index);
167
        }
168
169
        catch (\WinformsException $e)
170
        {
171
            return false;
172
        }
173
174
        return true;
175
    }
176
177
    # Итерация массивов
178
179
    public function foreach (callable $callback, string $type = null): void
180
    {
181
        $size = $this->count;
182
183
        for ($i = 0; $i < $size; ++$i)
184
            $callback (EngineAdditions::coupleSelector (VoidCore::getArrayValue ($this->selector, $type !== null ? [$i, $type] : $i), $this->selector), $i);
0 ignored issues
show
Unused Code introduced by
The call to VoidEngine\EngineAdditions::coupleSelector() has too many arguments starting with $this->selector. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

184
            $callback (EngineAdditions::/** @scrutinizer ignore-call */ coupleSelector (VoidCore::getArrayValue ($this->selector, $type !== null ? [$i, $type] : $i), $this->selector), $i);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
185
    }
186
187
    public function where (callable $comparator, string $type = null): array
188
    {
189
        $size   = $this->count;
190
        $return = [];
191
192
        for ($i = 0; $i < $size; ++$i)
193
            if ($comparator ($value = EngineAdditions::coupleSelector (VoidCore::getArrayValue ($this->selector, $type !== null ? [$i, $type] : $i), $this->selector), $i))
0 ignored issues
show
Unused Code introduced by
The call to VoidEngine\EngineAdditions::coupleSelector() has too many arguments starting with $this->selector. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

193
            if ($comparator ($value = EngineAdditions::/** @scrutinizer ignore-call */ coupleSelector (VoidCore::getArrayValue ($this->selector, $type !== null ? [$i, $type] : $i), $this->selector), $i))

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
194
                $return[] = $value;
195
196
        return $return;
197
    }
198
199
    # Магические методы
200
201
    public function __destruct ()
202
    {
203
        VoidCore::destructObject ($this->selector);
204
    }
205
206
    public function __toString (): string
207
    {
208
        return $this->selector;
209
    }
210
211
    public function __debugInfo (): array
212
    {
213
        $info = ['selector' => $this->selector];
214
215
        try
216
        {
217
            $info['name'] = $this->getProperty ('Name');
218
        }
219
220
        catch (\WinformsException $e) {}
221
222
        try
223
        {
224
            $info['info'] = $this->callMethod ('ToString');
225
        }
226
227
        catch (\WinformsException $e) {}
228
229
        return $info;
230
    }
231
}
232
233
class NetClass extends NetObject
234
{
235
    public function __construct ($name, $assembly = false)
236
    {
237
        if (is_int ($name) && VoidCore::objectExists ($name))
238
            $this->selector = $name;
239
240
        elseif (is_string ($name))
241
            $this->selector = VoidCore::getClass ($name, $assembly);
242
243
        else throw new \Exception ('Incorrect params passed');
244
    }
245
}
246
247
class EngineAdditions
248
{
249
	/**
250
     * * Компиляция PHP кода
251
     * 
252
     * TODO: дополнить описание
253
     * 
254
     * @param string $savePath - путь для компиляции
255
     * @param string $iconPath - путь до иконки
256
     * @param string $phpCode - код для компиляции без тэгов
257
     * 
258
     * [@param string $productDescription = null] - описание приложения
259
     * [@param string $productName = null]        - название приложения
260
     * [@param string $productVersion = null]     - версия приложения
261
     * [@param string $companyName = null]        - компания-производителя
262
     * [@param string $copyright = null]          - копирайт
263
     * [@param string $callSharpCode = '']        - чистый C# код
264
     * [@param string $declareSharpCode = '']     - C# код с объявлениями классов
265
     * 
266
     * @return array - возвращает список ошибок компиляции
267
     */
268
    public static function compile (string $savePath, string $iconPath, string $phpCode, string $productDescription = null, string $productName = null, string $productVersion = null, string $companyName = null, string $copyright = null, string $callSharpCode = '', string $declareSharpCode = '', NetObject $dictionary = null, NetObject $assemblies = null): array
269
    {
270
        if ($dictionary === null)
271
            $dictionary = new NetObject ('System.Collections.Generic.Dictionary`2[System.String,System.String]', null);
272
273
        if ($assemblies === null)
274
            $assemblies = dnArray ('System.String', []);
275
276
        if ($productName === null)
277
            $productName = basenameNoExt ($savePath);
278
279
        if ($productDescription === null)
280
            $productDescription = $productName;
281
282
        if ($productVersion === null)
283
            $productVersion = '1.0';
284
285
        if ($companyName === null)
286
            $companyName = 'Company N';
287
288
        if ($copyright === null)
289
            $copyright = $companyName .' copyright (c) '. date ('Y');
290
291
        return (new NetClass ('WinForms_PHP.WFCompiler', null))->compile ($savePath, $iconPath, $phpCode, $productDescription, $productName, $productVersion, $companyName, $copyright, $callSharpCode, $declareSharpCode, $dictionary, $assemblies)->names;
292
    }
293
294
    public static function loadModule (string $path): bool
295
    {
296
        try
297
        {
298
            (new NetClass ('System.Reflection.Assembly', 'mscorlib'))->loadFrom ($path);
299
        }
300
301
        catch (\WinformsException $e)
302
        {
303
            return false;
304
        }
305
306
        return true;
307
    }
308
	
309
    public static function coupleSelector ($selector)
310
    {
311
        return is_int ($selector) && VoidCore::objectExists ($selector) ?
312
            new NetObject ($selector) : $selector;
313
    }
314
315
    public static function uncoupleSelector ($object)
316
    {
317
        return is_object ($object) && $object instanceof NetObject ?
318
            $object->selector : $object;
319
    }
320
}
321