forked from clbustos/PHP_Beautifier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBeautifier.php
executable file
·1823 lines (1740 loc) · 50.1 KB
/
Beautifier.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Contents Php_Beautifier class and make some tests
*
* PHP version 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright 2004-2010 Claudio Bustos
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id:$
* @link http://pear.php.net/package/PHP_Beautifier
* @link http://beautifyphp.sourceforge.net
*/
error_reporting(E_ALL);
// Before all, test the tokenizer extension
if (!extension_loaded('tokenizer')) {
throw new Exception("Compile php with tokenizer extension. Use --enable-tokenizer or don't use --disable-all on configure.");
}
require_once 'PEAR.php';
require_once 'PEAR/Exception.php';
/**
* Require PHP_Beautifier_Filter
*/
require_once 'Beautifier/Filter.php';
/**
* Require PHP_Beautifier_Filter_Default
*/
require_once 'Beautifier/Filter/Default.filter.php';
/**
* Require PHP_Beautifier_Common
*/
require_once 'Beautifier/Common.php';
/**
* Require Log
*/
require_once 'Log.php';
/**
* Require Exceptions
*/
require_once 'Beautifier/Exception.php';
/**
* Require StreamWrapper
*/
require_once 'Beautifier/StreamWrapper.php';
/**
* PHP_Beautifier
*
* Class to beautify php code
* How to use:
* # Create a instance of the object
* # Define the input and output files
* # Optional: Set one or more Filter. They are processed in LIFO order (last in, first out)
* # Process the file
* # Get it, save it or show it.
*
* <code>
* $oToken = new PHP_Beautifier(); // create a instance
* $oToken->addFilter('ArraySimple');
* $oToken->addFilter('ListClassFunction'); // add one or more filters
* $oToken->setInputFile(__FILE__); // nice... process the same file
* $oToken->process(); // required
* $oToken->show();
* </code>
*
* @todo create a web interface.
* @category PHP
* @package PHP_Beautifier
* @author Claudio Bustos <cdx@users.sourceforge.com>
* @copyright 2004-2010 Claudio Bustos
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_Beautifier
* @link http://beautifyphp.sourceforge.net
*/
class PHP_Beautifier implements PHP_Beautifier_Interface
{
// public
/**
* Tokens created by the tokenizer
* @var array
*/
public $aTokens = array();
/**
* Tokens codes assigned to method on Filter
* @var array
*/
public $aTokenFunctions = array();
/**
* Token Names
* @var array
*/
public $aTokenNames = Array();
/**
* Stores the output
* @var array
*/
public $aOut = array();
/**
* Contains the assigment of modes
* @var array
* @see setMode()
* @see unsetMode()
* @see getMode()
*/
public $aModes = array();
/**
* List of availables modes
* @var array
*/
public $aModesAvailable = array(
'ternary_operator',
'double_quote'
);
/**
* Settings for the class
* @var array
*/
public $aSettings = array();
/**
* Index of current token
* @var int
*/
public $iCount = 0;
/**
* Chars for indentation
* @var int
*/
public $iIndentNumber = 4;
/**
* Level of array nesting
* @var int
*/
public $iArray = 0;
/**
* Level of ternary operator nesting
* @var int
*/
public $iTernary = 0;
/**
* Level of parenthesis nesting
* @var int
*/
public $iParenthesis = 0;
/**
* Level of verbosity (debug)
* @var int
*/
public $iVerbose = false;
/**
* Name of input file
* @var string
*/
public $sInputFile = '';
/**
* Name of output file
* @var string
*/
public $sOutputFile = '';
/**
* Type of newline
* @var string
*/
public $sNewLine = PHP_EOL;
/**
* Type of whitespace to use for indent
* @var string
*/
public $sIndentChar = ' ';
/**
* Save the last whitespace used. Use only for Filter! (i miss friends of C++ :( )
* @var string
*/
public $currentWhitespace = '';
/**
* Association $aTokens=>$aOut
* @var array
*/
public $aAssocs = array();
/**
* Current token. Could be changed by a filter (See Lowercase)
* @var array
*/
public $aCurrentToken = array();
// private
/**
* type of file
*/
private $sFileType = 'php';
/**
* Chars of indent
* @var int
*/
private $iIndent = 0;
/**
* @var int
*/
private $aIndentStack = array();
/** Text to beautify */
private $sText = '';
/** Constant for last Control */
private $iControlLast;
/** References to PHP_Beautifier_Filter's */
private $aFilters = array();
/**
* Stack with control construct
*/
private $aControlSeq = array();
/**
* List of construct that start control structures
*/
private $aControlStructures = array();
/**
* List of Control for parenthesis
*/
private $aControlParenthesis = array();
/**
* List of construct that end control structures
*/
private $aControlStructuresEnd = array();
/** Dirs for Filters */
private $aFilterDirs = array();
/** Flag for beautify/no beautify mode */
private $bBeautify = true;
/** Log */
private $oLog;
/** Before new line holder */
private $sBeforeNewLine = null;
/** Activate or deactivate 'no delete previous space' */
private $bNdps = false;
/** Mark the begin of the end of a DoWhile sequence **/
private $doWhileBeginEnd;
// Methods
/**
* Constructor.
* Assing values to {@link $aControlStructures},{@link $aControlStructuresEnd},
* {@link $aTokenFunctions}
*
* @access public
* @return void
*/
public function __construct()
{
$this->aControlStructures = array(
T_CLASS,
T_FUNCTION,
T_IF,
T_ELSE,
T_ELSEIF,
T_WHILE,
T_DO,
T_FOR,
T_FOREACH,
T_SWITCH,
T_DECLARE,
T_TRY,
T_CATCH
);
$this->aControlStructuresEnd = array(
T_ENDWHILE,
T_ENDFOREACH,
T_ENDFOR,
T_ENDDECLARE,
T_ENDSWITCH,
T_ENDIF
);
$aPreTokens = preg_grep('/^T_/', array_keys(get_defined_constants()));
foreach ($aPreTokens as $sToken) {
$this->aTokenNames[constant($sToken) ] = $sToken;
$this->aTokenFunctions[constant($sToken) ] = $sToken;
}
if (!defined('T_NAMESPACE')) { // like pre 5.3.0
define('T_NAMESPACE', 377);
}
$aTokensToChange = array(
/* QUOTES */
'"' => "T_DOUBLE_QUOTE",
"'" => "T_SINGLE_QUOTE",
/* PUNCTUATION */
'(' => 'T_PARENTHESIS_OPEN',
')' => 'T_PARENTHESIS_CLOSE',
';' => 'T_SEMI_COLON',
'{' => 'T_OPEN_BRACE',
'}' => 'T_CLOSE_BRACE',
',' => 'T_COMMA',
'?' => 'T_QUESTION',
':' => 'T_COLON',
'=' => 'T_ASSIGMENT',
'<' => 'T_EQUAL',
'>' => 'T_EQUAL',
'.' => 'T_DOT',
'[' => 'T_OPEN_SQUARE_BRACE',
']' => 'T_CLOSE_SQUARE_BRACE',
/* OPERATOR*/
'+' => 'T_OPERATOR',
'-' => 'T_OPERATOR',
'*' => 'T_OPERATOR',
'/' => 'T_OPERATOR',
'%' => 'T_OPERATOR',
'&' => 'T_OPERATOR',
'|' => 'T_OPERATOR',
'^' => 'T_OPERATOR',
'~' => 'T_OPERATOR',
'!' => 'T_OPERATOR_NEGATION',
T_SL => 'T_OPERATOR',
T_SR => 'T_OPERATOR',
T_OBJECT_OPERATOR => 'T_OBJECT_OPERATOR',
/* INCLUDE */
T_INCLUDE => 'T_INCLUDE',
T_INCLUDE_ONCE => 'T_INCLUDE',
T_REQUIRE => 'T_INCLUDE',
T_REQUIRE_ONCE => 'T_INCLUDE',
/* LANGUAGE CONSTRUCT */
T_FUNCTION => 'T_LANGUAGE_CONSTRUCT',
T_PRINT => 'T_LANGUAGE_CONSTRUCT',
T_RETURN => 'T_LANGUAGE_CONSTRUCT',
T_ECHO => 'T_LANGUAGE_CONSTRUCT',
T_NEW => 'T_LANGUAGE_CONSTRUCT',
T_CLASS => 'T_LANGUAGE_CONSTRUCT',
T_VAR => 'T_LANGUAGE_CONSTRUCT',
T_GLOBAL => 'T_LANGUAGE_CONSTRUCT',
T_THROW => 'T_LANGUAGE_CONSTRUCT',
/* CONTROL */
T_IF => 'T_CONTROL',
T_DO => 'T_CONTROL',
T_WHILE => 'T_CONTROL',
T_SWITCH => 'T_CONTROL',
/* ELSE */
T_ELSEIF => 'T_ELSE',
T_ELSE => 'T_ELSE',
/* ACCESS PHP 5 */
T_INTERFACE => 'T_ACCESS',
T_FINAL => 'T_ACCESS',
T_ABSTRACT => 'T_ACCESS',
T_PRIVATE => 'T_ACCESS',
T_PUBLIC => 'T_ACCESS',
T_PROTECTED => 'T_ACCESS',
T_CONST => 'T_ACCESS',
T_STATIC => 'T_ACCESS',
/* COMPARATORS */
T_PLUS_EQUAL => 'T_ASSIGMENT_PRE',
T_MINUS_EQUAL => 'T_ASSIGMENT_PRE',
T_MUL_EQUAL => 'T_ASSIGMENT_PRE',
T_DIV_EQUAL => 'T_ASSIGMENT_PRE',
T_CONCAT_EQUAL => 'T_ASSIGMENT_PRE',
T_MOD_EQUAL => 'T_ASSIGMENT_PRE',
T_AND_EQUAL => 'T_ASSIGMENT_PRE',
T_OR_EQUAL => 'T_ASSIGMENT_PRE',
T_XOR_EQUAL => 'T_ASSIGMENT_PRE',
T_DOUBLE_ARROW => 'T_ASSIGMENT',
T_SL_EQUAL => 'T_EQUAL',
T_SR_EQUAL => 'T_EQUAL',
T_IS_EQUAL => 'T_EQUAL',
T_IS_NOT_EQUAL => 'T_EQUAL',
T_IS_IDENTICAL => 'T_EQUAL',
T_IS_NOT_IDENTICAL => 'T_EQUAL',
T_IS_SMALLER_OR_EQUAL => 'T_EQUAL',
T_IS_GREATER_OR_EQUAL => 'T_EQUAL',
/* LOGICAL*/
T_LOGICAL_OR => 'T_LOGICAL',
T_LOGICAL_XOR => 'T_LOGICAL',
T_LOGICAL_AND => 'T_LOGICAL',
T_BOOLEAN_OR => 'T_LOGICAL',
T_BOOLEAN_AND => 'T_LOGICAL',
/* SUFIX END */
T_ENDWHILE => 'T_END_SUFFIX',
T_ENDFOREACH => 'T_END_SUFFIX',
T_ENDFOR => 'T_END_SUFFIX',
T_ENDDECLARE => 'T_END_SUFFIX',
T_ENDSWITCH => 'T_END_SUFFIX',
T_ENDIF => 'T_END_SUFFIX',
);
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
$aTokensToChange[T_NAMESPACE] = 'T_INCLUDE';
$aTokensToChange[T_USE] = 'T_INCLUDE';
}
foreach ($aTokensToChange as $iToken => $sFunction) {
$this->aTokenFunctions[$iToken] = $sFunction;
}
$this->addFilterDirectory(dirname(__FILE__) . '/Beautifier/Filter');
$this->addFilter('Default');
$this->oLog = PHP_Beautifier_Common::getLog();
}
/**
* getTokenName
*
* @param mixed $iToken Token
*
* @access public
* @return void
*/
public function getTokenName($iToken)
{
if (!$iToken) {
throw new Exception("Token $iToken doesn't exists");
}
return $this->aTokenNames[$iToken];
}
/**
* Start the log for debug
*
* @param string $sFile Filename
* @param mixed $iLevel Debug Level. See {$link Log}
*
* @access public
* @return void
*/
public function startLog($sFile = 'php_beautifier.log', $iLevel = PEAR_LOG_DEBUG)
{
@unlink($sFile);
$oLogFile = Log::factory('file', $sFile, 'php_beautifier', array(), PEAR_LOG_DEBUG);
$this->oLog->addChild($oLogFile);
}
/**
* Add a filter directory
*
* @param mixed $sDir Paht to directory
*
* @access public
* @return void
* @throws Exception
*/
public function addFilterDirectory($sDir)
{
$sDir = PHP_Beautifier_Common::normalizeDir($sDir);
if (file_exists($sDir)) {
array_push($this->aFilterDirs, $sDir);
} else {
throw new Exception_PHP_Beautifier_Filter("Path '$sDir' doesn't exists");
}
}
/**
* Return an array with all the Filter Dirs
*
* @access public
* @return array List of Filter Directories
*/
public function getFilterDirectories()
{
return $this->aFilterDirs;
}
/**
* addFilterObject
*
* @param PHP_Beautifier_Filter $oFilter PHP_Beautifier_Filter Object
*
* @access public
* @return void
*/
public function addFilterObject(PHP_Beautifier_Filter $oFilter)
{
array_unshift($this->aFilters, $oFilter);
return true;
}
/**
* Add a Filter to the Beautifier
* The first argument is the name of the file of the Filter.
*
* @param mixed $mFilter Name of the Filter
* @param array $aSettings Settings for the Filter
*
* @tutorial PHP_Beautifier/Filter/Filter2.pkg#use
* @access public
* @return bool true if Filter is loaded, false if the same filter was loaded previously
* @throws Exception
*/
public function addFilter($mFilter, $aSettings = array())
{
if ($mFilter instanceOf PHP_Beautifier_Filter) {
return $this->addFilterObject($mFilter);
}
$sFilterClass = 'PHP_Beautifier_Filter_' . $mFilter;
if (!class_exists($sFilterClass)) {
$this->addFilterFile($mFilter);
}
$oTemp = new $sFilterClass($this, $aSettings);
// verify if same Filter is loaded
if (in_array($oTemp, $this->aFilters, true)) {
return false;
} elseif ($oTemp instanceof PHP_Beautifier_Filter) {
$this->addFilterObject($oTemp);
} else {
throw new Exception_PHP_Beautifier_Filter("'$sFilterClass' isn't a subclass of 'Filter'");
}
}
/**
* Removes a Filter
*
* @param mixed $sFilter Name of the Filter
*
* @access public
* @return bool true if Filter is removed, false otherwise
*/
public function removeFilter($sFilter)
{
$sFilterName = strtolower('PHP_Beautifier_Filter_' . $sFilter);
foreach ($this->aFilters as $sId => $oFilter) {
if (strtolower(get_class($oFilter)) == $sFilterName) {
unset($this->aFilters[$sId]);
return true;
}
}
return false;
}
/**
* Return the Filter Description
*
* @param mixed $sFilter Name of the filter
*
* @access public
* @return mixed string or false
* @see PHP_Beautifier_Filter::__toString();
*/
public function getFilterDescription($sFilter)
{
$aFilters = $this->getFilterListTotal();
if (in_array($sFilter, $aFilters)) {
$this->addFilterFile($sFilter);
$sFilterClass = 'PHP_Beautifier_Filter_' . $sFilter;
$oTemp = new $sFilterClass($this, array());
return $oTemp;
} else {
return false;
}
}
/**
* Add a new filter to the processor.
* The system will process the filter in LIFO order
*
* @param mixed $sFilter Name of the filter
*
* @access private
* @see process()
* @return bool
* @throws Exception
*/
private function addFilterFile($sFilter)
{
$sFilterClass = 'PHP_Beautifier_Filter_' . $sFilter;
if (class_exists($sFilterClass)) {
return true;
}
foreach ($this->aFilterDirs as $sDir) {
$sFile = $sDir . $sFilter . '.filter.php';
if (file_exists($sFile)) {
include_once $sFile;
if (class_exists($sFilterClass)) {
return true;
} else {
throw new Exception_PHP_Beautifier_Filter("File '$sFile' exists,but doesn't exists filter '$sFilterClass'");
}
}
}
throw new Exception_PHP_Beautifier_Filter("Doesn't exists filter '$sFilter'");
}
/**
* Get the names of the loaded filters
*
* @access public
* @return array list of Filters
*/
public function getFilterList()
{
foreach ($this->aFilters as $oFilter) {
$aOut[] = $oFilter->getName();
}
return $aOut;
}
/**
* Get the list of all available Filters in all the include Dirs
*
* @access public
* @return array list of Filters
*/
public function getFilterListTotal()
{
$aFilterFiles = array();
foreach ($this->aFilterDirs as $sDir) {
$aFiles = PHP_Beautifier_Common::getFilesByPattern($sDir, ".*?\.filter\.php");
array_walk(
$aFiles,
array(
$this,
'getFilterList_FilterName'
)
);
$aFilterFiles = array_merge($aFilterFiles, $aFiles);
}
sort($aFilterFiles);
return $aFilterFiles;
}
/**
* Receive a path to a filter and replace it with the name of filter
*
* @param mixed &$sFile File name
*
* @access private
* @return void
*/
private function getFilterList_FilterName(&$sFile)
{
$aMatch=array();
preg_match("/\/([^\/]*?)\.filter\.php/", $sFile, $aMatch);
$sFile = $aMatch[1];
}
/**
* getIndentChar
*
* @access public
* @return void
*/
public function getIndentChar()
{
return $this->sIndentChar;
}
/**
* getIndentNumber
*
* @access public
* @return void
*/
public function getIndentNumber()
{
return $this->iIndentNumber;
}
/**
* getIndent
*
* @access public
* @return void
*/
public function getIndent()
{
return $this->iIndent;
}
/**
* getNewLine
*
* @access public
* @return void
*/
public function getNewLine()
{
return $this->sNewLine;
}
/**
* Character used for indentation
*
* @param string $sChar Usually ' ' or "\t"
*
* @access public
* @return void
*/
public function setIndentChar($sChar)
{
$this->sIndentChar = $sChar;
}
/**
* Number of characters for indentation
*
* @param int $iIndentNumber Usually 4 for space or 1 for tabs
*
* @access public
* @return void
*/
public function setIndentNumber($iIndentNumber)
{
$this->iIndentNumber = $iIndentNumber;
}
/**
* Character used as a new line
*
* @param string $sNewLine ussualy "\n", "\r\n" or "\r"
*
* @access public
* @return void
*/
public function setNewLine($sNewLine)
{
$this->sNewLine = $sNewLine;
}
/**
* Set the file for beautify
*
* @param string $sFile Path to file
*
* @access public
* @return void
* @throws Exception
*/
public function setInputFile($sFile)
{
$bCli = (php_sapi_name() == 'cli');
if (strpos($sFile, '://') === false and !file_exists($sFile) and !($bCli and $sFile == STDIN)) {
throw new Exception("File '$sFile' doesn't exists");
}
$this->sText = '';
$this->sInputFile = $sFile;
$fp = ($bCli and $sFile == STDIN) ? STDIN : fopen($sFile, 'r');
do {
$data = fread($fp, 8192);
if (strlen($data) == 0) {
break;
}
$this->sText.= $data;
} while (true);
if (!($bCli and $fp == STDIN)) {
fclose($fp);
}
return true;
}
/**
* Set the output file for beautify
*
* @param string $sFile Path to file
*
* @access public
* @return void
*/
public function setOutputFile($sFile)
{
$this->sOutputFile = $sFile;
}
/**
* Save the beautified code to output file
*
* @param string $sFile path to file. If null, {@link $sOutputFile} if exists, throw exception otherwise
*
* @access public
* @return void
* @see setOutputFile();
* @throws Exception
*/
public function save($sFile = null)
{
$bCli = (php_sapi_name() == 'cli');
if (!$sFile) {
if (!$this->sOutputFile) {
throw new Exception("Can't save without a output file");
} else {
$sFile = $this->sOutputFile;
}
}
$sText = $this->get();
$fp = ($bCli and $sFile == STDOUT) ? STDOUT : @fopen($sFile, "w");
if (!$fp) {
throw new Exception("Can't save file $sFile");
}
fputs($fp, $sText, strlen($sText));
if (!($bCli and $sFile == STDOUT)) {
fclose($fp);
}
$this->oLog->log("Success: $sFile saved", PEAR_LOG_INFO);
return true;
}
/**
* Set a string for beautify
*
* @param string $sText Must be preceded by open tag
*
* @access public
* @return void
*/
public function setInputString($sText)
{
$this->sText = $sText;
}
/**
* Reset all properties
*
* @access private
* @return void
*/
private function resetProperties()
{
$aProperties = array(
'aTokens' => array() ,
'aOut' => array() ,
'aModes' => array() ,
'iCount' => 0,
'iIndent' => 0
/*$this->iIndentNumber*/
,
'aIndentStack' => array(
/*$this->iIndentNumber*/
) ,
'iArray' => 0,
'iParenthesis' => 0,
'currentWhitespace' => '',
'aAssocs' => array() ,
'iControlLast' => null,
'aControlSeq' => array() ,
'bBeautify' => true
);
foreach ($aProperties as $sProperty => $sValue) {
$this->$sProperty = $sValue;
}
}
/**
* Process the string or file to beautify
*
* @access public
* @return bool true on success
* @throws Exception
*/
public function process()
{
$this->oLog->log('Init process of ' . (($this->sInputFile) ? 'file ' . $this->sInputFile : 'string'), PEAR_LOG_DEBUG);
$this->resetProperties();
// if file type is php, use token_get_all
// else, use a class named PHP_Beautifier_Tokenizer_XXX
// instanced with the text and get the tokens with
// getTokens()
if ($this->sFileType == 'php') {
$this->aTokens = token_get_all($this->sText);
} else {
$sClass = 'PHP_Beautifier_Tokenizer_' . ucfirst($this->sFileType);
if (class_exists($sClass)) {
$oTokenizer = new $sClass($this->sText);
$this->aTokens = $oTokenizer->getTokens();
} else {
throw new Exception("File type " . $this->sFileType . " not implemented");
}
}
$this->aOut = array();
$iTotal = count($this->aTokens);
$iPrevAssoc = false;
// Send a signal to the filter, announcing the init of the processing of a file
foreach ($this->aFilters as $oFilter) {
$oFilter->preProcess();
}
for ($this->iCount = 0 ; $this->iCount < $iTotal ; $this->iCount++) {
$aCurrentToken = $this->aTokens[$this->iCount];
if (is_string($aCurrentToken)) {
$aCurrentToken = array(
0 => $aCurrentToken,
1 => $aCurrentToken
);
}
// ArrayNested->off();
$sTextLog = PHP_Beautifier_Common::wsToString($aCurrentToken[1]);
// ArrayNested->on();
$sTokenName = (is_numeric($aCurrentToken[0])) ? token_name($aCurrentToken[0]) : '';
$this->oLog->log("Token:" . $sTokenName . "[" . $sTextLog . "]", PEAR_LOG_DEBUG);
$this->controlToken($aCurrentToken);
$iFirstOut = count($this->aOut); //5
$bError = false;
$this->aCurrentToken=$aCurrentToken;
if ($this->bBeautify) {
foreach ($this->aFilters as $oFilter) {
$bError = true;
if ($oFilter->handleToken($this->aCurrentToken) !== false) {
$this->oLog->log('Filter:' . $oFilter->getName(), PEAR_LOG_DEBUG);
$bError = false;
break;
}
}
} else {
$this->add($aCurrentToken[1]);
}
$this->controlTokenPost($aCurrentToken);
$iLastOut = count($this->aOut);
// set the assoc
if (($iLastOut-$iFirstOut) > 0) {
$this->aAssocs[$this->iCount] = array(
'offset' => $iFirstOut
);
if ($iPrevAssoc !== false) {
$this->aAssocs[$iPrevAssoc]['length'] = $iFirstOut-$this->aAssocs[$iPrevAssoc]['offset'];
}
$iPrevAssoc = $this->iCount;
}
if ($bError) {
throw new Exception("Can'process token: " . var_dump($aCurrentToken));
}
} // ~for
// generate the last assoc
if (count($this->aOut) == 0) {
if ($this->sFile) {
throw new Exception("Nothing on output for " . $this->sFile . "!");
} else {
throw new Exception("Nothing on output!");
}
}
$this->aAssocs[$iPrevAssoc]['length'] = (count($this->aOut) -1) -$this->aAssocs[$iPrevAssoc]['offset'];
// Post-processing
foreach ($this->aFilters as $oFilter) {
$oFilter->postProcess();
}
$this->oLog->log('End process', PEAR_LOG_DEBUG);
return true;
}
/**
* Get the reference to {@link $aOut}, based on the number of the token
*
* @param int $iIndex Token number
*
* @access public
* @return mixed false array or false if token doesn't exists
*/
public function getTokenAssoc($iIndex)
{
return (array_key_exists($iIndex, $this->aAssocs)) ? $this->aAssocs[$iIndex] : false;
}
/**
* Get the output for the specified token
*
* @param int $iIndex Token number
*
* @access public
* @return mixed string or false if token doesn't exists
*/
public function getTokenAssocText($iIndex)
{
if (!($aAssoc = $this->getTokenAssoc($iIndex))) {
return false;
}
return (implode('', array_slice($this->aOut, $aAssoc['offset'], $aAssoc['length'])));
}
/**
* Replace the output for specified token
*
* @param int $iIndex Token Number
* @param string $sText Replace text
*
* @access public
* @return bool
*/
public function replaceTokenAssoc($iIndex, $sText)
{
if (!($aAssoc = $this->getTokenAssoc($iIndex))) {
return false;
}
$this->aOut[$aAssoc['offset']] = $sText;
for ($x = 0 ; $x < $aAssoc['length']-1 ; $x++) {
$this->aOut[$aAssoc['offset']+$x+1] = '';
}
return true;
}
/**
* Return the function for a token constant or string.
*
* @param mixed $sTokenType Token constant or string
*
* @access public
* @return mixed name of function or false
*/
public function getTokenFunction($sTokenType)
{
return (array_key_exists($sTokenType, $this->aTokenFunctions)) ? strtolower($this->aTokenFunctions[$sTokenType]) : false;
}
/**
* Process a callback from the code to beautify
*
* @param array $aMatch third parameter from preg_match
*
* @access private
* @return bool
* @uses controlToken()
*/
private function processCallback($aMatch)
{
if (stristr('php_beautifier', $aMatch[1]) and method_exists($this, $aMatch[3])) {
if (preg_match("/^(set|add)/i", $aMatch[3]) and !stristr('file', $aMatch[3])) {