yoda_style.rst 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. ===================
  2. Rule ``yoda_style``
  3. ===================
  4. Write conditions in Yoda style (``true``), non-Yoda style (``['equal' => false,
  5. 'identical' => false, 'less_and_greater' => false]``) or ignore those conditions
  6. (``null``) based on configuration.
  7. Configuration
  8. -------------
  9. ``equal``
  10. ~~~~~~~~~
  11. Style for equal (``==``, ``!=``) statements.
  12. Allowed types: ``bool`` and ``null``
  13. Default value: ``true``
  14. ``identical``
  15. ~~~~~~~~~~~~~
  16. Style for identical (``===``, ``!==``) statements.
  17. Allowed types: ``bool`` and ``null``
  18. Default value: ``true``
  19. ``less_and_greater``
  20. ~~~~~~~~~~~~~~~~~~~~
  21. Style for less and greater than (``<``, ``<=``, ``>``, ``>=``) statements.
  22. Allowed types: ``bool`` and ``null``
  23. Default value: ``null``
  24. ``always_move_variable``
  25. ~~~~~~~~~~~~~~~~~~~~~~~~
  26. Whether variables should always be on non assignable side when applying Yoda
  27. style.
  28. Allowed types: ``bool``
  29. Default value: ``false``
  30. Examples
  31. --------
  32. Example #1
  33. ~~~~~~~~~~
  34. *Default* configuration.
  35. .. code-block:: diff
  36. --- Original
  37. +++ New
  38. <?php
  39. - if ($a === null) {
  40. + if (null === $a) {
  41. echo "null";
  42. }
  43. Example #2
  44. ~~~~~~~~~~
  45. With configuration: ``['equal' => true, 'identical' => false, 'less_and_greater' => null]``.
  46. .. code-block:: diff
  47. --- Original
  48. +++ New
  49. <?php
  50. - $b = $c != 1; // equal
  51. - $a = 1 === $b; // identical
  52. + $b = 1 != $c; // equal
  53. + $a = $b === 1; // identical
  54. $c = $c > 3; // less than
  55. Example #3
  56. ~~~~~~~~~~
  57. With configuration: ``['always_move_variable' => true]``.
  58. .. code-block:: diff
  59. --- Original
  60. +++ New
  61. <?php
  62. -return $foo === count($bar);
  63. +return count($bar) === $foo;
  64. Example #4
  65. ~~~~~~~~~~
  66. With configuration: ``['equal' => false, 'identical' => false, 'less_and_greater' => false]``.
  67. .. code-block:: diff
  68. --- Original
  69. +++ New
  70. <?php
  71. // Enforce non-Yoda style.
  72. - if (null === $a) {
  73. + if ($a === null) {
  74. echo "null";
  75. }
  76. Rule sets
  77. ---------
  78. The rule is part of the following rule sets:
  79. - `@PhpCsFixer <./../../ruleSets/PhpCsFixer.rst>`_
  80. - `@Symfony <./../../ruleSets/Symfony.rst>`_